@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,146 +1,146 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cometCreateRequire } from 'module';
3
3
  const require = __cometCreateRequire(import.meta.url);
4
- var Pm=Object.create;var Cl=Object.defineProperty;var Cm=Object.getOwnPropertyDescriptor;var Rm=Object.getOwnPropertyNames;var Am=Object.getPrototypeOf,_m=Object.prototype.hasOwnProperty;var tn=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var b=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var Im=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Rm(t))!_m.call(e,n)&&n!==r&&Cl(e,n,{get:()=>t[n],enumerable:!(i=Cm(t,n))||i.enumerable});return e};var Hr=(e,t,r)=>(r=e!=null?Pm(Am(e)):{},Im(t||!e||!e.__esModule?Cl(r,"default",{value:e,enumerable:!0}):r,e));var R=b(te=>{"use strict";var go=Symbol.for("yaml.alias"),Rl=Symbol.for("yaml.document"),rn=Symbol.for("yaml.map"),Al=Symbol.for("yaml.pair"),wo=Symbol.for("yaml.scalar"),nn=Symbol.for("yaml.seq"),it=Symbol.for("yaml.node.type"),Tm=e=>!!e&&typeof e=="object"&&e[it]===go,jm=e=>!!e&&typeof e=="object"&&e[it]===Rl,$m=e=>!!e&&typeof e=="object"&&e[it]===rn,Om=e=>!!e&&typeof e=="object"&&e[it]===Al,_l=e=>!!e&&typeof e=="object"&&e[it]===wo,Hm=e=>!!e&&typeof e=="object"&&e[it]===nn;function Il(e){if(e&&typeof e=="object")switch(e[it]){case rn:case nn:return!0}return!1}function Dm(e){if(e&&typeof e=="object")switch(e[it]){case go:case rn:case wo:case nn:return!0}return!1}var Bm=e=>(_l(e)||Il(e))&&!!e.anchor;te.ALIAS=go;te.DOC=Rl;te.MAP=rn;te.NODE_TYPE=it;te.PAIR=Al;te.SCALAR=wo;te.SEQ=nn;te.hasAnchor=Bm;te.isAlias=Tm;te.isCollection=Il;te.isDocument=jm;te.isMap=$m;te.isNode=Dm;te.isPair=Om;te.isScalar=_l;te.isSeq=Hm});var Dr=b(yo=>{"use strict";var z=R(),fe=Symbol("break visit"),Tl=Symbol("skip children"),qe=Symbol("remove node");function an(e,t){let r=jl(t);z.isDocument(e)?rr(null,e.contents,r,Object.freeze([e]))===qe&&(e.contents=null):rr(null,e,r,Object.freeze([]))}an.BREAK=fe;an.SKIP=Tl;an.REMOVE=qe;function rr(e,t,r,i){let n=$l(e,t,r,i);if(z.isNode(n)||z.isPair(n))return Ol(e,i,n),rr(e,n,r,i);if(typeof n!="symbol"){if(z.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=rr(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===fe)return fe;o===qe&&(t.items.splice(a,1),a-=1)}}}else if(z.isPair(t)){i=Object.freeze(i.concat(t));let a=rr("key",t.key,r,i);if(a===fe)return fe;a===qe&&(t.key=null);let o=rr("value",t.value,r,i);if(o===fe)return fe;o===qe&&(t.value=null)}}return n}async function on(e,t){let r=jl(t);z.isDocument(e)?await ir(null,e.contents,r,Object.freeze([e]))===qe&&(e.contents=null):await ir(null,e,r,Object.freeze([]))}on.BREAK=fe;on.SKIP=Tl;on.REMOVE=qe;async function ir(e,t,r,i){let n=await $l(e,t,r,i);if(z.isNode(n)||z.isPair(n))return Ol(e,i,n),ir(e,n,r,i);if(typeof n!="symbol"){if(z.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await ir(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===fe)return fe;o===qe&&(t.items.splice(a,1),a-=1)}}}else if(z.isPair(t)){i=Object.freeze(i.concat(t));let a=await ir("key",t.key,r,i);if(a===fe)return fe;a===qe&&(t.key=null);let o=await ir("value",t.value,r,i);if(o===fe)return fe;o===qe&&(t.value=null)}}return n}function jl(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 $l(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(z.isMap(t))return r.Map?.(e,t,i);if(z.isSeq(t))return r.Seq?.(e,t,i);if(z.isPair(t))return r.Pair?.(e,t,i);if(z.isScalar(t))return r.Scalar?.(e,t,i);if(z.isAlias(t))return r.Alias?.(e,t,i)}function Ol(e,t,r){let i=t[t.length-1];if(z.isCollection(i))i.items[e]=r;else if(z.isPair(i))e==="key"?i.key=r:i.value=r;else if(z.isDocument(i))i.contents=r;else{let n=z.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}yo.visit=an;yo.visitAsync=on});var No=b(Dl=>{"use strict";var Hl=R(),Lm=Dr(),Vm={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Mm=e=>e.replace(/[!,[\]{}]/g,t=>Vm[t]),Br=class e{constructor(t,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,r)}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,r){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let i=t.trim().split(/[ \t]+/),n=i.shift();switch(n){case"%TAG":{if(i.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[a,o]=i;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;let[a]=i;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return r(6,`Unsupported YAML version ${a}`,o),!1}}default:return r(0,`Unknown directive ${n}`,!0),!1}}tagName(t,r){if(t==="!")return"!";if(t[0]!=="!")return r(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}let[,i,n]=t.match(/^(.*!)([^!]*)$/s);n||r(`The ${t} tag has no suffix`);let a=this.tags[i];if(a)try{return a+decodeURIComponent(n)}catch(o){return r(String(o)),null}return i==="!"?t:(r(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[r,i]of Object.entries(this.tags))if(t.startsWith(i))return r+Mm(t.substring(i.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),n;if(t&&i.length>0&&Hl.isNode(t.contents)){let a={};Lm.visit(t.contents,(o,s)=>{Hl.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of i)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&r.push(`%TAG ${a} ${o}`);return r.join(`
5
- `)}};Br.defaultYaml={explicit:!1,version:"1.2"};Br.defaultTags={"!!":"tag:yaml.org,2002:"};Dl.Directives=Br});var sn=b(Lr=>{"use strict";var Bl=R(),Fm=Dr();function qm(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(r)}return!0}function Ll(e){let t=new Set;return Fm.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function Vl(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function Wm(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=Ll(e));let o=Vl(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(Bl.isScalar(o.node)||Bl.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:i}}Lr.anchorIsValid=qm;Lr.anchorNames=Ll;Lr.createNodeAnchors=Wm;Lr.findNewAnchor=Vl});var bo=b(Ml=>{"use strict";function Vr(e,t,r,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let n=0,a=i.length;n<a;++n){let o=i[n],s=Vr(e,i,String(n),o);s===void 0?delete i[n]:s!==o&&(i[n]=s)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let a=i.get(n),o=Vr(e,i,n,a);o===void 0?i.delete(n):o!==a&&i.set(n,o)}else if(i instanceof Set)for(let n of Array.from(i)){let a=Vr(e,i,n,n);a===void 0?i.delete(n):a!==n&&(i.delete(n),i.add(a))}else for(let[n,a]of Object.entries(i)){let o=Vr(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}Ml.applyReviver=Vr});var mt=b(ql=>{"use strict";var zm=R();function Fl(e,t,r){if(Array.isArray(e))return e.map((i,n)=>Fl(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!zm.hasAnchor(e))return e.toJSON(t,r);let i={aliasCount:0,count:1,res:void 0};r.anchors.set(e,i),r.onCreate=a=>{i.res=a,delete r.onCreate};let n=e.toJSON(t,r);return r.onCreate&&r.onCreate(n),n}return typeof e=="bigint"&&!r?.keep?Number(e):e}ql.toJS=Fl});var cn=b(zl=>{"use strict";var Jm=bo(),Wl=R(),Gm=mt(),ko=class{constructor(t){Object.defineProperty(this,Wl.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:r,maxAliasCount:i,onAnchor:n,reviver:a}={}){if(!Wl.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},s=Gm.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?Jm.applyReviver(a,{"":s},"",s):s}};zl.NodeBase=ko});var Mr=b(Jl=>{"use strict";var Um=sn(),Km=Dr(),nr=R(),Ym=cn(),Xm=mt(),So=class extends Ym.NodeBase{constructor(t){super(nr.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,r){if(r?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;r?.aliasResolveCache?i=r.aliasResolveCache:(i=[],Km.visit(t,{Node:(a,o)=>{(nr.isAlias(o)||nr.hasAnchor(o))&&i.push(o)}}),r&&(r.aliasResolveCache=i));let n;for(let a of i){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,r){if(!r)return{source:this.source};let{anchors:i,doc:n,maxAliasCount:a}=r,o=this.resolve(n,r);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=i.get(o);if(s||(Xm.toJS(o,null,r),s=i.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=ln(n,o,i)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,r,i){let n=`*${this.source}`;if(t){if(Um.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 ln(e,t,r){if(nr.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(nr.isCollection(t)){let i=0;for(let n of t.items){let a=ln(e,n,r);a>i&&(i=a)}return i}else if(nr.isPair(t)){let i=ln(e,t.key,r),n=ln(e,t.value,r);return Math.max(i,n)}return 1}Jl.Alias=So});var W=b(Eo=>{"use strict";var Qm=R(),Zm=cn(),ev=mt(),tv=e=>!e||typeof e!="function"&&typeof e!="object",vt=class extends Zm.NodeBase{constructor(t){super(Qm.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:ev.toJS(this.value,t,r)}toString(){return String(this.value)}};vt.BLOCK_FOLDED="BLOCK_FOLDED";vt.BLOCK_LITERAL="BLOCK_LITERAL";vt.PLAIN="PLAIN";vt.QUOTE_DOUBLE="QUOTE_DOUBLE";vt.QUOTE_SINGLE="QUOTE_SINGLE";Eo.Scalar=vt;Eo.isScalarValue=tv});var Fr=b(Ul=>{"use strict";var rv=Mr(),Bt=R(),Gl=W(),iv="tag:yaml.org,2002:";function nv(e,t,r){if(t){let i=r.filter(a=>a.tag===t),n=i.find(a=>!a.format)??i[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return r.find(i=>i.identify?.(e)&&!i.format)}function av(e,t,r){if(Bt.isDocument(e)&&(e=e.contents),Bt.isNode(e))return e;if(Bt.isPair(e)){let d=r.schema[Bt.MAP].createNode?.(r.schema,null,r);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:i,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=r,c;if(i&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new rv.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=iv+t.slice(2));let l=nv(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new Gl.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[Bt.MAP]:Symbol.iterator in Object(e)?o[Bt.SEQ]:o[Bt.MAP]}a&&(a(l),delete r.onTagObj);let f=l?.createNode?l.createNode(r.schema,e,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,e,r):new Gl.Scalar(e);return t?f.tag=t:l.default||(f.tag=l.tag),c&&(c.node=f),f}Ul.createNode=av});var dn=b(un=>{"use strict";var ov=Fr(),We=R(),sv=cn();function xo(e,t,r){let i=r;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]=i,i=o}else i=new Map([[a,i]])}return ov.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var Kl=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Po=class extends sv.NodeBase{constructor(t,r){super(t),Object.defineProperty(this,"schema",{value:r,configurable:!0,enumerable:!1,writable:!0})}clone(t){let r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(r.schema=t),r.items=r.items.map(i=>We.isNode(i)||We.isPair(i)?i.clone(t):i),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(Kl(t))this.add(r);else{let[i,...n]=t,a=this.get(i,!0);if(We.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,xo(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}deleteIn(t){let[r,...i]=t;if(i.length===0)return this.delete(r);let n=this.get(r,!0);if(We.isCollection(n))return n.deleteIn(i);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}getIn(t,r){let[i,...n]=t,a=this.get(i,!0);return n.length===0?!r&&We.isScalar(a)?a.value:a:We.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!We.isPair(r))return!1;let i=r.value;return i==null||t&&We.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(t){let[r,...i]=t;if(i.length===0)return this.has(r);let n=this.get(r,!0);return We.isCollection(n)?n.hasIn(i):!1}setIn(t,r){let[i,...n]=t;if(n.length===0)this.set(i,r);else{let a=this.get(i,!0);if(We.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,xo(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};un.Collection=Po;un.collectionFromPath=xo;un.isEmptyPath=Kl});var qr=b(fn=>{"use strict";var cv=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Co(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var lv=(e,t,r)=>e.endsWith(`
6
- `)?Co(r,t):r.includes(`
4
+ var Qm=Object.create;var Ml=Object.defineProperty;var Zm=Object.getOwnPropertyDescriptor;var ev=Object.getOwnPropertyNames;var tv=Object.getPrototypeOf,rv=Object.prototype.hasOwnProperty;var dn=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var k=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var iv=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of ev(t))!rv.call(e,n)&&n!==r&&Ml(e,n,{get:()=>t[n],enumerable:!(i=Zm(t,n))||i.enumerable});return e};var Wr=(e,t,r)=>(r=e!=null?Qm(tv(e)):{},iv(t||!e||!e.__esModule?Ml(r,"default",{value:e,enumerable:!0}):r,e));var A=k(ae=>{"use strict";var Ro=Symbol.for("yaml.alias"),Fl=Symbol.for("yaml.document"),fn=Symbol.for("yaml.map"),ql=Symbol.for("yaml.pair"),Ao=Symbol.for("yaml.scalar"),pn=Symbol.for("yaml.seq"),ct=Symbol.for("yaml.node.type"),nv=e=>!!e&&typeof e=="object"&&e[ct]===Ro,av=e=>!!e&&typeof e=="object"&&e[ct]===Fl,ov=e=>!!e&&typeof e=="object"&&e[ct]===fn,sv=e=>!!e&&typeof e=="object"&&e[ct]===ql,Wl=e=>!!e&&typeof e=="object"&&e[ct]===Ao,cv=e=>!!e&&typeof e=="object"&&e[ct]===pn;function zl(e){if(e&&typeof e=="object")switch(e[ct]){case fn:case pn:return!0}return!1}function lv(e){if(e&&typeof e=="object")switch(e[ct]){case Ro:case fn:case Ao:case pn:return!0}return!1}var uv=e=>(Wl(e)||zl(e))&&!!e.anchor;ae.ALIAS=Ro;ae.DOC=Fl;ae.MAP=fn;ae.NODE_TYPE=ct;ae.PAIR=ql;ae.SCALAR=Ao;ae.SEQ=pn;ae.hasAnchor=uv;ae.isAlias=nv;ae.isCollection=zl;ae.isDocument=av;ae.isMap=ov;ae.isNode=lv;ae.isPair=sv;ae.isScalar=Wl;ae.isSeq=cv});var zr=k(_o=>{"use strict";var K=A(),he=Symbol("break visit"),Jl=Symbol("skip children"),Ge=Symbol("remove node");function hn(e,t){let r=Gl(t);K.isDocument(e)?lr(null,e.contents,r,Object.freeze([e]))===Ge&&(e.contents=null):lr(null,e,r,Object.freeze([]))}hn.BREAK=he;hn.SKIP=Jl;hn.REMOVE=Ge;function lr(e,t,r,i){let n=Ul(e,t,r,i);if(K.isNode(n)||K.isPair(n))return Kl(e,i,n),lr(e,n,r,i);if(typeof n!="symbol"){if(K.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=lr(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===he)return he;o===Ge&&(t.items.splice(a,1),a-=1)}}}else if(K.isPair(t)){i=Object.freeze(i.concat(t));let a=lr("key",t.key,r,i);if(a===he)return he;a===Ge&&(t.key=null);let o=lr("value",t.value,r,i);if(o===he)return he;o===Ge&&(t.value=null)}}return n}async function mn(e,t){let r=Gl(t);K.isDocument(e)?await ur(null,e.contents,r,Object.freeze([e]))===Ge&&(e.contents=null):await ur(null,e,r,Object.freeze([]))}mn.BREAK=he;mn.SKIP=Jl;mn.REMOVE=Ge;async function ur(e,t,r,i){let n=await Ul(e,t,r,i);if(K.isNode(n)||K.isPair(n))return Kl(e,i,n),ur(e,n,r,i);if(typeof n!="symbol"){if(K.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await ur(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===he)return he;o===Ge&&(t.items.splice(a,1),a-=1)}}}else if(K.isPair(t)){i=Object.freeze(i.concat(t));let a=await ur("key",t.key,r,i);if(a===he)return he;a===Ge&&(t.key=null);let o=await ur("value",t.value,r,i);if(o===he)return he;o===Ge&&(t.value=null)}}return n}function Gl(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 Ul(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(K.isMap(t))return r.Map?.(e,t,i);if(K.isSeq(t))return r.Seq?.(e,t,i);if(K.isPair(t))return r.Pair?.(e,t,i);if(K.isScalar(t))return r.Scalar?.(e,t,i);if(K.isAlias(t))return r.Alias?.(e,t,i)}function Kl(e,t,r){let i=t[t.length-1];if(K.isCollection(i))i.items[e]=r;else if(K.isPair(i))e==="key"?i.key=r:i.value=r;else if(K.isDocument(i))i.contents=r;else{let n=K.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}_o.visit=hn;_o.visitAsync=mn});var Io=k(Xl=>{"use strict";var Yl=A(),dv=zr(),fv={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},pv=e=>e.replace(/[!,[\]{}]/g,t=>fv[t]),Jr=class e{constructor(t,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,r)}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,r){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let i=t.trim().split(/[ \t]+/),n=i.shift();switch(n){case"%TAG":{if(i.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[a,o]=i;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;let[a]=i;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return r(6,`Unsupported YAML version ${a}`,o),!1}}default:return r(0,`Unknown directive ${n}`,!0),!1}}tagName(t,r){if(t==="!")return"!";if(t[0]!=="!")return r(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}let[,i,n]=t.match(/^(.*!)([^!]*)$/s);n||r(`The ${t} tag has no suffix`);let a=this.tags[i];if(a)try{return a+decodeURIComponent(n)}catch(o){return r(String(o)),null}return i==="!"?t:(r(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[r,i]of Object.entries(this.tags))if(t.startsWith(i))return r+pv(t.substring(i.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),n;if(t&&i.length>0&&Yl.isNode(t.contents)){let a={};dv.visit(t.contents,(o,s)=>{Yl.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of i)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&r.push(`%TAG ${a} ${o}`);return r.join(`
5
+ `)}};Jr.defaultYaml={explicit:!1,version:"1.2"};Jr.defaultTags={"!!":"tag:yaml.org,2002:"};Xl.Directives=Jr});var vn=k(Gr=>{"use strict";var Ql=A(),hv=zr();function mv(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(r)}return!0}function Zl(e){let t=new Set;return hv.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function eu(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function vv(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=Zl(e));let o=eu(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(Ql.isScalar(o.node)||Ql.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:i}}Gr.anchorIsValid=mv;Gr.anchorNames=Zl;Gr.createNodeAnchors=vv;Gr.findNewAnchor=eu});var To=k(tu=>{"use strict";function Ur(e,t,r,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let n=0,a=i.length;n<a;++n){let o=i[n],s=Ur(e,i,String(n),o);s===void 0?delete i[n]:s!==o&&(i[n]=s)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let a=i.get(n),o=Ur(e,i,n,a);o===void 0?i.delete(n):o!==a&&i.set(n,o)}else if(i instanceof Set)for(let n of Array.from(i)){let a=Ur(e,i,n,n);a===void 0?i.delete(n):a!==n&&(i.delete(n),i.add(a))}else for(let[n,a]of Object.entries(i)){let o=Ur(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}tu.applyReviver=Ur});var Nt=k(iu=>{"use strict";var gv=A();function ru(e,t,r){if(Array.isArray(e))return e.map((i,n)=>ru(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!gv.hasAnchor(e))return e.toJSON(t,r);let i={aliasCount:0,count:1,res:void 0};r.anchors.set(e,i),r.onCreate=a=>{i.res=a,delete r.onCreate};let n=e.toJSON(t,r);return r.onCreate&&r.onCreate(n),n}return typeof e=="bigint"&&!r?.keep?Number(e):e}iu.toJS=ru});var gn=k(au=>{"use strict";var wv=To(),nu=A(),yv=Nt(),jo=class{constructor(t){Object.defineProperty(this,nu.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:r,maxAliasCount:i,onAnchor:n,reviver:a}={}){if(!nu.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},s=yv.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?wv.applyReviver(a,{"":s},"",s):s}};au.NodeBase=jo});var Kr=k(ou=>{"use strict";var Nv=vn(),bv=zr(),dr=A(),kv=gn(),Sv=Nt(),$o=class extends kv.NodeBase{constructor(t){super(dr.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,r){if(r?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;r?.aliasResolveCache?i=r.aliasResolveCache:(i=[],bv.visit(t,{Node:(a,o)=>{(dr.isAlias(o)||dr.hasAnchor(o))&&i.push(o)}}),r&&(r.aliasResolveCache=i));let n;for(let a of i){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,r){if(!r)return{source:this.source};let{anchors:i,doc:n,maxAliasCount:a}=r,o=this.resolve(n,r);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=i.get(o);if(s||(Sv.toJS(o,null,r),s=i.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=wn(n,o,i)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,r,i){let n=`*${this.source}`;if(t){if(Nv.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 wn(e,t,r){if(dr.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(dr.isCollection(t)){let i=0;for(let n of t.items){let a=wn(e,n,r);a>i&&(i=a)}return i}else if(dr.isPair(t)){let i=wn(e,t.key,r),n=wn(e,t.value,r);return Math.max(i,n)}return 1}ou.Alias=$o});var J=k(Oo=>{"use strict";var Ev=A(),xv=gn(),Cv=Nt(),Pv=e=>!e||typeof e!="function"&&typeof e!="object",bt=class extends xv.NodeBase{constructor(t){super(Ev.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:Cv.toJS(this.value,t,r)}toString(){return String(this.value)}};bt.BLOCK_FOLDED="BLOCK_FOLDED";bt.BLOCK_LITERAL="BLOCK_LITERAL";bt.PLAIN="PLAIN";bt.QUOTE_DOUBLE="QUOTE_DOUBLE";bt.QUOTE_SINGLE="QUOTE_SINGLE";Oo.Scalar=bt;Oo.isScalarValue=Pv});var Yr=k(cu=>{"use strict";var Rv=Kr(),qt=A(),su=J(),Av="tag:yaml.org,2002:";function _v(e,t,r){if(t){let i=r.filter(a=>a.tag===t),n=i.find(a=>!a.format)??i[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return r.find(i=>i.identify?.(e)&&!i.format)}function Iv(e,t,r){if(qt.isDocument(e)&&(e=e.contents),qt.isNode(e))return e;if(qt.isPair(e)){let u=r.schema[qt.MAP].createNode?.(r.schema,null,r);return u.items.push(e),u}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:i,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=r,c;if(i&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new Rv.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=Av+t.slice(2));let l=_v(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let u=new su.Scalar(e);return c&&(c.node=u),u}l=e instanceof Map?o[qt.MAP]:Symbol.iterator in Object(e)?o[qt.SEQ]:o[qt.MAP]}a&&(a(l),delete r.onTagObj);let f=l?.createNode?l.createNode(r.schema,e,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,e,r):new su.Scalar(e);return t?f.tag=t:l.default||(f.tag=l.tag),c&&(c.node=f),f}cu.createNode=Iv});var Nn=k(yn=>{"use strict";var Tv=Yr(),Ue=A(),jv=gn();function Ho(e,t,r){let i=r;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]=i,i=o}else i=new Map([[a,i]])}return Tv.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var lu=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Do=class extends jv.NodeBase{constructor(t,r){super(t),Object.defineProperty(this,"schema",{value:r,configurable:!0,enumerable:!1,writable:!0})}clone(t){let r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(r.schema=t),r.items=r.items.map(i=>Ue.isNode(i)||Ue.isPair(i)?i.clone(t):i),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(lu(t))this.add(r);else{let[i,...n]=t,a=this.get(i,!0);if(Ue.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,Ho(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}deleteIn(t){let[r,...i]=t;if(i.length===0)return this.delete(r);let n=this.get(r,!0);if(Ue.isCollection(n))return n.deleteIn(i);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}getIn(t,r){let[i,...n]=t,a=this.get(i,!0);return n.length===0?!r&&Ue.isScalar(a)?a.value:a:Ue.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!Ue.isPair(r))return!1;let i=r.value;return i==null||t&&Ue.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(t){let[r,...i]=t;if(i.length===0)return this.has(r);let n=this.get(r,!0);return Ue.isCollection(n)?n.hasIn(i):!1}setIn(t,r){let[i,...n]=t;if(n.length===0)this.set(i,r);else{let a=this.get(i,!0);if(Ue.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,Ho(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};yn.Collection=Do;yn.collectionFromPath=Ho;yn.isEmptyPath=lu});var Xr=k(bn=>{"use strict";var $v=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Bo(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Ov=(e,t,r)=>e.endsWith(`
6
+ `)?Bo(r,t):r.includes(`
7
7
  `)?`
8
- `+Co(r,t):(e.endsWith(" ")?"":" ")+r;fn.indentComment=Co;fn.lineComment=lv;fn.stringifyComment=cv});var Xl=b(Wr=>{"use strict";var uv="flow",Ro="block",hn="quoted";function dv(e,t,r="flow",{indentAtStart:i,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=[],f={},d=n-t.length;typeof i=="number"&&(i>n-Math.max(2,a)?l.push(0):d=n-i);let u,h,v=!1,m=-1,p=-1,y=-1;r===Ro&&(m=Yl(e,m,t.length),m!==-1&&(d=m+c));for(let w;w=e[m+=1];){if(r===hn&&w==="\\"){switch(p=m,e[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}y=m}if(w===`
9
- `)r===Ro&&(m=Yl(e,m,t.length)),d=m+t.length+c,u=void 0;else{if(w===" "&&h&&h!==" "&&h!==`
10
- `&&h!==" "){let k=e[m+1];k&&k!==" "&&k!==`
11
- `&&k!==" "&&(u=m)}if(m>=d)if(u)l.push(u),d=u+c,u=void 0;else if(r===hn){for(;h===" "||h===" ";)h=w,w=e[m+=1],v=!0;let k=m>y+1?m-2:p-1;if(f[k])return e;l.push(k),f[k]=!0,d=k+c,u=void 0}else v=!0}h=w}if(v&&s&&s(),l.length===0)return e;o&&o();let g=e.slice(0,l[0]);for(let w=0;w<l.length;++w){let k=l[w],S=l[w+1]||e.length;k===0?g=`
12
- ${t}${e.slice(0,S)}`:(r===hn&&f[k]&&(g+=`${e[k]}\\`),g+=`
13
- ${t}${e.slice(k+1,S)}`)}return g}function Yl(e,t,r){let i=t,n=t+1,a=e[n];for(;a===" "||a===" ";)if(t<n+r)a=e[++t];else{do a=e[++t];while(a&&a!==`
14
- `);i=t,n=t+1,a=e[n]}return i}Wr.FOLD_BLOCK=Ro;Wr.FOLD_FLOW=uv;Wr.FOLD_QUOTED=hn;Wr.foldFlowLines=dv});var Jr=b(Ql=>{"use strict";var _e=W(),gt=Xl(),mn=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),vn=e=>/^(%|---|\.\.\.)/m.test(e);function fv(e,t,r){if(!t||t<0)return!1;let i=t-r,n=e.length;if(n<=i)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
15
- `){if(a-o>i)return!0;if(o=a+1,n-o<=i)return!1}return!0}function zr(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:i}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(vn(e)?" ":""),o="",s=0;for(let c=0,l=r[c];l;l=r[++c])if(l===" "&&r[c+1]==="\\"&&r[c+2]==="n"&&(o+=r.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(r[c+1]){case"u":{o+=r.slice(s,c);let f=r.substr(c+2,4);switch(f){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:f.substr(0,2)==="00"?o+="\\x"+f.substr(2):o+=r.substr(c,6)}c+=5,s=c+1}break;case"n":if(i||r[c+2]==='"'||r.length<n)c+=1;else{for(o+=r.slice(s,c)+`
8
+ `+Bo(r,t):(e.endsWith(" ")?"":" ")+r;bn.indentComment=Bo;bn.lineComment=Ov;bn.stringifyComment=$v});var du=k(Qr=>{"use strict";var Hv="flow",Lo="block",kn="quoted";function Dv(e,t,r="flow",{indentAtStart:i,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=[],f={},u=n-t.length;typeof i=="number"&&(i>n-Math.max(2,a)?l.push(0):u=n-i);let d,p,v=!1,m=-1,h=-1,g=-1;r===Lo&&(m=uu(e,m,t.length),m!==-1&&(u=m+c));for(let y;y=e[m+=1];){if(r===kn&&y==="\\"){switch(h=m,e[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}g=m}if(y===`
9
+ `)r===Lo&&(m=uu(e,m,t.length)),u=m+t.length+c,d=void 0;else{if(y===" "&&p&&p!==" "&&p!==`
10
+ `&&p!==" "){let S=e[m+1];S&&S!==" "&&S!==`
11
+ `&&S!==" "&&(d=m)}if(m>=u)if(d)l.push(d),u=d+c,d=void 0;else if(r===kn){for(;p===" "||p===" ";)p=y,y=e[m+=1],v=!0;let S=m>g+1?m-2:h-1;if(f[S])return e;l.push(S),f[S]=!0,u=S+c,d=void 0}else v=!0}p=y}if(v&&s&&s(),l.length===0)return e;o&&o();let w=e.slice(0,l[0]);for(let y=0;y<l.length;++y){let S=l[y],N=l[y+1]||e.length;S===0?w=`
12
+ ${t}${e.slice(0,N)}`:(r===kn&&f[S]&&(w+=`${e[S]}\\`),w+=`
13
+ ${t}${e.slice(S+1,N)}`)}return w}function uu(e,t,r){let i=t,n=t+1,a=e[n];for(;a===" "||a===" ";)if(t<n+r)a=e[++t];else{do a=e[++t];while(a&&a!==`
14
+ `);i=t,n=t+1,a=e[n]}return i}Qr.FOLD_BLOCK=Lo;Qr.FOLD_FLOW=Hv;Qr.FOLD_QUOTED=kn;Qr.foldFlowLines=Dv});var ei=k(fu=>{"use strict";var $e=J(),kt=du(),En=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),xn=e=>/^(%|---|\.\.\.)/m.test(e);function Bv(e,t,r){if(!t||t<0)return!1;let i=t-r,n=e.length;if(n<=i)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
15
+ `){if(a-o>i)return!0;if(o=a+1,n-o<=i)return!1}return!0}function Zr(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:i}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(xn(e)?" ":""),o="",s=0;for(let c=0,l=r[c];l;l=r[++c])if(l===" "&&r[c+1]==="\\"&&r[c+2]==="n"&&(o+=r.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(r[c+1]){case"u":{o+=r.slice(s,c);let f=r.substr(c+2,4);switch(f){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:f.substr(0,2)==="00"?o+="\\x"+f.substr(2):o+=r.substr(c,6)}c+=5,s=c+1}break;case"n":if(i||r[c+2]==='"'||r.length<n)c+=1;else{for(o+=r.slice(s,c)+`
16
16
 
17
17
  `;r[c+2]==="\\"&&r[c+3]==="n"&&r[c+4]!=='"';)o+=`
18
- `,c+=2;o+=a,r[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+r.slice(s):r,i?o:gt.foldFlowLines(o,a,gt.FOLD_QUOTED,mn(t,!1))}function Ao(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
19
- `)||/[ \t]\n|\n[ \t]/.test(e))return zr(e,t);let r=t.indent||(vn(e)?" ":""),i="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
20
- ${r}`)+"'";return t.implicitKey?i:gt.foldFlowLines(i,r,gt.FOLD_FLOW,mn(t,!1))}function ar(e,t){let{singleQuote:r}=t.options,i;if(r===!1)i=zr;else{let n=e.includes('"'),a=e.includes("'");n&&!a?i=Ao:a&&!n?i=zr:i=r?Ao:zr}return i(e,t)}var _o;try{_o=new RegExp(`(^|(?<!
18
+ `,c+=2;o+=a,r[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+r.slice(s):r,i?o:kt.foldFlowLines(o,a,kt.FOLD_QUOTED,En(t,!1))}function Vo(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
19
+ `)||/[ \t]\n|\n[ \t]/.test(e))return Zr(e,t);let r=t.indent||(xn(e)?" ":""),i="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
20
+ ${r}`)+"'";return t.implicitKey?i:kt.foldFlowLines(i,r,kt.FOLD_FLOW,En(t,!1))}function fr(e,t){let{singleQuote:r}=t.options,i;if(r===!1)i=Zr;else{let n=e.includes('"'),a=e.includes("'");n&&!a?i=Vo:a&&!n?i=Zr:i=r?Vo:Zr}return i(e,t)}var Mo;try{Mo=new RegExp(`(^|(?<!
21
21
  ))
22
22
  +(?!
23
- |$)`,"g")}catch{_o=/\n+(?!\n|$)/g}function pn({comment:e,type:t,value:r},i,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=i.options;if(!o||/\n[\t ]+$/.test(r))return ar(r,i);let l=i.indent||(i.forceBlockIndent||vn(r)?" ":""),f=o==="literal"?!0:o==="folded"||t===_e.Scalar.BLOCK_FOLDED?!1:t===_e.Scalar.BLOCK_LITERAL?!0:!fv(r,c,l.length);if(!r)return f?`|
23
+ |$)`,"g")}catch{Mo=/\n+(?!\n|$)/g}function Sn({comment:e,type:t,value:r},i,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=i.options;if(!o||/\n[\t ]+$/.test(r))return fr(r,i);let l=i.indent||(i.forceBlockIndent||xn(r)?" ":""),f=o==="literal"?!0:o==="folded"||t===$e.Scalar.BLOCK_FOLDED?!1:t===$e.Scalar.BLOCK_LITERAL?!0:!Bv(r,c,l.length);if(!r)return f?`|
24
24
  `:`>
25
- `;let d,u;for(u=r.length;u>0;--u){let S=r[u-1];if(S!==`
26
- `&&S!==" "&&S!==" ")break}let h=r.substring(u),v=h.indexOf(`
27
- `);v===-1?d="-":r===h||v!==h.length-1?(d="+",a&&a()):d="",h&&(r=r.slice(0,-h.length),h[h.length-1]===`
28
- `&&(h=h.slice(0,-1)),h=h.replace(_o,`$&${l}`));let m=!1,p,y=-1;for(p=0;p<r.length;++p){let S=r[p];if(S===" ")m=!0;else if(S===`
29
- `)y=p;else break}let g=r.substring(0,y<p?y+1:p);g&&(r=r.substring(g.length),g=g.replace(/\n+/g,`$&${l}`));let k=(m?l?"2":"1":"")+d;if(e&&(k+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!f){let S=r.replace(/\n+/g,`
30
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),E=!1,x=mn(i,!0);o!=="folded"&&t!==_e.Scalar.BLOCK_FOLDED&&(x.onOverflow=()=>{E=!0});let N=gt.foldFlowLines(`${g}${S}${h}`,l,gt.FOLD_BLOCK,x);if(!E)return`>${k}
31
- ${l}${N}`}return r=r.replace(/\n+/g,`$&${l}`),`|${k}
32
- ${l}${g}${r}${h}`}function hv(e,t,r,i){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:f}=t;if(s&&a.includes(`
33
- `)||f&&/[[\]{},]/.test(a))return ar(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||f||!a.includes(`
34
- `)?ar(a,t):pn(e,t,r,i);if(!s&&!f&&n!==_e.Scalar.PLAIN&&a.includes(`
35
- `))return pn(e,t,r,i);if(vn(a)){if(c==="")return t.forceBlockIndent=!0,pn(e,t,r,i);if(s&&c===l)return ar(a,t)}let d=a.replace(/\n+/g,`$&
36
- ${c}`);if(o){let u=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(d),{compat:h,tags:v}=t.doc.schema;if(v.some(u)||h?.some(u))return ar(a,t)}return s?d:gt.foldFlowLines(d,c,gt.FOLD_FLOW,mn(t,!1))}function pv(e,t,r,i){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==_e.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=_e.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case _e.Scalar.BLOCK_FOLDED:case _e.Scalar.BLOCK_LITERAL:return n||a?ar(o.value,t):pn(o,t,r,i);case _e.Scalar.QUOTE_DOUBLE:return zr(o.value,t);case _e.Scalar.QUOTE_SINGLE:return Ao(o.value,t);case _e.Scalar.PLAIN:return hv(o,t,r,i);default:return null}},l=c(s);if(l===null){let{defaultKeyType:f,defaultStringType:d}=t.options,u=n&&f||d;if(l=c(u),l===null)throw new Error(`Unsupported default string type ${u}`)}return l}Ql.stringifyString=pv});var Gr=b(Io=>{"use strict";var mv=sn(),wt=R(),vv=qr(),gv=Jr();function wv(e,t){let r=Object.assign({blockQuote:!0,commentString:vv.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),i;switch(r.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:e,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:i,options:r}}function yv(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 r,i;if(wt.isScalar(t)){i=t.value;let n=e.filter(a=>a.identify?.(i));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}r=n.find(a=>a.format===t.format)??n.find(a=>!a.format)}else i=t,r=e.find(n=>n.nodeClass&&i instanceof n.nodeClass);if(!r){let n=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${n} value`)}return r}function Nv(e,t,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=(wt.isScalar(e)||wt.isCollection(e))&&e.anchor;a&&mv.anchorIsValid(a)&&(r.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(i.directives.tagString(o)),n.join(" ")}function bv(e,t,r,i){if(wt.isPair(e))return e.toString(t,r,i);if(wt.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=wt.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=yv(t.doc.schema.tags,a));let o=Nv(a,n,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,t,r,i):wt.isScalar(a)?gv.stringifyString(a,t,r,i):a.toString(t,r,i);return o?wt.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
- ${t.indent}${s}`:s}Io.createStringifyContext=wv;Io.stringify=bv});var ru=b(tu=>{"use strict";var nt=R(),Zl=W(),eu=Gr(),Ur=qr();function kv({key:e,value:t},r,i,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:f,simpleKeys:d}}=r,u=nt.isNode(e)&&e.comment||null;if(d){if(u)throw new Error("With simple keys, key nodes cannot have comments");if(nt.isCollection(e)||!nt.isNode(e)&&typeof e=="object"){let x="With simple keys, collection cannot be used as a key value";throw new Error(x)}}let h=!d&&(!e||u&&t==null&&!r.inFlow||nt.isCollection(e)||(nt.isScalar(e)?e.type===Zl.Scalar.BLOCK_FOLDED||e.type===Zl.Scalar.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!h&&(d||!a),indent:s+c});let v=!1,m=!1,p=eu.stringify(e,r,()=>v=!0,()=>m=!0);if(!h&&!r.inFlow&&p.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(r.inFlow){if(a||t==null)return v&&i&&i(),p===""?"?":h?`? ${p}`:p}else if(a&&!d||t==null&&h)return p=`? ${p}`,u&&!v?p+=Ur.lineComment(p,r.indent,l(u)):m&&n&&n(),p;v&&(u=null),h?(u&&(p+=Ur.lineComment(p,r.indent,l(u))),p=`? ${p}
38
- ${s}:`):(p=`${p}:`,u&&(p+=Ur.lineComment(p,r.indent,l(u))));let y,g,w;nt.isNode(t)?(y=!!t.spaceBefore,g=t.commentBefore,w=t.comment):(y=!1,g=null,w=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!h&&!u&&nt.isScalar(t)&&(r.indentAtStart=p.length+1),m=!1,!f&&c.length>=2&&!r.inFlow&&!h&&nt.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let k=!1,S=eu.stringify(t,r,()=>k=!0,()=>m=!0),E=" ";if(u||y||g){if(E=y?`
39
- `:"",g){let x=l(g);E+=`
40
- ${Ur.indentComment(x,r.indent)}`}S===""&&!r.inFlow?E===`
41
- `&&w&&(E=`
25
+ `;let u,d;for(d=r.length;d>0;--d){let N=r[d-1];if(N!==`
26
+ `&&N!==" "&&N!==" ")break}let p=r.substring(d),v=p.indexOf(`
27
+ `);v===-1?u="-":r===p||v!==p.length-1?(u="+",a&&a()):u="",p&&(r=r.slice(0,-p.length),p[p.length-1]===`
28
+ `&&(p=p.slice(0,-1)),p=p.replace(Mo,`$&${l}`));let m=!1,h,g=-1;for(h=0;h<r.length;++h){let N=r[h];if(N===" ")m=!0;else if(N===`
29
+ `)g=h;else break}let w=r.substring(0,g<h?g+1:h);w&&(r=r.substring(w.length),w=w.replace(/\n+/g,`$&${l}`));let S=(m?l?"2":"1":"")+u;if(e&&(S+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!f){let N=r.replace(/\n+/g,`
30
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),E=!1,C=En(i,!0);o!=="folded"&&t!==$e.Scalar.BLOCK_FOLDED&&(C.onOverflow=()=>{E=!0});let b=kt.foldFlowLines(`${w}${N}${p}`,l,kt.FOLD_BLOCK,C);if(!E)return`>${S}
31
+ ${l}${b}`}return r=r.replace(/\n+/g,`$&${l}`),`|${S}
32
+ ${l}${w}${r}${p}`}function Lv(e,t,r,i){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:f}=t;if(s&&a.includes(`
33
+ `)||f&&/[[\]{},]/.test(a))return fr(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||f||!a.includes(`
34
+ `)?fr(a,t):Sn(e,t,r,i);if(!s&&!f&&n!==$e.Scalar.PLAIN&&a.includes(`
35
+ `))return Sn(e,t,r,i);if(xn(a)){if(c==="")return t.forceBlockIndent=!0,Sn(e,t,r,i);if(s&&c===l)return fr(a,t)}let u=a.replace(/\n+/g,`$&
36
+ ${c}`);if(o){let d=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(u),{compat:p,tags:v}=t.doc.schema;if(v.some(d)||p?.some(d))return fr(a,t)}return s?u:kt.foldFlowLines(u,c,kt.FOLD_FLOW,En(t,!1))}function Vv(e,t,r,i){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==$e.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=$e.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case $e.Scalar.BLOCK_FOLDED:case $e.Scalar.BLOCK_LITERAL:return n||a?fr(o.value,t):Sn(o,t,r,i);case $e.Scalar.QUOTE_DOUBLE:return Zr(o.value,t);case $e.Scalar.QUOTE_SINGLE:return Vo(o.value,t);case $e.Scalar.PLAIN:return Lv(o,t,r,i);default:return null}},l=c(s);if(l===null){let{defaultKeyType:f,defaultStringType:u}=t.options,d=n&&f||u;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}fu.stringifyString=Vv});var ti=k(Fo=>{"use strict";var Mv=vn(),St=A(),Fv=Xr(),qv=ei();function Wv(e,t){let r=Object.assign({blockQuote:!0,commentString:Fv.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),i;switch(r.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:e,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:i,options:r}}function zv(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 r,i;if(St.isScalar(t)){i=t.value;let n=e.filter(a=>a.identify?.(i));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}r=n.find(a=>a.format===t.format)??n.find(a=>!a.format)}else i=t,r=e.find(n=>n.nodeClass&&i instanceof n.nodeClass);if(!r){let n=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${n} value`)}return r}function Jv(e,t,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=(St.isScalar(e)||St.isCollection(e))&&e.anchor;a&&Mv.anchorIsValid(a)&&(r.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(i.directives.tagString(o)),n.join(" ")}function Gv(e,t,r,i){if(St.isPair(e))return e.toString(t,r,i);if(St.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=St.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=zv(t.doc.schema.tags,a));let o=Jv(a,n,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,t,r,i):St.isScalar(a)?qv.stringifyString(a,t,r,i):a.toString(t,r,i);return o?St.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
+ ${t.indent}${s}`:s}Fo.createStringifyContext=Wv;Fo.stringify=Gv});var vu=k(mu=>{"use strict";var lt=A(),pu=J(),hu=ti(),ri=Xr();function Uv({key:e,value:t},r,i,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:f,simpleKeys:u}}=r,d=lt.isNode(e)&&e.comment||null;if(u){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(lt.isCollection(e)||!lt.isNode(e)&&typeof e=="object"){let C="With simple keys, collection cannot be used as a key value";throw new Error(C)}}let p=!u&&(!e||d&&t==null&&!r.inFlow||lt.isCollection(e)||(lt.isScalar(e)?e.type===pu.Scalar.BLOCK_FOLDED||e.type===pu.Scalar.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!p&&(u||!a),indent:s+c});let v=!1,m=!1,h=hu.stringify(e,r,()=>v=!0,()=>m=!0);if(!p&&!r.inFlow&&h.length>1024){if(u)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(r.inFlow){if(a||t==null)return v&&i&&i(),h===""?"?":p?`? ${h}`:h}else if(a&&!u||t==null&&p)return h=`? ${h}`,d&&!v?h+=ri.lineComment(h,r.indent,l(d)):m&&n&&n(),h;v&&(d=null),p?(d&&(h+=ri.lineComment(h,r.indent,l(d))),h=`? ${h}
38
+ ${s}:`):(h=`${h}:`,d&&(h+=ri.lineComment(h,r.indent,l(d))));let g,w,y;lt.isNode(t)?(g=!!t.spaceBefore,w=t.commentBefore,y=t.comment):(g=!1,w=null,y=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!p&&!d&&lt.isScalar(t)&&(r.indentAtStart=h.length+1),m=!1,!f&&c.length>=2&&!r.inFlow&&!p&&lt.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let S=!1,N=hu.stringify(t,r,()=>S=!0,()=>m=!0),E=" ";if(d||g||w){if(E=g?`
39
+ `:"",w){let C=l(w);E+=`
40
+ ${ri.indentComment(C,r.indent)}`}N===""&&!r.inFlow?E===`
41
+ `&&y&&(E=`
42
42
 
43
43
  `):E+=`
44
- ${r.indent}`}else if(!h&&nt.isCollection(t)){let x=S[0],N=S.indexOf(`
45
- `),_=N!==-1,Y=r.inFlow??t.flow??t.items.length===0;if(_||!Y){let ee=!1;if(_&&(x==="&"||x==="!")){let $=S.indexOf(" ");x==="&"&&$!==-1&&$<N&&S[$+1]==="!"&&($=S.indexOf(" ",$+1)),($===-1||N<$)&&(ee=!0)}ee||(E=`
46
- ${r.indent}`)}}else(S===""||S[0]===`
47
- `)&&(E="");return p+=E+S,r.inFlow?k&&i&&i():w&&!k?p+=Ur.lineComment(p,r.indent,l(w)):m&&n&&n(),p}tu.stringifyPair=kv});var jo=b(To=>{"use strict";var iu=tn("process");function Sv(e,...t){e==="debug"&&console.log(...t)}function Ev(e,t){(e==="debug"||e==="warn")&&(typeof iu.emitWarning=="function"?iu.emitWarning(t):console.warn(t))}To.debug=Sv;To.warn=Ev});var bn=b(Nn=>{"use strict";var yn=R(),nu=W(),gn="<<",wn={identify:e=>e===gn||typeof e=="symbol"&&e.description===gn,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new nu.Scalar(Symbol(gn)),{addToJSMap:au}),stringify:()=>gn},xv=(e,t)=>(wn.identify(t)||yn.isScalar(t)&&(!t.type||t.type===nu.Scalar.PLAIN)&&wn.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===wn.tag&&r.default);function au(e,t,r){let i=ou(e,r);if(yn.isSeq(i))for(let n of i.items)$o(e,t,n);else if(Array.isArray(i))for(let n of i)$o(e,t,n);else $o(e,t,i)}function $o(e,t,r){let i=ou(e,r);if(!yn.isMap(i))throw new Error("Merge sources must be maps or map aliases");let n=i.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 ou(e,t){return e&&yn.isAlias(t)?t.resolve(e.doc,e):t}Nn.addMergeToJSMap=au;Nn.isMergeKey=xv;Nn.merge=wn});var Ho=b(lu=>{"use strict";var Pv=jo(),su=bn(),Cv=Gr(),cu=R(),Oo=mt();function Rv(e,t,{key:r,value:i}){if(cu.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,i);else if(su.isMergeKey(e,r))su.addMergeToJSMap(e,t,i);else{let n=Oo.toJS(r,"",e);if(t instanceof Map)t.set(n,Oo.toJS(i,n,e));else if(t instanceof Set)t.add(n);else{let a=Av(r,n,e),o=Oo.toJS(i,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function Av(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(cu.isNode(e)&&r?.doc){let i=Cv.createStringifyContext(r.doc,{});i.anchors=new Set;for(let a of r.anchors.keys())i.anchors.add(a.anchor);i.inFlow=!0,i.inStringifyKey=!0;let n=e.toString(i);if(!r.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),Pv.warn(r.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),r.mapKeyWarned=!0}return n}return JSON.stringify(t)}lu.addPairToJSMap=Rv});var yt=b(Do=>{"use strict";var uu=Fr(),_v=ru(),Iv=Ho(),kn=R();function Tv(e,t,r){let i=uu.createNode(e,void 0,r),n=uu.createNode(t,void 0,r);return new Sn(i,n)}var Sn=class e{constructor(t,r=null){Object.defineProperty(this,kn.NODE_TYPE,{value:kn.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:i}=this;return kn.isNode(r)&&(r=r.clone(t)),kn.isNode(i)&&(i=i.clone(t)),new e(r,i)}toJSON(t,r){let i=r?.mapAsMap?new Map:{};return Iv.addPairToJSMap(r,i,this)}toString(t,r,i){return t?.doc?_v.stringifyPair(this,t,r,i):JSON.stringify(this)}};Do.Pair=Sn;Do.createPair=Tv});var Bo=b(fu=>{"use strict";var Lt=R(),du=Gr(),En=qr();function jv(e,t,r){return(t.inFlow??e.flow?Ov:$v)(e,t,r)}function $v({comment:e,items:t},r,{blockItemPrefix:i,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=r,f=Object.assign({},r,{indent:a,type:null}),d=!1,u=[];for(let v=0;v<t.length;++v){let m=t[v],p=null;if(Lt.isNode(m))!d&&m.spaceBefore&&u.push(""),xn(r,u,m.commentBefore,d),m.comment&&(p=m.comment);else if(Lt.isPair(m)){let g=Lt.isNode(m.key)?m.key:null;g&&(!d&&g.spaceBefore&&u.push(""),xn(r,u,g.commentBefore,d))}d=!1;let y=du.stringify(m,f,()=>p=null,()=>d=!0);p&&(y+=En.lineComment(y,a,l(p))),d&&p&&(d=!1),u.push(i+y)}let h;if(u.length===0)h=n.start+n.end;else{h=u[0];for(let v=1;v<u.length;++v){let m=u[v];h+=m?`
44
+ ${r.indent}`}else if(!p&&lt.isCollection(t)){let C=N[0],b=N.indexOf(`
45
+ `),T=b!==-1,F=r.inFlow??t.flow??t.items.length===0;if(T||!F){let Z=!1;if(T&&(C==="&"||C==="!")){let j=N.indexOf(" ");C==="&"&&j!==-1&&j<b&&N[j+1]==="!"&&(j=N.indexOf(" ",j+1)),(j===-1||b<j)&&(Z=!0)}Z||(E=`
46
+ ${r.indent}`)}}else(N===""||N[0]===`
47
+ `)&&(E="");return h+=E+N,r.inFlow?S&&i&&i():y&&!S?h+=ri.lineComment(h,r.indent,l(y)):m&&n&&n(),h}mu.stringifyPair=Uv});var Wo=k(qo=>{"use strict";var gu=dn("process");function Kv(e,...t){e==="debug"&&console.log(...t)}function Yv(e,t){(e==="debug"||e==="warn")&&(typeof gu.emitWarning=="function"?gu.emitWarning(t):console.warn(t))}qo.debug=Kv;qo.warn=Yv});var _n=k(An=>{"use strict";var Rn=A(),wu=J(),Cn="<<",Pn={identify:e=>e===Cn||typeof e=="symbol"&&e.description===Cn,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new wu.Scalar(Symbol(Cn)),{addToJSMap:yu}),stringify:()=>Cn},Xv=(e,t)=>(Pn.identify(t)||Rn.isScalar(t)&&(!t.type||t.type===wu.Scalar.PLAIN)&&Pn.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===Pn.tag&&r.default);function yu(e,t,r){let i=Nu(e,r);if(Rn.isSeq(i))for(let n of i.items)zo(e,t,n);else if(Array.isArray(i))for(let n of i)zo(e,t,n);else zo(e,t,i)}function zo(e,t,r){let i=Nu(e,r);if(!Rn.isMap(i))throw new Error("Merge sources must be maps or map aliases");let n=i.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 Nu(e,t){return e&&Rn.isAlias(t)?t.resolve(e.doc,e):t}An.addMergeToJSMap=yu;An.isMergeKey=Xv;An.merge=Pn});var Go=k(Su=>{"use strict";var Qv=Wo(),bu=_n(),Zv=ti(),ku=A(),Jo=Nt();function eg(e,t,{key:r,value:i}){if(ku.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,i);else if(bu.isMergeKey(e,r))bu.addMergeToJSMap(e,t,i);else{let n=Jo.toJS(r,"",e);if(t instanceof Map)t.set(n,Jo.toJS(i,n,e));else if(t instanceof Set)t.add(n);else{let a=tg(r,n,e),o=Jo.toJS(i,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function tg(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(ku.isNode(e)&&r?.doc){let i=Zv.createStringifyContext(r.doc,{});i.anchors=new Set;for(let a of r.anchors.keys())i.anchors.add(a.anchor);i.inFlow=!0,i.inStringifyKey=!0;let n=e.toString(i);if(!r.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),Qv.warn(r.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),r.mapKeyWarned=!0}return n}return JSON.stringify(t)}Su.addPairToJSMap=eg});var Et=k(Uo=>{"use strict";var Eu=Yr(),rg=vu(),ig=Go(),In=A();function ng(e,t,r){let i=Eu.createNode(e,void 0,r),n=Eu.createNode(t,void 0,r);return new Tn(i,n)}var Tn=class e{constructor(t,r=null){Object.defineProperty(this,In.NODE_TYPE,{value:In.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:i}=this;return In.isNode(r)&&(r=r.clone(t)),In.isNode(i)&&(i=i.clone(t)),new e(r,i)}toJSON(t,r){let i=r?.mapAsMap?new Map:{};return ig.addPairToJSMap(r,i,this)}toString(t,r,i){return t?.doc?rg.stringifyPair(this,t,r,i):JSON.stringify(this)}};Uo.Pair=Tn;Uo.createPair=ng});var Ko=k(Cu=>{"use strict";var Wt=A(),xu=ti(),jn=Xr();function ag(e,t,r){return(t.inFlow??e.flow?sg:og)(e,t,r)}function og({comment:e,items:t},r,{blockItemPrefix:i,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=r,f=Object.assign({},r,{indent:a,type:null}),u=!1,d=[];for(let v=0;v<t.length;++v){let m=t[v],h=null;if(Wt.isNode(m))!u&&m.spaceBefore&&d.push(""),$n(r,d,m.commentBefore,u),m.comment&&(h=m.comment);else if(Wt.isPair(m)){let w=Wt.isNode(m.key)?m.key:null;w&&(!u&&w.spaceBefore&&d.push(""),$n(r,d,w.commentBefore,u))}u=!1;let g=xu.stringify(m,f,()=>h=null,()=>u=!0);h&&(g+=jn.lineComment(g,a,l(h))),u&&h&&(u=!1),d.push(i+g)}let p;if(d.length===0)p=n.start+n.end;else{p=d[0];for(let v=1;v<d.length;++v){let m=d[v];p+=m?`
48
48
  ${c}${m}`:`
49
- `}}return e?(h+=`
50
- `+En.indentComment(l(e),c),s&&s()):d&&o&&o(),h}function Ov({items:e},t,{flowChars:r,itemIndent:i}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;i+=a;let c=Object.assign({},t,{indent:i,inFlow:!0,type:null}),l=!1,f=0,d=[];for(let v=0;v<e.length;++v){let m=e[v],p=null;if(Lt.isNode(m))m.spaceBefore&&d.push(""),xn(t,d,m.commentBefore,!1),m.comment&&(p=m.comment);else if(Lt.isPair(m)){let g=Lt.isNode(m.key)?m.key:null;g&&(g.spaceBefore&&d.push(""),xn(t,d,g.commentBefore,!1),g.comment&&(l=!0));let w=Lt.isNode(m.value)?m.value:null;w?(w.comment&&(p=w.comment),w.commentBefore&&(l=!0)):m.value==null&&g?.comment&&(p=g.comment)}p&&(l=!0);let y=du.stringify(m,c,()=>p=null);l||(l=d.length>f||y.includes(`
51
- `)),v<e.length-1?y+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((g,w)=>g+w.length+2,2)+(y.length+2)>t.options.lineWidth)),l&&(y+=",")),p&&(y+=En.lineComment(y,i,s(p))),d.push(y),f=d.length}let{start:u,end:h}=r;if(d.length===0)return u+h;if(!l){let v=d.reduce((m,p)=>m+p.length+2,2);l=t.options.lineWidth>0&&v>t.options.lineWidth}if(l){let v=u;for(let m of d)v+=m?`
49
+ `}}return e?(p+=`
50
+ `+jn.indentComment(l(e),c),s&&s()):u&&o&&o(),p}function sg({items:e},t,{flowChars:r,itemIndent:i}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;i+=a;let c=Object.assign({},t,{indent:i,inFlow:!0,type:null}),l=!1,f=0,u=[];for(let v=0;v<e.length;++v){let m=e[v],h=null;if(Wt.isNode(m))m.spaceBefore&&u.push(""),$n(t,u,m.commentBefore,!1),m.comment&&(h=m.comment);else if(Wt.isPair(m)){let w=Wt.isNode(m.key)?m.key:null;w&&(w.spaceBefore&&u.push(""),$n(t,u,w.commentBefore,!1),w.comment&&(l=!0));let y=Wt.isNode(m.value)?m.value:null;y?(y.comment&&(h=y.comment),y.commentBefore&&(l=!0)):m.value==null&&w?.comment&&(h=w.comment)}h&&(l=!0);let g=xu.stringify(m,c,()=>h=null);l||(l=u.length>f||g.includes(`
51
+ `)),v<e.length-1?g+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=u.reduce((w,y)=>w+y.length+2,2)+(g.length+2)>t.options.lineWidth)),l&&(g+=",")),h&&(g+=jn.lineComment(g,i,s(h))),u.push(g),f=u.length}let{start:d,end:p}=r;if(u.length===0)return d+p;if(!l){let v=u.reduce((m,h)=>m+h.length+2,2);l=t.options.lineWidth>0&&v>t.options.lineWidth}if(l){let v=d;for(let m of u)v+=m?`
52
52
  ${a}${n}${m}`:`
53
53
  `;return`${v}
54
- ${n}${h}`}else return`${u}${o}${d.join(" ")}${o}${h}`}function xn({indent:e,options:{commentString:t}},r,i,n){if(i&&n&&(i=i.replace(/^\n+/,"")),i){let a=En.indentComment(t(i),e);r.push(a.trimStart())}}fu.stringifyCollection=jv});var bt=b(Vo=>{"use strict";var Hv=Bo(),Dv=Ho(),Bv=dn(),Nt=R(),Pn=yt(),Lv=W();function Kr(e,t){let r=Nt.isScalar(t)?t.value:t;for(let i of e)if(Nt.isPair(i)&&(i.key===t||i.key===r||Nt.isScalar(i.key)&&i.key.value===r))return i}var Lo=class extends Bv.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Nt.MAP,t),this.items=[]}static from(t,r,i){let{keepUndefined:n,replacer:a}=i,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(r,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||n)&&o.items.push(Pn.createPair(c,l,i))};if(r instanceof Map)for(let[c,l]of r)s(c,l);else if(r&&typeof r=="object")for(let c of Object.keys(r))s(c,r[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,r){let i;Nt.isPair(t)?i=t:!t||typeof t!="object"||!("key"in t)?i=new Pn.Pair(t,t?.value):i=new Pn.Pair(t.key,t.value);let n=Kr(this.items,i.key),a=this.schema?.sortMapEntries;if(n){if(!r)throw new Error(`Key ${i.key} already set`);Nt.isScalar(n.value)&&Lv.isScalarValue(i.value)?n.value.value=i.value:n.value=i.value}else if(a){let o=this.items.findIndex(s=>a(i,s)<0);o===-1?this.items.push(i):this.items.splice(o,0,i)}else this.items.push(i)}delete(t){let r=Kr(this.items,t);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(t,r){let n=Kr(this.items,t)?.value;return(!r&&Nt.isScalar(n)?n.value:n)??void 0}has(t){return!!Kr(this.items,t)}set(t,r){this.add(new Pn.Pair(t,r),!0)}toJSON(t,r,i){let n=i?new i:r?.mapAsMap?new Map:{};r?.onCreate&&r.onCreate(n);for(let a of this.items)Dv.addPairToJSMap(r,n,a);return n}toString(t,r,i){if(!t)return JSON.stringify(this);for(let n of this.items)if(!Nt.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})),Hv.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:i,onComment:r})}};Vo.YAMLMap=Lo;Vo.findPair=Kr});var or=b(pu=>{"use strict";var Vv=R(),hu=bt(),Mv={collection:"map",default:!0,nodeClass:hu.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return Vv.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>hu.YAMLMap.from(e,t,r)};pu.map=Mv});var kt=b(mu=>{"use strict";var Fv=Fr(),qv=Bo(),Wv=dn(),Rn=R(),zv=W(),Jv=mt(),Mo=class extends Wv.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Rn.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let r=Cn(t);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(t,r){let i=Cn(t);if(typeof i!="number")return;let n=this.items[i];return!r&&Rn.isScalar(n)?n.value:n}has(t){let r=Cn(t);return typeof r=="number"&&r<this.items.length}set(t,r){let i=Cn(t);if(typeof i!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[i];Rn.isScalar(n)&&zv.isScalarValue(r)?n.value=r:this.items[i]=r}toJSON(t,r){let i=[];r?.onCreate&&r.onCreate(i);let n=0;for(let a of this.items)i.push(Jv.toJS(a,String(n++),r));return i}toString(t,r,i){return t?qv.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:i,onComment:r}):JSON.stringify(this)}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r)){let o=0;for(let s of r){if(typeof n=="function"){let c=r instanceof Set?s:String(o++);s=n.call(r,c,s)}a.items.push(Fv.createNode(s,void 0,i))}}return a}};function Cn(e){let t=Rn.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}mu.YAMLSeq=Mo});var sr=b(gu=>{"use strict";var Gv=R(),vu=kt(),Uv={collection:"seq",default:!0,nodeClass:vu.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return Gv.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>vu.YAMLSeq.from(e,t,r)};gu.seq=Uv});var Yr=b(wu=>{"use strict";var Kv=Jr(),Yv={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,r,i){return t=Object.assign({actualString:!0},t),Kv.stringifyString(e,t,r,i)}};wu.string=Yv});var An=b(bu=>{"use strict";var yu=W(),Nu={identify:e=>e==null,createNode:()=>new yu.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new yu.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Nu.test.test(e)?e:t.options.nullStr};bu.nullTag=Nu});var Fo=b(Su=>{"use strict";var Xv=W(),ku={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new Xv.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&ku.test.test(e)){let i=e[0]==="t"||e[0]==="T";if(t===i)return e}return t?r.options.trueStr:r.options.falseStr}};Su.boolTag=ku});var cr=b(Eu=>{"use strict";function Qv({format:e,minFractionDigits:t,tag:r,value:i}){if(typeof i=="bigint")return String(i);let n=typeof i=="number"?i:Number(i);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let a=Object.is(i,-0)?"-0":JSON.stringify(i);if(!e&&t&&(!r||r==="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}Eu.stringifyNumber=Qv});var Wo=b(_n=>{"use strict";var Zv=W(),qo=cr(),eg={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:qo.stringifyNumber},tg={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():qo.stringifyNumber(e)}},rg={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 Zv.Scalar(parseFloat(e)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:qo.stringifyNumber};_n.float=rg;_n.floatExp=tg;_n.floatNaN=eg});var Jo=b(Tn=>{"use strict";var xu=cr(),In=e=>typeof e=="bigint"||Number.isInteger(e),zo=(e,t,r,{intAsBigInt:i})=>i?BigInt(e):parseInt(e.substring(t),r);function Pu(e,t,r){let{value:i}=e;return In(i)&&i>=0?r+i.toString(t):xu.stringifyNumber(e)}var ig={identify:e=>In(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>zo(e,2,8,r),stringify:e=>Pu(e,8,"0o")},ng={identify:In,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>zo(e,0,10,r),stringify:xu.stringifyNumber},ag={identify:e=>In(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>zo(e,2,16,r),stringify:e=>Pu(e,16,"0x")};Tn.int=ng;Tn.intHex=ag;Tn.intOct=ig});var Ru=b(Cu=>{"use strict";var og=or(),sg=An(),cg=sr(),lg=Yr(),ug=Fo(),Go=Wo(),Uo=Jo(),dg=[og.map,cg.seq,lg.string,sg.nullTag,ug.boolTag,Uo.intOct,Uo.int,Uo.intHex,Go.floatNaN,Go.floatExp,Go.float];Cu.schema=dg});var Iu=b(_u=>{"use strict";var fg=W(),hg=or(),pg=sr();function Au(e){return typeof e=="bigint"||Number.isInteger(e)}var jn=({value:e})=>JSON.stringify(e),mg=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:jn},{identify:e=>e==null,createNode:()=>new fg.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:jn},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:jn},{identify:Au,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:r})=>r?BigInt(e):parseInt(e,10),stringify:({value:e})=>Au(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:jn}],vg={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},gg=[hg.map,pg.seq].concat(mg,vg);_u.schema=gg});var Yo=b(Tu=>{"use strict";var Xr=tn("buffer"),Ko=W(),wg=Jr(),yg={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Xr.Buffer=="function")return Xr.Buffer.from(e,"base64");if(typeof atob=="function"){let r=atob(e.replace(/[\n\r]/g,"")),i=new Uint8Array(r.length);for(let n=0;n<r.length;++n)i[n]=r.charCodeAt(n);return i}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:r},i,n,a){if(!r)return"";let o=r,s;if(typeof Xr.Buffer=="function")s=o instanceof Xr.Buffer?o.toString("base64"):Xr.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=Ko.Scalar.BLOCK_LITERAL),t!==Ko.Scalar.QUOTE_DOUBLE){let c=Math.max(i.options.lineWidth-i.indent.length,i.options.minContentWidth),l=Math.ceil(s.length/c),f=new Array(l);for(let d=0,u=0;d<l;++d,u+=c)f[d]=s.substr(u,c);s=f.join(t===Ko.Scalar.BLOCK_LITERAL?`
55
- `:" ")}return wg.stringifyString({comment:e,type:t,value:s},i,n,a)}};Tu.binary=yg});var Hn=b(On=>{"use strict";var $n=R(),Xo=yt(),Ng=W(),bg=kt();function ju(e,t){if($n.isSeq(e))for(let r=0;r<e.items.length;++r){let i=e.items[r];if(!$n.isPair(i)){if($n.isMap(i)){i.items.length>1&&t("Each pair must have its own sequence indicator");let n=i.items[0]||new Xo.Pair(new Ng.Scalar(null));if(i.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${i.commentBefore}
54
+ ${n}${p}`}else return`${d}${o}${u.join(" ")}${o}${p}`}function $n({indent:e,options:{commentString:t}},r,i,n){if(i&&n&&(i=i.replace(/^\n+/,"")),i){let a=jn.indentComment(t(i),e);r.push(a.trimStart())}}Cu.stringifyCollection=ag});var Ct=k(Xo=>{"use strict";var cg=Ko(),lg=Go(),ug=Nn(),xt=A(),On=Et(),dg=J();function ii(e,t){let r=xt.isScalar(t)?t.value:t;for(let i of e)if(xt.isPair(i)&&(i.key===t||i.key===r||xt.isScalar(i.key)&&i.key.value===r))return i}var Yo=class extends ug.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(xt.MAP,t),this.items=[]}static from(t,r,i){let{keepUndefined:n,replacer:a}=i,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(r,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||n)&&o.items.push(On.createPair(c,l,i))};if(r instanceof Map)for(let[c,l]of r)s(c,l);else if(r&&typeof r=="object")for(let c of Object.keys(r))s(c,r[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,r){let i;xt.isPair(t)?i=t:!t||typeof t!="object"||!("key"in t)?i=new On.Pair(t,t?.value):i=new On.Pair(t.key,t.value);let n=ii(this.items,i.key),a=this.schema?.sortMapEntries;if(n){if(!r)throw new Error(`Key ${i.key} already set`);xt.isScalar(n.value)&&dg.isScalarValue(i.value)?n.value.value=i.value:n.value=i.value}else if(a){let o=this.items.findIndex(s=>a(i,s)<0);o===-1?this.items.push(i):this.items.splice(o,0,i)}else this.items.push(i)}delete(t){let r=ii(this.items,t);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(t,r){let n=ii(this.items,t)?.value;return(!r&&xt.isScalar(n)?n.value:n)??void 0}has(t){return!!ii(this.items,t)}set(t,r){this.add(new On.Pair(t,r),!0)}toJSON(t,r,i){let n=i?new i:r?.mapAsMap?new Map:{};r?.onCreate&&r.onCreate(n);for(let a of this.items)lg.addPairToJSMap(r,n,a);return n}toString(t,r,i){if(!t)return JSON.stringify(this);for(let n of this.items)if(!xt.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})),cg.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:i,onComment:r})}};Xo.YAMLMap=Yo;Xo.findPair=ii});var pr=k(Ru=>{"use strict";var fg=A(),Pu=Ct(),pg={collection:"map",default:!0,nodeClass:Pu.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return fg.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>Pu.YAMLMap.from(e,t,r)};Ru.map=pg});var Pt=k(Au=>{"use strict";var hg=Yr(),mg=Ko(),vg=Nn(),Dn=A(),gg=J(),wg=Nt(),Qo=class extends vg.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Dn.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let r=Hn(t);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(t,r){let i=Hn(t);if(typeof i!="number")return;let n=this.items[i];return!r&&Dn.isScalar(n)?n.value:n}has(t){let r=Hn(t);return typeof r=="number"&&r<this.items.length}set(t,r){let i=Hn(t);if(typeof i!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[i];Dn.isScalar(n)&&gg.isScalarValue(r)?n.value=r:this.items[i]=r}toJSON(t,r){let i=[];r?.onCreate&&r.onCreate(i);let n=0;for(let a of this.items)i.push(wg.toJS(a,String(n++),r));return i}toString(t,r,i){return t?mg.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:i,onComment:r}):JSON.stringify(this)}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r)){let o=0;for(let s of r){if(typeof n=="function"){let c=r instanceof Set?s:String(o++);s=n.call(r,c,s)}a.items.push(hg.createNode(s,void 0,i))}}return a}};function Hn(e){let t=Dn.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Au.YAMLSeq=Qo});var hr=k(Iu=>{"use strict";var yg=A(),_u=Pt(),Ng={collection:"seq",default:!0,nodeClass:_u.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return yg.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>_u.YAMLSeq.from(e,t,r)};Iu.seq=Ng});var ni=k(Tu=>{"use strict";var bg=ei(),kg={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,r,i){return t=Object.assign({actualString:!0},t),bg.stringifyString(e,t,r,i)}};Tu.string=kg});var Bn=k(Ou=>{"use strict";var ju=J(),$u={identify:e=>e==null,createNode:()=>new ju.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new ju.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&$u.test.test(e)?e:t.options.nullStr};Ou.nullTag=$u});var Zo=k(Du=>{"use strict";var Sg=J(),Hu={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new Sg.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&Hu.test.test(e)){let i=e[0]==="t"||e[0]==="T";if(t===i)return e}return t?r.options.trueStr:r.options.falseStr}};Du.boolTag=Hu});var mr=k(Bu=>{"use strict";function Eg({format:e,minFractionDigits:t,tag:r,value:i}){if(typeof i=="bigint")return String(i);let n=typeof i=="number"?i:Number(i);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let a=Object.is(i,-0)?"-0":JSON.stringify(i);if(!e&&t&&(!r||r==="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}Bu.stringifyNumber=Eg});var ts=k(Ln=>{"use strict";var xg=J(),es=mr(),Cg={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:es.stringifyNumber},Pg={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():es.stringifyNumber(e)}},Rg={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 xg.Scalar(parseFloat(e)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:es.stringifyNumber};Ln.float=Rg;Ln.floatExp=Pg;Ln.floatNaN=Cg});var is=k(Mn=>{"use strict";var Lu=mr(),Vn=e=>typeof e=="bigint"||Number.isInteger(e),rs=(e,t,r,{intAsBigInt:i})=>i?BigInt(e):parseInt(e.substring(t),r);function Vu(e,t,r){let{value:i}=e;return Vn(i)&&i>=0?r+i.toString(t):Lu.stringifyNumber(e)}var Ag={identify:e=>Vn(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>rs(e,2,8,r),stringify:e=>Vu(e,8,"0o")},_g={identify:Vn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>rs(e,0,10,r),stringify:Lu.stringifyNumber},Ig={identify:e=>Vn(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>rs(e,2,16,r),stringify:e=>Vu(e,16,"0x")};Mn.int=_g;Mn.intHex=Ig;Mn.intOct=Ag});var Fu=k(Mu=>{"use strict";var Tg=pr(),jg=Bn(),$g=hr(),Og=ni(),Hg=Zo(),ns=ts(),as=is(),Dg=[Tg.map,$g.seq,Og.string,jg.nullTag,Hg.boolTag,as.intOct,as.int,as.intHex,ns.floatNaN,ns.floatExp,ns.float];Mu.schema=Dg});var zu=k(Wu=>{"use strict";var Bg=J(),Lg=pr(),Vg=hr();function qu(e){return typeof e=="bigint"||Number.isInteger(e)}var Fn=({value:e})=>JSON.stringify(e),Mg=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Fn},{identify:e=>e==null,createNode:()=>new Bg.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Fn},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Fn},{identify:qu,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:r})=>r?BigInt(e):parseInt(e,10),stringify:({value:e})=>qu(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:Fn}],Fg={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},qg=[Lg.map,Vg.seq].concat(Mg,Fg);Wu.schema=qg});var ss=k(Ju=>{"use strict";var ai=dn("buffer"),os=J(),Wg=ei(),zg={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof ai.Buffer=="function")return ai.Buffer.from(e,"base64");if(typeof atob=="function"){let r=atob(e.replace(/[\n\r]/g,"")),i=new Uint8Array(r.length);for(let n=0;n<r.length;++n)i[n]=r.charCodeAt(n);return i}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:r},i,n,a){if(!r)return"";let o=r,s;if(typeof ai.Buffer=="function")s=o instanceof ai.Buffer?o.toString("base64"):ai.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=os.Scalar.BLOCK_LITERAL),t!==os.Scalar.QUOTE_DOUBLE){let c=Math.max(i.options.lineWidth-i.indent.length,i.options.minContentWidth),l=Math.ceil(s.length/c),f=new Array(l);for(let u=0,d=0;u<l;++u,d+=c)f[u]=s.substr(d,c);s=f.join(t===os.Scalar.BLOCK_LITERAL?`
55
+ `:" ")}return Wg.stringifyString({comment:e,type:t,value:s},i,n,a)}};Ju.binary=zg});var zn=k(Wn=>{"use strict";var qn=A(),cs=Et(),Jg=J(),Gg=Pt();function Gu(e,t){if(qn.isSeq(e))for(let r=0;r<e.items.length;++r){let i=e.items[r];if(!qn.isPair(i)){if(qn.isMap(i)){i.items.length>1&&t("Each pair must have its own sequence indicator");let n=i.items[0]||new cs.Pair(new Jg.Scalar(null));if(i.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${i.commentBefore}
56
56
  ${n.key.commentBefore}`:i.commentBefore),i.comment){let a=n.value??n.key;a.comment=a.comment?`${i.comment}
57
- ${a.comment}`:i.comment}i=n}e.items[r]=$n.isPair(i)?i:new Xo.Pair(i)}}else t("Expected a sequence for this tag");return e}function $u(e,t,r){let{replacer:i}=r,n=new bg.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 i=="function"&&(o=i.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(Xo.createPair(s,c,r))}return n}var kg={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:ju,createNode:$u};On.createPairs=$u;On.pairs=kg;On.resolvePairs=ju});var es=b(Zo=>{"use strict";var Ou=R(),Qo=mt(),Qr=bt(),Sg=kt(),Hu=Hn(),Vt=class e extends Sg.YAMLSeq{constructor(){super(),this.add=Qr.YAMLMap.prototype.add.bind(this),this.delete=Qr.YAMLMap.prototype.delete.bind(this),this.get=Qr.YAMLMap.prototype.get.bind(this),this.has=Qr.YAMLMap.prototype.has.bind(this),this.set=Qr.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,r){if(!r)return super.toJSON(t);let i=new Map;r?.onCreate&&r.onCreate(i);for(let n of this.items){let a,o;if(Ou.isPair(n)?(a=Qo.toJS(n.key,"",r),o=Qo.toJS(n.value,a,r)):a=Qo.toJS(n,"",r),i.has(a))throw new Error("Ordered maps must not include duplicate keys");i.set(a,o)}return i}static from(t,r,i){let n=Hu.createPairs(t,r,i),a=new this;return a.items=n.items,a}};Vt.tag="tag:yaml.org,2002:omap";var Eg={collection:"seq",identify:e=>e instanceof Map,nodeClass:Vt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=Hu.resolvePairs(e,t),i=[];for(let{key:n}of r.items)Ou.isScalar(n)&&(i.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new Vt,r)},createNode:(e,t,r)=>Vt.from(e,t,r)};Zo.YAMLOMap=Vt;Zo.omap=Eg});var Mu=b(ts=>{"use strict";var Du=W();function Bu({value:e,source:t},r){return t&&(e?Lu:Vu).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var Lu={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 Du.Scalar(!0),stringify:Bu},Vu={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 Du.Scalar(!1),stringify:Bu};ts.falseTag=Vu;ts.trueTag=Lu});var Fu=b(Dn=>{"use strict";var xg=W(),rs=cr(),Pg={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:rs.stringifyNumber},Cg={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():rs.stringifyNumber(e)}},Rg={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 xg.Scalar(parseFloat(e.replace(/_/g,""))),r=e.indexOf(".");if(r!==-1){let i=e.substring(r+1).replace(/_/g,"");i[i.length-1]==="0"&&(t.minFractionDigits=i.length)}return t},stringify:rs.stringifyNumber};Dn.float=Rg;Dn.floatExp=Cg;Dn.floatNaN=Pg});var Wu=b(ei=>{"use strict";var qu=cr(),Zr=e=>typeof e=="bigint"||Number.isInteger(e);function Bn(e,t,r,{intAsBigInt:i}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),i){switch(r){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,r);return n==="-"?-1*a:a}function is(e,t,r){let{value:i}=e;if(Zr(i)){let n=i.toString(t);return i<0?"-"+r+n.substr(1):r+n}return qu.stringifyNumber(e)}var Ag={identify:Zr,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>Bn(e,2,2,r),stringify:e=>is(e,2,"0b")},_g={identify:Zr,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>Bn(e,1,8,r),stringify:e=>is(e,8,"0")},Ig={identify:Zr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>Bn(e,0,10,r),stringify:qu.stringifyNumber},Tg={identify:Zr,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>Bn(e,2,16,r),stringify:e=>is(e,16,"0x")};ei.int=Ig;ei.intBin=Ag;ei.intHex=Tg;ei.intOct=_g});var as=b(ns=>{"use strict";var Mn=R(),Ln=yt(),Vn=bt(),Mt=class e extends Vn.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;Mn.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new Ln.Pair(t.key,null):r=new Ln.Pair(t,null),Vn.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let i=Vn.findPair(this.items,t);return!r&&Mn.isPair(i)?Mn.isScalar(i.key)?i.key.value:i.key:i}set(t,r){if(typeof r!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof r}`);let i=Vn.findPair(this.items,t);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new Ln.Pair(t))}toJSON(t,r){return super.toJSON(t,r,Set)}toString(t,r,i){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),r,i);throw new Error("Set items must all have null values")}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r))for(let o of r)typeof n=="function"&&(o=n.call(r,o,o)),a.items.push(Ln.createPair(o,null,i));return a}};Mt.tag="tag:yaml.org,2002:set";var jg={collection:"map",identify:e=>e instanceof Set,nodeClass:Mt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>Mt.from(e,t,r),resolve(e,t){if(Mn.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Mt,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};ns.YAMLSet=Mt;ns.set=jg});var ss=b(Fn=>{"use strict";var $g=cr();function os(e,t){let r=e[0],i=r==="-"||r==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=i.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return r==="-"?n(-1)*a:a}function zu(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return $g.stringifyNumber(e);let i="";t<0&&(i="-",t*=r(-1));let n=r(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))),i+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Og={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:r})=>os(e,r),stringify:zu},Hg={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=>os(e,!1),stringify:zu},Ju={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(Ju.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,i,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(r,i-1,n,a||0,o||0,s||0,c),f=t[8];if(f&&f!=="Z"){let d=os(f,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Fn.floatTime=Hg;Fn.intTime=Og;Fn.timestamp=Ju});var Ku=b(Uu=>{"use strict";var Dg=or(),Bg=An(),Lg=sr(),Vg=Yr(),Mg=Yo(),Gu=Mu(),cs=Fu(),qn=Wu(),Fg=bn(),qg=es(),Wg=Hn(),zg=as(),ls=ss(),Jg=[Dg.map,Lg.seq,Vg.string,Bg.nullTag,Gu.trueTag,Gu.falseTag,qn.intBin,qn.intOct,qn.int,qn.intHex,cs.floatNaN,cs.floatExp,cs.float,Mg.binary,Fg.merge,qg.omap,Wg.pairs,zg.set,ls.intTime,ls.floatTime,ls.timestamp];Uu.schema=Jg});var ad=b(fs=>{"use strict";var Zu=or(),Gg=An(),ed=sr(),Ug=Yr(),Kg=Fo(),us=Wo(),ds=Jo(),Yg=Ru(),Xg=Iu(),td=Yo(),ti=bn(),rd=es(),id=Hn(),Yu=Ku(),nd=as(),Wn=ss(),Xu=new Map([["core",Yg.schema],["failsafe",[Zu.map,ed.seq,Ug.string]],["json",Xg.schema],["yaml11",Yu.schema],["yaml-1.1",Yu.schema]]),Qu={binary:td.binary,bool:Kg.boolTag,float:us.float,floatExp:us.floatExp,floatNaN:us.floatNaN,floatTime:Wn.floatTime,int:ds.int,intHex:ds.intHex,intOct:ds.intOct,intTime:Wn.intTime,map:Zu.map,merge:ti.merge,null:Gg.nullTag,omap:rd.omap,pairs:id.pairs,seq:ed.seq,set:nd.set,timestamp:Wn.timestamp},Qg={"tag:yaml.org,2002:binary":td.binary,"tag:yaml.org,2002:merge":ti.merge,"tag:yaml.org,2002:omap":rd.omap,"tag:yaml.org,2002:pairs":id.pairs,"tag:yaml.org,2002:set":nd.set,"tag:yaml.org,2002:timestamp":Wn.timestamp};function Zg(e,t,r){let i=Xu.get(t);if(i&&!e)return r&&!i.includes(ti.merge)?i.concat(ti.merge):i.slice();let n=i;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(Xu.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 r&&(n=n.concat(ti.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Qu[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Qu).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}fs.coreKnownTags=Qg;fs.getTags=Zg});var ms=b(od=>{"use strict";var hs=R(),ew=or(),tw=sr(),rw=Yr(),zn=ad(),iw=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,ps=class e{constructor({compat:t,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?zn.getTags(t,"compat"):t?zn.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?zn.coreKnownTags:{},this.tags=zn.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,hs.MAP,{value:ew.map}),Object.defineProperty(this,hs.SCALAR,{value:rw.string}),Object.defineProperty(this,hs.SEQ,{value:tw.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?iw:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};od.Schema=ps});var cd=b(sd=>{"use strict";var nw=R(),vs=Gr(),ri=qr();function aw(e,t){let r=[],i=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(r.push(c),i=!0):e.directives.docStart&&(i=!0)}i&&r.push("---");let n=vs.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=a(e.commentBefore);r.unshift(ri.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(nw.isNode(e.contents)){if(e.contents.spaceBefore&&i&&r.push(""),e.contents.commentBefore){let f=a(e.contents.commentBefore);r.push(ri.indentComment(f,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=vs.stringify(e.contents,n,()=>s=null,c);s&&(l+=ri.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(vs.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
58
- `)?(r.push("..."),r.push(ri.indentComment(c,""))):r.push(`... ${c}`)}else r.push("...");else{let c=e.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&r[r.length-1]!==""&&r.push(""),r.push(ri.indentComment(a(c),"")))}return r.join(`
57
+ ${a.comment}`:i.comment}i=n}e.items[r]=qn.isPair(i)?i:new cs.Pair(i)}}else t("Expected a sequence for this tag");return e}function Uu(e,t,r){let{replacer:i}=r,n=new Gg.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 i=="function"&&(o=i.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(cs.createPair(s,c,r))}return n}var Ug={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Gu,createNode:Uu};Wn.createPairs=Uu;Wn.pairs=Ug;Wn.resolvePairs=Gu});var ds=k(us=>{"use strict";var Ku=A(),ls=Nt(),oi=Ct(),Kg=Pt(),Yu=zn(),zt=class e extends Kg.YAMLSeq{constructor(){super(),this.add=oi.YAMLMap.prototype.add.bind(this),this.delete=oi.YAMLMap.prototype.delete.bind(this),this.get=oi.YAMLMap.prototype.get.bind(this),this.has=oi.YAMLMap.prototype.has.bind(this),this.set=oi.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,r){if(!r)return super.toJSON(t);let i=new Map;r?.onCreate&&r.onCreate(i);for(let n of this.items){let a,o;if(Ku.isPair(n)?(a=ls.toJS(n.key,"",r),o=ls.toJS(n.value,a,r)):a=ls.toJS(n,"",r),i.has(a))throw new Error("Ordered maps must not include duplicate keys");i.set(a,o)}return i}static from(t,r,i){let n=Yu.createPairs(t,r,i),a=new this;return a.items=n.items,a}};zt.tag="tag:yaml.org,2002:omap";var Yg={collection:"seq",identify:e=>e instanceof Map,nodeClass:zt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=Yu.resolvePairs(e,t),i=[];for(let{key:n}of r.items)Ku.isScalar(n)&&(i.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new zt,r)},createNode:(e,t,r)=>zt.from(e,t,r)};us.YAMLOMap=zt;us.omap=Yg});var td=k(fs=>{"use strict";var Xu=J();function Qu({value:e,source:t},r){return t&&(e?Zu:ed).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var Zu={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 Xu.Scalar(!0),stringify:Qu},ed={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 Xu.Scalar(!1),stringify:Qu};fs.falseTag=ed;fs.trueTag=Zu});var rd=k(Jn=>{"use strict";var Xg=J(),ps=mr(),Qg={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:ps.stringifyNumber},Zg={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():ps.stringifyNumber(e)}},ew={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 Xg.Scalar(parseFloat(e.replace(/_/g,""))),r=e.indexOf(".");if(r!==-1){let i=e.substring(r+1).replace(/_/g,"");i[i.length-1]==="0"&&(t.minFractionDigits=i.length)}return t},stringify:ps.stringifyNumber};Jn.float=ew;Jn.floatExp=Zg;Jn.floatNaN=Qg});var nd=k(ci=>{"use strict";var id=mr(),si=e=>typeof e=="bigint"||Number.isInteger(e);function Gn(e,t,r,{intAsBigInt:i}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),i){switch(r){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,r);return n==="-"?-1*a:a}function hs(e,t,r){let{value:i}=e;if(si(i)){let n=i.toString(t);return i<0?"-"+r+n.substr(1):r+n}return id.stringifyNumber(e)}var tw={identify:si,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>Gn(e,2,2,r),stringify:e=>hs(e,2,"0b")},rw={identify:si,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>Gn(e,1,8,r),stringify:e=>hs(e,8,"0")},iw={identify:si,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>Gn(e,0,10,r),stringify:id.stringifyNumber},nw={identify:si,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>Gn(e,2,16,r),stringify:e=>hs(e,16,"0x")};ci.int=iw;ci.intBin=tw;ci.intHex=nw;ci.intOct=rw});var vs=k(ms=>{"use strict";var Yn=A(),Un=Et(),Kn=Ct(),Jt=class e extends Kn.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;Yn.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new Un.Pair(t.key,null):r=new Un.Pair(t,null),Kn.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let i=Kn.findPair(this.items,t);return!r&&Yn.isPair(i)?Yn.isScalar(i.key)?i.key.value:i.key:i}set(t,r){if(typeof r!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof r}`);let i=Kn.findPair(this.items,t);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new Un.Pair(t))}toJSON(t,r){return super.toJSON(t,r,Set)}toString(t,r,i){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),r,i);throw new Error("Set items must all have null values")}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r))for(let o of r)typeof n=="function"&&(o=n.call(r,o,o)),a.items.push(Un.createPair(o,null,i));return a}};Jt.tag="tag:yaml.org,2002:set";var aw={collection:"map",identify:e=>e instanceof Set,nodeClass:Jt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>Jt.from(e,t,r),resolve(e,t){if(Yn.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Jt,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};ms.YAMLSet=Jt;ms.set=aw});var ws=k(Xn=>{"use strict";var ow=mr();function gs(e,t){let r=e[0],i=r==="-"||r==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=i.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return r==="-"?n(-1)*a:a}function ad(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return ow.stringifyNumber(e);let i="";t<0&&(i="-",t*=r(-1));let n=r(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))),i+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var sw={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:r})=>gs(e,r),stringify:ad},cw={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=>gs(e,!1),stringify:ad},od={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(od.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,i,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(r,i-1,n,a||0,o||0,s||0,c),f=t[8];if(f&&f!=="Z"){let u=gs(f,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Xn.floatTime=cw;Xn.intTime=sw;Xn.timestamp=od});var ld=k(cd=>{"use strict";var lw=pr(),uw=Bn(),dw=hr(),fw=ni(),pw=ss(),sd=td(),ys=rd(),Qn=nd(),hw=_n(),mw=ds(),vw=zn(),gw=vs(),Ns=ws(),ww=[lw.map,dw.seq,fw.string,uw.nullTag,sd.trueTag,sd.falseTag,Qn.intBin,Qn.intOct,Qn.int,Qn.intHex,ys.floatNaN,ys.floatExp,ys.float,pw.binary,hw.merge,mw.omap,vw.pairs,gw.set,Ns.intTime,Ns.floatTime,Ns.timestamp];cd.schema=ww});var yd=k(Ss=>{"use strict";var pd=pr(),yw=Bn(),hd=hr(),Nw=ni(),bw=Zo(),bs=ts(),ks=is(),kw=Fu(),Sw=zu(),md=ss(),li=_n(),vd=ds(),gd=zn(),ud=ld(),wd=vs(),Zn=ws(),dd=new Map([["core",kw.schema],["failsafe",[pd.map,hd.seq,Nw.string]],["json",Sw.schema],["yaml11",ud.schema],["yaml-1.1",ud.schema]]),fd={binary:md.binary,bool:bw.boolTag,float:bs.float,floatExp:bs.floatExp,floatNaN:bs.floatNaN,floatTime:Zn.floatTime,int:ks.int,intHex:ks.intHex,intOct:ks.intOct,intTime:Zn.intTime,map:pd.map,merge:li.merge,null:yw.nullTag,omap:vd.omap,pairs:gd.pairs,seq:hd.seq,set:wd.set,timestamp:Zn.timestamp},Ew={"tag:yaml.org,2002:binary":md.binary,"tag:yaml.org,2002:merge":li.merge,"tag:yaml.org,2002:omap":vd.omap,"tag:yaml.org,2002:pairs":gd.pairs,"tag:yaml.org,2002:set":wd.set,"tag:yaml.org,2002:timestamp":Zn.timestamp};function xw(e,t,r){let i=dd.get(t);if(i&&!e)return r&&!i.includes(li.merge)?i.concat(li.merge):i.slice();let n=i;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(dd.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 r&&(n=n.concat(li.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?fd[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(fd).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}Ss.coreKnownTags=Ew;Ss.getTags=xw});var Cs=k(Nd=>{"use strict";var Es=A(),Cw=pr(),Pw=hr(),Rw=ni(),ea=yd(),Aw=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,xs=class e{constructor({compat:t,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?ea.getTags(t,"compat"):t?ea.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?ea.coreKnownTags:{},this.tags=ea.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,Es.MAP,{value:Cw.map}),Object.defineProperty(this,Es.SCALAR,{value:Rw.string}),Object.defineProperty(this,Es.SEQ,{value:Pw.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Aw:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Nd.Schema=xs});var kd=k(bd=>{"use strict";var _w=A(),Ps=ti(),ui=Xr();function Iw(e,t){let r=[],i=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(r.push(c),i=!0):e.directives.docStart&&(i=!0)}i&&r.push("---");let n=Ps.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=a(e.commentBefore);r.unshift(ui.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(_w.isNode(e.contents)){if(e.contents.spaceBefore&&i&&r.push(""),e.contents.commentBefore){let f=a(e.contents.commentBefore);r.push(ui.indentComment(f,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Ps.stringify(e.contents,n,()=>s=null,c);s&&(l+=ui.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(Ps.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
58
+ `)?(r.push("..."),r.push(ui.indentComment(c,""))):r.push(`... ${c}`)}else r.push("...");else{let c=e.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&r[r.length-1]!==""&&r.push(""),r.push(ui.indentComment(a(c),"")))}return r.join(`
59
59
  `)+`
60
- `}sd.stringifyDocument=aw});var ii=b(ld=>{"use strict";var ow=Mr(),lr=dn(),Se=R(),sw=yt(),cw=mt(),lw=ms(),uw=cd(),gs=sn(),dw=bo(),fw=Fr(),ws=No(),ys=class e{constructor(t,r,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Se.NODE_TYPE,{value:Se.DOC});let n=null;typeof r=="function"||Array.isArray(r)?n=r:i===void 0&&r&&(i=r,r=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},i);this.options=a;let{version:o}=a;i?._directives?(this.directives=i._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new ws.Directives({version:o}),this.setSchema(o,i),this.contents=t===void 0?null:this.createNode(t,n,i)}clone(){let t=Object.create(e.prototype,{[Se.NODE_TYPE]:{value:Se.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=Se.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){ur(this.contents)&&this.contents.add(t)}addIn(t,r){ur(this.contents)&&this.contents.addIn(t,r)}createAlias(t,r){if(!t.anchor){let i=gs.anchorNames(this);t.anchor=!r||i.has(r)?gs.findNewAnchor(r||"a",i):r}return new ow.Alias(t.anchor)}createNode(t,r,i){let n;if(typeof r=="function")t=r.call({"":t},"",t),n=r;else if(Array.isArray(r)){let p=g=>typeof g=="number"||g instanceof String||g instanceof Number,y=r.filter(p).map(String);y.length>0&&(r=r.concat(y)),n=r}else i===void 0&&r&&(i=r,r=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:f}=i??{},{onAnchor:d,setAnchors:u,sourceObjects:h}=gs.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:h},m=fw.createNode(t,f,v);return s&&Se.isCollection(m)&&(m.flow=!0),u(),m}createPair(t,r,i={}){let n=this.createNode(t,null,i),a=this.createNode(r,null,i);return new sw.Pair(n,a)}delete(t){return ur(this.contents)?this.contents.delete(t):!1}deleteIn(t){return lr.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):ur(this.contents)?this.contents.deleteIn(t):!1}get(t,r){return Se.isCollection(this.contents)?this.contents.get(t,r):void 0}getIn(t,r){return lr.isEmptyPath(t)?!r&&Se.isScalar(this.contents)?this.contents.value:this.contents:Se.isCollection(this.contents)?this.contents.getIn(t,r):void 0}has(t){return Se.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return lr.isEmptyPath(t)?this.contents!==void 0:Se.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,r){this.contents==null?this.contents=lr.collectionFromPath(this.schema,[t],r):ur(this.contents)&&this.contents.set(t,r)}setIn(t,r){lr.isEmptyPath(t)?this.contents=r:this.contents==null?this.contents=lr.collectionFromPath(this.schema,Array.from(t),r):ur(this.contents)&&this.contents.setIn(t,r)}setSchema(t,r={}){typeof t=="number"&&(t=String(t));let i;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new ws.Directives({version:"1.1"}),i={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new ws.Directives({version:t}),i={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,i=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(r.schema instanceof Object)this.schema=r.schema;else if(i)this.schema=new lw.Schema(Object.assign(i,r));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:r,mapAsMap:i,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=cw.toJS(this.contents,r??"",s);if(typeof a=="function")for(let{count:l,res:f}of s.anchors.values())a(f,l);return typeof o=="function"?dw.applyReviver(o,{"":c},"",c):c}toJSON(t,r){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:r})}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 r=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${r}`)}return uw.stringifyDocument(this,t)}};function ur(e){if(Se.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}ld.Document=ys});var oi=b(ai=>{"use strict";var ni=class extends Error{constructor(t,r,i,n){super(),this.name=t,this.code=i,this.message=n,this.pos=r}},Ns=class extends ni{constructor(t,r,i){super("YAMLParseError",t,r,i)}},bs=class extends ni{constructor(t,r,i){super("YAMLWarning",t,r,i)}},hw=(e,t)=>r=>{if(r.pos[0]===-1)return;r.linePos=r.pos.map(s=>t.linePos(s));let{line:i,col:n}=r.linePos[0];r.message+=` at line ${i}, column ${n}`;let a=n-1,o=e.substring(t.lineStarts[i-1],t.lineStarts[i]).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)+"…"),i>1&&/^ *$/.test(o.substring(0,a))){let s=e.substring(t.lineStarts[i-2],t.lineStarts[i-1]);s.length>80&&(s=s.substring(0,79)+`…
60
+ `}bd.stringifyDocument=Iw});var di=k(Sd=>{"use strict";var Tw=Kr(),vr=Nn(),xe=A(),jw=Et(),$w=Nt(),Ow=Cs(),Hw=kd(),Rs=vn(),Dw=To(),Bw=Yr(),As=Io(),_s=class e{constructor(t,r,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,xe.NODE_TYPE,{value:xe.DOC});let n=null;typeof r=="function"||Array.isArray(r)?n=r:i===void 0&&r&&(i=r,r=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},i);this.options=a;let{version:o}=a;i?._directives?(this.directives=i._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new As.Directives({version:o}),this.setSchema(o,i),this.contents=t===void 0?null:this.createNode(t,n,i)}clone(){let t=Object.create(e.prototype,{[xe.NODE_TYPE]:{value:xe.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=xe.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){gr(this.contents)&&this.contents.add(t)}addIn(t,r){gr(this.contents)&&this.contents.addIn(t,r)}createAlias(t,r){if(!t.anchor){let i=Rs.anchorNames(this);t.anchor=!r||i.has(r)?Rs.findNewAnchor(r||"a",i):r}return new Tw.Alias(t.anchor)}createNode(t,r,i){let n;if(typeof r=="function")t=r.call({"":t},"",t),n=r;else if(Array.isArray(r)){let h=w=>typeof w=="number"||w instanceof String||w instanceof Number,g=r.filter(h).map(String);g.length>0&&(r=r.concat(g)),n=r}else i===void 0&&r&&(i=r,r=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:f}=i??{},{onAnchor:u,setAnchors:d,sourceObjects:p}=Rs.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:p},m=Bw.createNode(t,f,v);return s&&xe.isCollection(m)&&(m.flow=!0),d(),m}createPair(t,r,i={}){let n=this.createNode(t,null,i),a=this.createNode(r,null,i);return new jw.Pair(n,a)}delete(t){return gr(this.contents)?this.contents.delete(t):!1}deleteIn(t){return vr.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):gr(this.contents)?this.contents.deleteIn(t):!1}get(t,r){return xe.isCollection(this.contents)?this.contents.get(t,r):void 0}getIn(t,r){return vr.isEmptyPath(t)?!r&&xe.isScalar(this.contents)?this.contents.value:this.contents:xe.isCollection(this.contents)?this.contents.getIn(t,r):void 0}has(t){return xe.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return vr.isEmptyPath(t)?this.contents!==void 0:xe.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,r){this.contents==null?this.contents=vr.collectionFromPath(this.schema,[t],r):gr(this.contents)&&this.contents.set(t,r)}setIn(t,r){vr.isEmptyPath(t)?this.contents=r:this.contents==null?this.contents=vr.collectionFromPath(this.schema,Array.from(t),r):gr(this.contents)&&this.contents.setIn(t,r)}setSchema(t,r={}){typeof t=="number"&&(t=String(t));let i;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new As.Directives({version:"1.1"}),i={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new As.Directives({version:t}),i={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,i=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(r.schema instanceof Object)this.schema=r.schema;else if(i)this.schema=new Ow.Schema(Object.assign(i,r));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:r,mapAsMap:i,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=$w.toJS(this.contents,r??"",s);if(typeof a=="function")for(let{count:l,res:f}of s.anchors.values())a(f,l);return typeof o=="function"?Dw.applyReviver(o,{"":c},"",c):c}toJSON(t,r){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:r})}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 r=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${r}`)}return Hw.stringifyDocument(this,t)}};function gr(e){if(xe.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Sd.Document=_s});var hi=k(pi=>{"use strict";var fi=class extends Error{constructor(t,r,i,n){super(),this.name=t,this.code=i,this.message=n,this.pos=r}},Is=class extends fi{constructor(t,r,i){super("YAMLParseError",t,r,i)}},Ts=class extends fi{constructor(t,r,i){super("YAMLWarning",t,r,i)}},Lw=(e,t)=>r=>{if(r.pos[0]===-1)return;r.linePos=r.pos.map(s=>t.linePos(s));let{line:i,col:n}=r.linePos[0];r.message+=` at line ${i}, column ${n}`;let a=n-1,o=e.substring(t.lineStarts[i-1],t.lineStarts[i]).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)+"…"),i>1&&/^ *$/.test(o.substring(0,a))){let s=e.substring(t.lineStarts[i-2],t.lineStarts[i-1]);s.length>80&&(s=s.substring(0,79)+`…
61
61
  `),o=s+o}if(/[^ ]/.test(o)){let s=1,c=r.linePos[1];c?.line===i&&c.col>n&&(s=Math.max(1,Math.min(c.col-n,80-a)));let l=" ".repeat(a)+"^".repeat(s);r.message+=`:
62
62
 
63
63
  ${o}
64
64
  ${l}
65
- `}};ai.YAMLError=ni;ai.YAMLParseError=Ns;ai.YAMLWarning=bs;ai.prettifyError=hw});var si=b(ud=>{"use strict";function pw(e,{flow:t,indicator:r,next:i,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,f=s,d="",u="",h=!1,v=!1,m=null,p=null,y=null,g=null,w=null,k=null,S=null;for(let N of e)switch(v&&(N.type!=="space"&&N.type!=="newline"&&N.type!=="comma"&&a(N.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),m&&(l&&N.type!=="comment"&&N.type!=="newline"&&a(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),N.type){case"space":!t&&(r!=="doc-start"||i?.type!=="flow-collection")&&N.source.includes(" ")&&(m=N),f=!0;break;case"comment":{f||a(N,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let _=N.source.substring(1)||" ";d?d+=u+_:d=_,u="",l=!1;break}case"newline":l?d?d+=N.source:(!k||r!=="seq-item-ind")&&(c=!0):u+=N.source,l=!0,h=!0,(p||y)&&(g=N),f=!0;break;case"anchor":p&&a(N,"MULTIPLE_ANCHORS","A node can have at most one anchor"),N.source.endsWith(":")&&a(N.offset+N.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),p=N,S??(S=N.offset),l=!1,f=!1,v=!0;break;case"tag":{y&&a(N,"MULTIPLE_TAGS","A node can have at most one tag"),y=N,S??(S=N.offset),l=!1,f=!1,v=!0;break}case r:(p||y)&&a(N,"BAD_PROP_ORDER",`Anchors and tags must be after the ${N.source} indicator`),k&&a(N,"UNEXPECTED_TOKEN",`Unexpected ${N.source} in ${t??"collection"}`),k=N,l=r==="seq-item-ind"||r==="explicit-key-ind",f=!1;break;case"comma":if(t){w&&a(N,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),w=N,l=!1,f=!1;break}default:a(N,"UNEXPECTED_TOKEN",`Unexpected ${N.type} token`),l=!1,f=!1}let E=e[e.length-1],x=E?E.offset+E.source.length:n;return v&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&a(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m&&(l&&m.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&a(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:w,found:k,spaceBefore:c,comment:d,hasNewline:h,anchor:p,tag:y,newlineAfterProp:g,end:x,start:S??x}}ud.resolveProps=pw});var Jn=b(dd=>{"use strict";function ks(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 r of t.start)if(r.type==="newline")return!0;if(t.sep){for(let r of t.sep)if(r.type==="newline")return!0}if(ks(t.key)||ks(t.value))return!0}return!1;default:return!0}}dd.containsNewline=ks});var Ss=b(fd=>{"use strict";var mw=Jn();function vw(e,t,r){if(t?.type==="flow-collection"){let i=t.end[0];i.indent===e&&(i.source==="]"||i.source==="}")&&mw.containsNewline(t)&&r(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}fd.flowIndentCheck=vw});var Es=b(pd=>{"use strict";var hd=R();function gw(e,t,r){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let n=typeof i=="function"?i:(a,o)=>a===o||hd.isScalar(a)&&hd.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,r))}pd.mapIncludes=gw});var Nd=b(yd=>{"use strict";var md=yt(),ww=bt(),vd=si(),yw=Jn(),gd=Ss(),Nw=Es(),wd="All mapping items must start at the same column";function bw({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??ww.YAMLMap,s=new o(r.schema);r.atRoot&&(r.atRoot=!1);let c=i.offset,l=null;for(let f of i.items){let{start:d,key:u,sep:h,value:v}=f,m=vd.resolveProps(d,{indicator:"explicit-key-ind",next:u??h?.[0],offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0}),p=!m.found;if(p){if(u&&(u.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in u&&u.indent!==i.indent&&n(c,"BAD_INDENT",wd)),!m.anchor&&!m.tag&&!h){l=m.end,m.comment&&(s.comment?s.comment+=`
67
- `+m.comment:s.comment=m.comment);continue}(m.newlineAfterProp||yw.containsNewline(u))&&n(u??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else m.found?.indent!==i.indent&&n(c,"BAD_INDENT",wd);r.atKey=!0;let y=m.end,g=u?e(r,u,m,n):t(r,y,d,null,m,n);r.schema.compat&&gd.flowIndentCheck(i.indent,u,n),r.atKey=!1,Nw.mapIncludes(r,s.items,g)&&n(y,"DUPLICATE_KEY","Map keys must be unique");let w=vd.resolveProps(h??[],{indicator:"map-value-ind",next:v,offset:g.range[2],onError:n,parentIndent:i.indent,startOnNewline:!u||u.type==="block-scalar"});if(c=w.end,w.found){p&&(v?.type==="block-map"&&!w.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&m.start<w.found.offset-1024&&n(g.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let k=v?e(r,v,w,n):t(r,c,h,null,w,n);r.schema.compat&&gd.flowIndentCheck(i.indent,v,n),c=k.range[2];let S=new md.Pair(g,k);r.options.keepSourceTokens&&(S.srcToken=f),s.items.push(S)}else{p&&n(g.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),w.comment&&(g.comment?g.comment+=`
68
- `+w.comment:g.comment=w.comment);let k=new md.Pair(g);r.options.keepSourceTokens&&(k.srcToken=f),s.items.push(k)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[i.offset,c,l??c],s}yd.resolveBlockMap=bw});var kd=b(bd=>{"use strict";var kw=kt(),Sw=si(),Ew=Ss();function xw({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??kw.YAMLSeq,s=new o(r.schema);r.atRoot&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let c=i.offset,l=null;for(let{start:f,value:d}of i.items){let u=Sw.resolveProps(f,{indicator:"seq-item-ind",next:d,offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0});if(!u.found)if(u.anchor||u.tag||d)d?.type==="block-seq"?n(u.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=u.end,u.comment&&(s.comment=u.comment);continue}let h=d?e(r,d,u,n):t(r,u.end,f,null,u,n);r.schema.compat&&Ew.flowIndentCheck(i.indent,d,n),c=h.range[2],s.items.push(h)}return s.range=[i.offset,c,l??c],s}bd.resolveBlockSeq=xw});var dr=b(Sd=>{"use strict";function Pw(e,t,r,i){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":{r&&!a&&i(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let f=c.substring(1)||" ";n?n+=o+f:n=f,o="";break}case"newline":n&&(o+=c),a=!0;break;default:i(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:n,offset:t}}Sd.resolveEnd=Pw});var Cd=b(Pd=>{"use strict";var Cw=R(),Rw=yt(),Ed=bt(),Aw=kt(),_w=dr(),xd=si(),Iw=Jn(),Tw=Es(),xs="Block collections are not allowed within flow collections",Ps=e=>e&&(e.type==="block-map"||e.type==="block-seq");function jw({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=i.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Ed.YAMLMap:Aw.YAMLSeq),l=new c(r.schema);l.flow=!0;let f=r.atRoot;f&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let d=i.offset+i.start.source.length;for(let p=0;p<i.items.length;++p){let y=i.items[p],{start:g,key:w,sep:k,value:S}=y,E=xd.resolveProps(g,{flow:s,indicator:"explicit-key-ind",next:w??k?.[0],offset:d,onError:n,parentIndent:i.indent,startOnNewline:!1});if(!E.found){if(!E.anchor&&!E.tag&&!k&&!S){p===0&&E.comma?n(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):p<i.items.length-1&&n(E.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),E.comment&&(l.comment?l.comment+=`
69
- `+E.comment:l.comment=E.comment),d=E.end;continue}!o&&r.options.strict&&Iw.containsNewline(w)&&n(w,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(p===0)E.comma&&n(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(E.comma||n(E.start,"MISSING_CHAR",`Missing , between ${s} items`),E.comment){let x="";e:for(let N of g)switch(N.type){case"comma":case"space":break;case"comment":x=N.source.substring(1);break e;default:break e}if(x){let N=l.items[l.items.length-1];Cw.isPair(N)&&(N=N.value??N.key),N.comment?N.comment+=`
70
- `+x:N.comment=x,E.comment=E.comment.substring(x.length+1)}}if(!o&&!k&&!E.found){let x=S?e(r,S,E,n):t(r,E.end,k,null,E,n);l.items.push(x),d=x.range[2],Ps(S)&&n(x.range,"BLOCK_IN_FLOW",xs)}else{r.atKey=!0;let x=E.end,N=w?e(r,w,E,n):t(r,x,g,null,E,n);Ps(w)&&n(N.range,"BLOCK_IN_FLOW",xs),r.atKey=!1;let _=xd.resolveProps(k??[],{flow:s,indicator:"map-value-ind",next:S,offset:N.range[2],onError:n,parentIndent:i.indent,startOnNewline:!1});if(_.found){if(!o&&!E.found&&r.options.strict){if(k)for(let $ of k){if($===_.found)break;if($.type==="newline"){n($,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}E.start<_.found.offset-1024&&n(_.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else S&&("source"in S&&S.source?.[0]===":"?n(S,"MISSING_CHAR",`Missing space after : in ${s}`):n(_.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let Y=S?e(r,S,_,n):_.found?t(r,_.end,k,null,_,n):null;Y?Ps(S)&&n(Y.range,"BLOCK_IN_FLOW",xs):_.comment&&(N.comment?N.comment+=`
71
- `+_.comment:N.comment=_.comment);let ee=new Rw.Pair(N,Y);if(r.options.keepSourceTokens&&(ee.srcToken=y),o){let $=l;Tw.mapIncludes(r,$.items,N)&&n(x,"DUPLICATE_KEY","Map keys must be unique"),$.items.push(ee)}else{let $=new Ed.YAMLMap(r.schema);$.flow=!0,$.items.push(ee);let Pl=(Y??N).range;$.range=[N.range[0],Pl[1],Pl[2]],l.items.push($)}d=Y?Y.range[2]:_.end}}let u=o?"}":"]",[h,...v]=i.end,m=d;if(h?.source===u)m=h.offset+h.source.length;else{let p=s[0].toUpperCase()+s.substring(1),y=f?`${p} must end with a ${u}`:`${p} in block collection must be sufficiently indented and end with a ${u}`;n(d,f?"MISSING_CHAR":"BAD_INDENT",y),h&&h.source.length!==1&&v.unshift(h)}if(v.length>0){let p=_w.resolveEnd(v,m,r.options.strict,n);p.comment&&(l.comment?l.comment+=`
72
- `+p.comment:l.comment=p.comment),l.range=[i.offset,m,p.offset]}else l.range=[i.offset,m,m];return l}Pd.resolveFlowCollection=jw});var Ad=b(Rd=>{"use strict";var $w=R(),Ow=W(),Hw=bt(),Dw=kt(),Bw=Nd(),Lw=kd(),Vw=Cd();function Cs(e,t,r,i,n,a){let o=r.type==="block-map"?Bw.resolveBlockMap(e,t,r,i,a):r.type==="block-seq"?Lw.resolveBlockSeq(e,t,r,i,a):Vw.resolveFlowCollection(e,t,r,i,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function Mw(e,t,r,i,n){let a=i.tag,o=a?t.directives.tagName(a.source,u=>n(a,"TAG_RESOLVE_FAILED",u)):null;if(r.type==="block-seq"){let{anchor:u,newlineAfterProp:h}=i,v=u&&a?u.offset>a.offset?u:a:u??a;v&&(!h||h.offset<v.offset)&&n(v,"MISSING_CHAR","Missing newline after block sequence props")}let s=r.type==="block-map"?"map":r.type==="block-seq"?"seq":r.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===Hw.YAMLMap.tagName&&s==="map"||o===Dw.YAMLSeq.tagName&&s==="seq")return Cs(e,t,r,n,o);let c=t.schema.tags.find(u=>u.tag===o&&u.collection===s);if(!c){let u=t.schema.knownTags[o];if(u?.collection===s)t.schema.tags.push(Object.assign({},u,{default:!1})),c=u;else return u?n(a,"BAD_COLLECTION_TYPE",`${u.tag} used for ${s} collection, but expects ${u.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Cs(e,t,r,n,o)}let l=Cs(e,t,r,n,o,c),f=c.resolve?.(l,u=>n(a,"TAG_RESOLVE_FAILED",u),t.options)??l,d=$w.isNode(f)?f:new Ow.Scalar(f);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}Rd.composeCollection=Mw});var As=b(_d=>{"use strict";var Rs=W();function Fw(e,t,r){let i=t.offset,n=qw(t,e.options.strict,r);if(!n)return{value:"",type:null,comment:"",range:[i,i,i]};let a=n.mode===">"?Rs.Scalar.BLOCK_FOLDED:Rs.Scalar.BLOCK_LITERAL,o=t.source?Ww(t.source):[],s=o.length;for(let m=o.length-1;m>=0;--m){let p=o[m][1];if(p===""||p==="\r")s=m;else break}if(s===0){let m=n.chomp==="+"&&o.length>0?`
73
- `.repeat(Math.max(1,o.length-1)):"",p=i+n.length;return t.source&&(p+=t.source.length),{value:m,type:a,comment:n.comment,range:[i,p,p]}}let c=t.indent+n.indent,l=t.offset+n.length,f=0;for(let m=0;m<s;++m){let[p,y]=o[m];if(y===""||y==="\r")n.indent===0&&p.length>c&&(c=p.length);else{p.length<c&&r(l+p.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(c=p.length),f=m,c===0&&!e.atRoot&&r(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=p.length+y.length+1}for(let m=o.length-1;m>=s;--m)o[m][0].length>c&&(s=m+1);let d="",u="",h=!1;for(let m=0;m<f;++m)d+=o[m][0].slice(c)+`
74
- `;for(let m=f;m<s;++m){let[p,y]=o[m];l+=p.length+y.length+1;let g=y[y.length-1]==="\r";if(g&&(y=y.slice(0,-1)),y&&p.length<c){let k=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;r(l-y.length-(g?2:1),"BAD_INDENT",k),p=""}a===Rs.Scalar.BLOCK_LITERAL?(d+=u+p.slice(c)+y,u=`
75
- `):p.length>c||y[0]===" "?(u===" "?u=`
76
- `:!h&&u===`
77
- `&&(u=`
78
-
79
- `),d+=u+p.slice(c)+y,u=`
80
- `,h=!0):y===""?u===`
81
- `?d+=`
82
- `:u=`
83
- `:(d+=u+y,u=" ",h=!1)}switch(n.chomp){case"-":break;case"+":for(let m=s;m<o.length;++m)d+=`
84
- `+o[m][0].slice(c);d[d.length-1]!==`
85
- `&&(d+=`
86
- `);break;default:d+=`
87
- `}let v=i+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[i,v,v]}}function qw({offset:e,props:t},r,i){if(t[0].type!=="block-scalar-header")return i(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",c=-1;for(let u=1;u<n.length;++u){let h=n[u];if(!s&&(h==="-"||h==="+"))s=h;else{let v=Number(h);!o&&v?o=v:c===-1&&(c=e+u)}}c!==-1&&i(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,f="",d=n.length;for(let u=1;u<t.length;++u){let h=t[u];switch(h.type){case"space":l=!0;case"newline":d+=h.source.length;break;case"comment":r&&!l&&i(h,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=h.source.length,f=h.source.substring(1);break;case"error":i(h,"UNEXPECTED_TOKEN",h.message),d+=h.source.length;break;default:{let v=`Unexpected token in block scalar header: ${h.type}`;i(h,"UNEXPECTED_TOKEN",v);let m=h.source;m&&typeof m=="string"&&(d+=m.length)}}}return{mode:a,indent:o,chomp:s,comment:f,length:d}}function Ww(e){let t=e.split(/\n( *)/),r=t[0],i=r.match(/^( *)/),a=[i?.[1]?[i[1],r.slice(i[1].length)]:["",r]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}_d.resolveBlockScalar=Fw});var Is=b(Td=>{"use strict";var _s=W(),zw=dr();function Jw(e,t,r){let{offset:i,type:n,source:a,end:o}=e,s,c,l=(u,h,v)=>r(i+u,h,v);switch(n){case"scalar":s=_s.Scalar.PLAIN,c=Gw(a,l);break;case"single-quoted-scalar":s=_s.Scalar.QUOTE_SINGLE,c=Uw(a,l);break;case"double-quoted-scalar":s=_s.Scalar.QUOTE_DOUBLE,c=Kw(a,l);break;default:return r(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[i,i+a.length,i+a.length]}}let f=i+a.length,d=zw.resolveEnd(o,f,t,r);return{value:c,type:s,comment:d.comment,range:[i,f,d.offset]}}function Gw(e,t){let r="";switch(e[0]){case" ":r="a tab character";break;case",":r="flow indicator character ,";break;case"%":r="directive indicator character %";break;case"|":case">":{r=`block scalar indicator ${e[0]}`;break}case"@":case"`":{r=`reserved character ${e[0]}`;break}}return r&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${r}`),Id(e)}function Uw(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Id(e.slice(1,-1)).replace(/''/g,"'")}function Id(e){let t,r;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
65
+ `}};pi.YAMLError=fi;pi.YAMLParseError=Is;pi.YAMLWarning=Ts;pi.prettifyError=Lw});var mi=k(Ed=>{"use strict";function Vw(e,{flow:t,indicator:r,next:i,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,f=s,u="",d="",p=!1,v=!1,m=null,h=null,g=null,w=null,y=null,S=null,N=null;for(let b of e)switch(v&&(b.type!=="space"&&b.type!=="newline"&&b.type!=="comma"&&a(b.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),m&&(l&&b.type!=="comment"&&b.type!=="newline"&&a(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),b.type){case"space":!t&&(r!=="doc-start"||i?.type!=="flow-collection")&&b.source.includes(" ")&&(m=b),f=!0;break;case"comment":{f||a(b,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let T=b.source.substring(1)||" ";u?u+=d+T:u=T,d="",l=!1;break}case"newline":l?u?u+=b.source:(!S||r!=="seq-item-ind")&&(c=!0):d+=b.source,l=!0,p=!0,(h||g)&&(w=b),f=!0;break;case"anchor":h&&a(b,"MULTIPLE_ANCHORS","A node can have at most one anchor"),b.source.endsWith(":")&&a(b.offset+b.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),h=b,N??(N=b.offset),l=!1,f=!1,v=!0;break;case"tag":{g&&a(b,"MULTIPLE_TAGS","A node can have at most one tag"),g=b,N??(N=b.offset),l=!1,f=!1,v=!0;break}case r:(h||g)&&a(b,"BAD_PROP_ORDER",`Anchors and tags must be after the ${b.source} indicator`),S&&a(b,"UNEXPECTED_TOKEN",`Unexpected ${b.source} in ${t??"collection"}`),S=b,l=r==="seq-item-ind"||r==="explicit-key-ind",f=!1;break;case"comma":if(t){y&&a(b,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),y=b,l=!1,f=!1;break}default:a(b,"UNEXPECTED_TOKEN",`Unexpected ${b.type} token`),l=!1,f=!1}let E=e[e.length-1],C=E?E.offset+E.source.length:n;return v&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&a(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m&&(l&&m.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&a(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:y,found:S,spaceBefore:c,comment:u,hasNewline:p,anchor:h,tag:g,newlineAfterProp:w,end:C,start:N??C}}Ed.resolveProps=Vw});var ta=k(xd=>{"use strict";function js(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 r of t.start)if(r.type==="newline")return!0;if(t.sep){for(let r of t.sep)if(r.type==="newline")return!0}if(js(t.key)||js(t.value))return!0}return!1;default:return!0}}xd.containsNewline=js});var $s=k(Cd=>{"use strict";var Mw=ta();function Fw(e,t,r){if(t?.type==="flow-collection"){let i=t.end[0];i.indent===e&&(i.source==="]"||i.source==="}")&&Mw.containsNewline(t)&&r(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Cd.flowIndentCheck=Fw});var Os=k(Rd=>{"use strict";var Pd=A();function qw(e,t,r){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let n=typeof i=="function"?i:(a,o)=>a===o||Pd.isScalar(a)&&Pd.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,r))}Rd.mapIncludes=qw});var $d=k(jd=>{"use strict";var Ad=Et(),Ww=Ct(),_d=mi(),zw=ta(),Id=$s(),Jw=Os(),Td="All mapping items must start at the same column";function Gw({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??Ww.YAMLMap,s=new o(r.schema);r.atRoot&&(r.atRoot=!1);let c=i.offset,l=null;for(let f of i.items){let{start:u,key:d,sep:p,value:v}=f,m=_d.resolveProps(u,{indicator:"explicit-key-ind",next:d??p?.[0],offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0}),h=!m.found;if(h){if(d&&(d.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in d&&d.indent!==i.indent&&n(c,"BAD_INDENT",Td)),!m.anchor&&!m.tag&&!p){l=m.end,m.comment&&(s.comment?s.comment+=`
67
+ `+m.comment:s.comment=m.comment);continue}(m.newlineAfterProp||zw.containsNewline(d))&&n(d??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else m.found?.indent!==i.indent&&n(c,"BAD_INDENT",Td);r.atKey=!0;let g=m.end,w=d?e(r,d,m,n):t(r,g,u,null,m,n);r.schema.compat&&Id.flowIndentCheck(i.indent,d,n),r.atKey=!1,Jw.mapIncludes(r,s.items,w)&&n(g,"DUPLICATE_KEY","Map keys must be unique");let y=_d.resolveProps(p??[],{indicator:"map-value-ind",next:v,offset:w.range[2],onError:n,parentIndent:i.indent,startOnNewline:!d||d.type==="block-scalar"});if(c=y.end,y.found){h&&(v?.type==="block-map"&&!y.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&m.start<y.found.offset-1024&&n(w.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let S=v?e(r,v,y,n):t(r,c,p,null,y,n);r.schema.compat&&Id.flowIndentCheck(i.indent,v,n),c=S.range[2];let N=new Ad.Pair(w,S);r.options.keepSourceTokens&&(N.srcToken=f),s.items.push(N)}else{h&&n(w.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),y.comment&&(w.comment?w.comment+=`
68
+ `+y.comment:w.comment=y.comment);let S=new Ad.Pair(w);r.options.keepSourceTokens&&(S.srcToken=f),s.items.push(S)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[i.offset,c,l??c],s}jd.resolveBlockMap=Gw});var Hd=k(Od=>{"use strict";var Uw=Pt(),Kw=mi(),Yw=$s();function Xw({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??Uw.YAMLSeq,s=new o(r.schema);r.atRoot&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let c=i.offset,l=null;for(let{start:f,value:u}of i.items){let d=Kw.resolveProps(f,{indicator:"seq-item-ind",next:u,offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||u)u?.type==="block-seq"?n(d.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=d.end,d.comment&&(s.comment=d.comment);continue}let p=u?e(r,u,d,n):t(r,d.end,f,null,d,n);r.schema.compat&&Yw.flowIndentCheck(i.indent,u,n),c=p.range[2],s.items.push(p)}return s.range=[i.offset,c,l??c],s}Od.resolveBlockSeq=Xw});var wr=k(Dd=>{"use strict";function Qw(e,t,r,i){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":{r&&!a&&i(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let f=c.substring(1)||" ";n?n+=o+f:n=f,o="";break}case"newline":n&&(o+=c),a=!0;break;default:i(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:n,offset:t}}Dd.resolveEnd=Qw});var Md=k(Vd=>{"use strict";var Zw=A(),ey=Et(),Bd=Ct(),ty=Pt(),ry=wr(),Ld=mi(),iy=ta(),ny=Os(),Hs="Block collections are not allowed within flow collections",Ds=e=>e&&(e.type==="block-map"||e.type==="block-seq");function ay({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=i.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Bd.YAMLMap:ty.YAMLSeq),l=new c(r.schema);l.flow=!0;let f=r.atRoot;f&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let u=i.offset+i.start.source.length;for(let h=0;h<i.items.length;++h){let g=i.items[h],{start:w,key:y,sep:S,value:N}=g,E=Ld.resolveProps(w,{flow:s,indicator:"explicit-key-ind",next:y??S?.[0],offset:u,onError:n,parentIndent:i.indent,startOnNewline:!1});if(!E.found){if(!E.anchor&&!E.tag&&!S&&!N){h===0&&E.comma?n(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):h<i.items.length-1&&n(E.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),E.comment&&(l.comment?l.comment+=`
69
+ `+E.comment:l.comment=E.comment),u=E.end;continue}!o&&r.options.strict&&iy.containsNewline(y)&&n(y,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(h===0)E.comma&&n(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(E.comma||n(E.start,"MISSING_CHAR",`Missing , between ${s} items`),E.comment){let C="";e:for(let b of w)switch(b.type){case"comma":case"space":break;case"comment":C=b.source.substring(1);break e;default:break e}if(C){let b=l.items[l.items.length-1];Zw.isPair(b)&&(b=b.value??b.key),b.comment?b.comment+=`
70
+ `+C:b.comment=C,E.comment=E.comment.substring(C.length+1)}}if(!o&&!S&&!E.found){let C=N?e(r,N,E,n):t(r,E.end,S,null,E,n);l.items.push(C),u=C.range[2],Ds(N)&&n(C.range,"BLOCK_IN_FLOW",Hs)}else{r.atKey=!0;let C=E.end,b=y?e(r,y,E,n):t(r,C,w,null,E,n);Ds(y)&&n(b.range,"BLOCK_IN_FLOW",Hs),r.atKey=!1;let T=Ld.resolveProps(S??[],{flow:s,indicator:"map-value-ind",next:N,offset:b.range[2],onError:n,parentIndent:i.indent,startOnNewline:!1});if(T.found){if(!o&&!E.found&&r.options.strict){if(S)for(let j of S){if(j===T.found)break;if(j.type==="newline"){n(j,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}E.start<T.found.offset-1024&&n(T.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else N&&("source"in N&&N.source?.[0]===":"?n(N,"MISSING_CHAR",`Missing space after : in ${s}`):n(T.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let F=N?e(r,N,T,n):T.found?t(r,T.end,S,null,T,n):null;F?Ds(N)&&n(F.range,"BLOCK_IN_FLOW",Hs):T.comment&&(b.comment?b.comment+=`
71
+ `+T.comment:b.comment=T.comment);let Z=new ey.Pair(b,F);if(r.options.keepSourceTokens&&(Z.srcToken=g),o){let j=l;ny.mapIncludes(r,j.items,b)&&n(C,"DUPLICATE_KEY","Map keys must be unique"),j.items.push(Z)}else{let j=new Bd.YAMLMap(r.schema);j.flow=!0,j.items.push(Z);let yt=(F??b).range;j.range=[b.range[0],yt[1],yt[2]],l.items.push(j)}u=F?F.range[2]:T.end}}let d=o?"}":"]",[p,...v]=i.end,m=u;if(p?.source===d)m=p.offset+p.source.length;else{let h=s[0].toUpperCase()+s.substring(1),g=f?`${h} must end with a ${d}`:`${h} in block collection must be sufficiently indented and end with a ${d}`;n(u,f?"MISSING_CHAR":"BAD_INDENT",g),p&&p.source.length!==1&&v.unshift(p)}if(v.length>0){let h=ry.resolveEnd(v,m,r.options.strict,n);h.comment&&(l.comment?l.comment+=`
72
+ `+h.comment:l.comment=h.comment),l.range=[i.offset,m,h.offset]}else l.range=[i.offset,m,m];return l}Vd.resolveFlowCollection=ay});var qd=k(Fd=>{"use strict";var oy=A(),sy=J(),cy=Ct(),ly=Pt(),uy=$d(),dy=Hd(),fy=Md();function Bs(e,t,r,i,n,a){let o=r.type==="block-map"?uy.resolveBlockMap(e,t,r,i,a):r.type==="block-seq"?dy.resolveBlockSeq(e,t,r,i,a):fy.resolveFlowCollection(e,t,r,i,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function py(e,t,r,i,n){let a=i.tag,o=a?t.directives.tagName(a.source,d=>n(a,"TAG_RESOLVE_FAILED",d)):null;if(r.type==="block-seq"){let{anchor:d,newlineAfterProp:p}=i,v=d&&a?d.offset>a.offset?d:a:d??a;v&&(!p||p.offset<v.offset)&&n(v,"MISSING_CHAR","Missing newline after block sequence props")}let s=r.type==="block-map"?"map":r.type==="block-seq"?"seq":r.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===cy.YAMLMap.tagName&&s==="map"||o===ly.YAMLSeq.tagName&&s==="seq")return Bs(e,t,r,n,o);let c=t.schema.tags.find(d=>d.tag===o&&d.collection===s);if(!c){let d=t.schema.knownTags[o];if(d?.collection===s)t.schema.tags.push(Object.assign({},d,{default:!1})),c=d;else return d?n(a,"BAD_COLLECTION_TYPE",`${d.tag} used for ${s} collection, but expects ${d.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Bs(e,t,r,n,o)}let l=Bs(e,t,r,n,o,c),f=c.resolve?.(l,d=>n(a,"TAG_RESOLVE_FAILED",d),t.options)??l,u=oy.isNode(f)?f:new sy.Scalar(f);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}Fd.composeCollection=py});var Vs=k(Wd=>{"use strict";var Ls=J();function hy(e,t,r){let i=t.offset,n=my(t,e.options.strict,r);if(!n)return{value:"",type:null,comment:"",range:[i,i,i]};let a=n.mode===">"?Ls.Scalar.BLOCK_FOLDED:Ls.Scalar.BLOCK_LITERAL,o=t.source?vy(t.source):[],s=o.length;for(let m=o.length-1;m>=0;--m){let h=o[m][1];if(h===""||h==="\r")s=m;else break}if(s===0){let m=n.chomp==="+"&&o.length>0?`
73
+ `.repeat(Math.max(1,o.length-1)):"",h=i+n.length;return t.source&&(h+=t.source.length),{value:m,type:a,comment:n.comment,range:[i,h,h]}}let c=t.indent+n.indent,l=t.offset+n.length,f=0;for(let m=0;m<s;++m){let[h,g]=o[m];if(g===""||g==="\r")n.indent===0&&h.length>c&&(c=h.length);else{h.length<c&&r(l+h.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(c=h.length),f=m,c===0&&!e.atRoot&&r(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=h.length+g.length+1}for(let m=o.length-1;m>=s;--m)o[m][0].length>c&&(s=m+1);let u="",d="",p=!1;for(let m=0;m<f;++m)u+=o[m][0].slice(c)+`
74
+ `;for(let m=f;m<s;++m){let[h,g]=o[m];l+=h.length+g.length+1;let w=g[g.length-1]==="\r";if(w&&(g=g.slice(0,-1)),g&&h.length<c){let S=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;r(l-g.length-(w?2:1),"BAD_INDENT",S),h=""}a===Ls.Scalar.BLOCK_LITERAL?(u+=d+h.slice(c)+g,d=`
75
+ `):h.length>c||g[0]===" "?(d===" "?d=`
76
+ `:!p&&d===`
77
+ `&&(d=`
78
+
79
+ `),u+=d+h.slice(c)+g,d=`
80
+ `,p=!0):g===""?d===`
81
+ `?u+=`
82
+ `:d=`
83
+ `:(u+=d+g,d=" ",p=!1)}switch(n.chomp){case"-":break;case"+":for(let m=s;m<o.length;++m)u+=`
84
+ `+o[m][0].slice(c);u[u.length-1]!==`
85
+ `&&(u+=`
86
+ `);break;default:u+=`
87
+ `}let v=i+n.length+t.source.length;return{value:u,type:a,comment:n.comment,range:[i,v,v]}}function my({offset:e,props:t},r,i){if(t[0].type!=="block-scalar-header")return i(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",c=-1;for(let d=1;d<n.length;++d){let p=n[d];if(!s&&(p==="-"||p==="+"))s=p;else{let v=Number(p);!o&&v?o=v:c===-1&&(c=e+d)}}c!==-1&&i(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,f="",u=n.length;for(let d=1;d<t.length;++d){let p=t[d];switch(p.type){case"space":l=!0;case"newline":u+=p.source.length;break;case"comment":r&&!l&&i(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),u+=p.source.length,f=p.source.substring(1);break;case"error":i(p,"UNEXPECTED_TOKEN",p.message),u+=p.source.length;break;default:{let v=`Unexpected token in block scalar header: ${p.type}`;i(p,"UNEXPECTED_TOKEN",v);let m=p.source;m&&typeof m=="string"&&(u+=m.length)}}}return{mode:a,indent:o,chomp:s,comment:f,length:u}}function vy(e){let t=e.split(/\n( *)/),r=t[0],i=r.match(/^( *)/),a=[i?.[1]?[i[1],r.slice(i[1].length)]:["",r]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}Wd.resolveBlockScalar=hy});var Fs=k(Jd=>{"use strict";var Ms=J(),gy=wr();function wy(e,t,r){let{offset:i,type:n,source:a,end:o}=e,s,c,l=(d,p,v)=>r(i+d,p,v);switch(n){case"scalar":s=Ms.Scalar.PLAIN,c=yy(a,l);break;case"single-quoted-scalar":s=Ms.Scalar.QUOTE_SINGLE,c=Ny(a,l);break;case"double-quoted-scalar":s=Ms.Scalar.QUOTE_DOUBLE,c=by(a,l);break;default:return r(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[i,i+a.length,i+a.length]}}let f=i+a.length,u=gy.resolveEnd(o,f,t,r);return{value:c,type:s,comment:u.comment,range:[i,f,u.offset]}}function yy(e,t){let r="";switch(e[0]){case" ":r="a tab character";break;case",":r="flow indicator character ,";break;case"%":r="directive indicator character %";break;case"|":case">":{r=`block scalar indicator ${e[0]}`;break}case"@":case"`":{r=`reserved character ${e[0]}`;break}}return r&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${r}`),zd(e)}function Ny(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),zd(e.slice(1,-1)).replace(/''/g,"'")}function zd(e){let t,r;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
88
88
  `,"sy"),r=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
89
89
  `,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,r=/[ \t]*(.*?)[ \t]*\r?\n/sy}let i=t.exec(e);if(!i)return e;let n=i[1],a=" ",o=t.lastIndex;for(r.lastIndex=o;i=r.exec(e);)i[1]===""?a===`
90
90
  `?n+=a:a=`
91
- `:(n+=a+i[1],a=" "),o=r.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,i=s.exec(e),n+a+(i?.[1]??"")}function Kw(e,t){let r="";for(let i=1;i<e.length-1;++i){let n=e[i];if(!(n==="\r"&&e[i+1]===`
91
+ `:(n+=a+i[1],a=" "),o=r.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,i=s.exec(e),n+a+(i?.[1]??"")}function by(e,t){let r="";for(let i=1;i<e.length-1;++i){let n=e[i];if(!(n==="\r"&&e[i+1]===`
92
92
  `))if(n===`
93
- `){let{fold:a,offset:o}=Yw(e,i);r+=a,i=o}else if(n==="\\"){let a=e[++i],o=Xw[a];if(o)r+=o;else if(a===`
93
+ `){let{fold:a,offset:o}=ky(e,i);r+=a,i=o}else if(n==="\\"){let a=e[++i],o=Sy[a];if(o)r+=o;else if(a===`
94
94
  `)for(a=e[i+1];a===" "||a===" ";)a=e[++i+1];else if(a==="\r"&&e[i+1]===`
95
- `)for(a=e[++i+1];a===" "||a===" ";)a=e[++i+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;r+=Qw(e,i+1,s,t),i+=s}else{let s=e.substr(i-1,2);t(i-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),r+=s}}else if(n===" "||n===" "){let a=i,o=e[i+1];for(;o===" "||o===" ";)o=e[++i+1];o!==`
95
+ `)for(a=e[++i+1];a===" "||a===" ";)a=e[++i+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;r+=Ey(e,i+1,s,t),i+=s}else{let s=e.substr(i-1,2);t(i-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),r+=s}}else if(n===" "||n===" "){let a=i,o=e[i+1];for(;o===" "||o===" ";)o=e[++i+1];o!==`
96
96
  `&&!(o==="\r"&&e[i+2]===`
97
- `)&&(r+=i>a?e.slice(a,i+1):n)}else r+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),r}function Yw(e,t){let r="",i=e[t+1];for(;(i===" "||i===" "||i===`
97
+ `)&&(r+=i>a?e.slice(a,i+1):n)}else r+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),r}function ky(e,t){let r="",i=e[t+1];for(;(i===" "||i===" "||i===`
98
98
  `||i==="\r")&&!(i==="\r"&&e[t+2]!==`
99
99
  `);)i===`
100
100
  `&&(r+=`
101
- `),t+=1,i=e[t+1];return r||(r=" "),{fold:r,offset:t}}var Xw={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
102
- `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Qw(e,t,r,i){let n=e.substr(t,r),o=n.length===r&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,r+2);return i(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}Td.resolveFlowScalar=Jw});var Od=b($d=>{"use strict";var Ft=R(),jd=W(),Zw=As(),ey=Is();function ty(e,t,r,i){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?Zw.resolveBlockScalar(e,t,i):ey.resolveFlowScalar(t,e.options.strict,i),c=r?e.directives.tagName(r.source,d=>i(r,"TAG_RESOLVE_FAILED",d)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[Ft.SCALAR]:c?l=ry(e.schema,n,c,r,i):t.type==="scalar"?l=iy(e,n,t,i):l=e.schema[Ft.SCALAR];let f;try{let d=l.resolve(n,u=>i(r??t,"TAG_RESOLVE_FAILED",u),e.options);f=Ft.isScalar(d)?d:new jd.Scalar(d)}catch(d){let u=d instanceof Error?d.message:String(d);i(r??t,"TAG_RESOLVE_FAILED",u),f=new jd.Scalar(n)}return f.range=s,f.source=n,a&&(f.type=a),c&&(f.tag=c),l.format&&(f.format=l.format),o&&(f.comment=o),f}function ry(e,t,r,i,n){if(r==="!")return e[Ft.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===r)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[r];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${r}`,r!=="tag:yaml.org,2002:str"),e[Ft.SCALAR])}function iy({atKey:e,directives:t,schema:r},i,n,a){let o=r.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(i))||r[Ft.SCALAR];if(r.compat){let s=r.compat.find(c=>c.default&&c.test?.test(i))??r[Ft.SCALAR];if(o.tag!==s.tag){let c=t.tagString(o.tag),l=t.tagString(s.tag),f=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",f,!0)}}return o}$d.composeScalar=ty});var Dd=b(Hd=>{"use strict";function ny(e,t,r){if(t){r??(r=t.length);for(let i=r-1;i>=0;--i){let n=t[i];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}for(n=t[++i];n?.type==="space";)e+=n.source.length,n=t[++i];break}}return e}Hd.emptyScalarPosition=ny});var Vd=b(js=>{"use strict";var ay=Mr(),oy=R(),sy=Ad(),Bd=Od(),cy=dr(),ly=Dd(),uy={composeNode:Ld,composeEmptyNode:Ts};function Ld(e,t,r,i){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=r,l,f=!0;switch(t.type){case"alias":l=dy(e,t,i),(s||c)&&i(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=Bd.composeScalar(e,t,c,i),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=sy.composeCollection(uy,e,t,r,i),s&&(l.anchor=s.source.substring(1))}catch(d){let u=d instanceof Error?d.message:String(d);i(t,"RESOURCE_EXHAUSTION",u)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;i(t,"UNEXPECTED_TOKEN",d),f=!1}}return l??(l=Ts(e,t.offset,void 0,null,r,i)),s&&l.anchor===""&&i(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&e.options.stringKeys&&(!oy.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&i(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&&f&&(l.srcToken=t),l}function Ts(e,t,r,i,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let f={type:"scalar",offset:ly.emptyScalarPosition(t,r,i),indent:-1,source:""},d=Bd.composeScalar(e,f,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 dy({options:e},{offset:t,source:r,end:i},n){let a=new ay.Alias(r.substring(1));a.source===""&&n(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(t+r.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+r.length,s=cy.resolveEnd(i,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}js.composeEmptyNode=Ts;js.composeNode=Ld});var qd=b(Fd=>{"use strict";var fy=ii(),Md=Vd(),hy=dr(),py=si();function my(e,t,{offset:r,start:i,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new fy.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=py.resolveProps(i,{indicator:"doc-start",next:n??a?.[0],offset:r,onError:o,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!f.hasNewline&&o(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?Md.composeNode(l,n,f,o):Md.composeEmptyNode(l,f.end,i,null,f,o);let d=c.contents.range[2],u=hy.resolveEnd(a,d,!1,o);return u.comment&&(c.comment=u.comment),c.range=[r,d,u.offset],c}Fd.composeDoc=my});var Os=b(Jd=>{"use strict";var vy=tn("process"),gy=No(),wy=ii(),ci=oi(),Wd=R(),yy=qd(),Ny=dr();function li(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:r}=e;return[t,t+(typeof r=="string"?r.length:1)]}function zd(e){let t="",r=!1,i=!1;for(let n=0;n<e.length;++n){let a=e[n];switch(a[0]){case"#":t+=(t===""?"":i?`
101
+ `),t+=1,i=e[t+1];return r||(r=" "),{fold:r,offset:t}}var Sy={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
102
+ `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Ey(e,t,r,i){let n=e.substr(t,r),o=n.length===r&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,r+2);return i(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}Jd.resolveFlowScalar=wy});var Kd=k(Ud=>{"use strict";var Gt=A(),Gd=J(),xy=Vs(),Cy=Fs();function Py(e,t,r,i){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?xy.resolveBlockScalar(e,t,i):Cy.resolveFlowScalar(t,e.options.strict,i),c=r?e.directives.tagName(r.source,u=>i(r,"TAG_RESOLVE_FAILED",u)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[Gt.SCALAR]:c?l=Ry(e.schema,n,c,r,i):t.type==="scalar"?l=Ay(e,n,t,i):l=e.schema[Gt.SCALAR];let f;try{let u=l.resolve(n,d=>i(r??t,"TAG_RESOLVE_FAILED",d),e.options);f=Gt.isScalar(u)?u:new Gd.Scalar(u)}catch(u){let d=u instanceof Error?u.message:String(u);i(r??t,"TAG_RESOLVE_FAILED",d),f=new Gd.Scalar(n)}return f.range=s,f.source=n,a&&(f.type=a),c&&(f.tag=c),l.format&&(f.format=l.format),o&&(f.comment=o),f}function Ry(e,t,r,i,n){if(r==="!")return e[Gt.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===r)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[r];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${r}`,r!=="tag:yaml.org,2002:str"),e[Gt.SCALAR])}function Ay({atKey:e,directives:t,schema:r},i,n,a){let o=r.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(i))||r[Gt.SCALAR];if(r.compat){let s=r.compat.find(c=>c.default&&c.test?.test(i))??r[Gt.SCALAR];if(o.tag!==s.tag){let c=t.tagString(o.tag),l=t.tagString(s.tag),f=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",f,!0)}}return o}Ud.composeScalar=Py});var Xd=k(Yd=>{"use strict";function _y(e,t,r){if(t){r??(r=t.length);for(let i=r-1;i>=0;--i){let n=t[i];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}for(n=t[++i];n?.type==="space";)e+=n.source.length,n=t[++i];break}}return e}Yd.emptyScalarPosition=_y});var ef=k(Ws=>{"use strict";var Iy=Kr(),Ty=A(),jy=qd(),Qd=Kd(),$y=wr(),Oy=Xd(),Hy={composeNode:Zd,composeEmptyNode:qs};function Zd(e,t,r,i){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=r,l,f=!0;switch(t.type){case"alias":l=Dy(e,t,i),(s||c)&&i(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=Qd.composeScalar(e,t,c,i),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=jy.composeCollection(Hy,e,t,r,i),s&&(l.anchor=s.source.substring(1))}catch(u){let d=u instanceof Error?u.message:String(u);i(t,"RESOURCE_EXHAUSTION",d)}break;default:{let u=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;i(t,"UNEXPECTED_TOKEN",u),f=!1}}return l??(l=qs(e,t.offset,void 0,null,r,i)),s&&l.anchor===""&&i(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&e.options.stringKeys&&(!Ty.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&i(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&&f&&(l.srcToken=t),l}function qs(e,t,r,i,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let f={type:"scalar",offset:Oy.emptyScalarPosition(t,r,i),indent:-1,source:""},u=Qd.composeScalar(e,f,s,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(u.spaceBefore=!0),a&&(u.comment=a,u.range[2]=c),u}function Dy({options:e},{offset:t,source:r,end:i},n){let a=new Iy.Alias(r.substring(1));a.source===""&&n(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(t+r.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+r.length,s=$y.resolveEnd(i,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}Ws.composeEmptyNode=qs;Ws.composeNode=Zd});var nf=k(rf=>{"use strict";var By=di(),tf=ef(),Ly=wr(),Vy=mi();function My(e,t,{offset:r,start:i,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new By.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=Vy.resolveProps(i,{indicator:"doc-start",next:n??a?.[0],offset:r,onError:o,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!f.hasNewline&&o(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?tf.composeNode(l,n,f,o):tf.composeEmptyNode(l,f.end,i,null,f,o);let u=c.contents.range[2],d=Ly.resolveEnd(a,u,!1,o);return d.comment&&(c.comment=d.comment),c.range=[r,u,d.offset],c}rf.composeDoc=My});var Js=k(sf=>{"use strict";var Fy=dn("process"),qy=Io(),Wy=di(),vi=hi(),af=A(),zy=nf(),Jy=wr();function gi(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:r}=e;return[t,t+(typeof r=="string"?r.length:1)]}function of(e){let t="",r=!1,i=!1;for(let n=0;n<e.length;++n){let a=e[n];switch(a[0]){case"#":t+=(t===""?"":i?`
103
103
 
104
104
  `:`
105
- `)+(a.substring(1)||" "),r=!0,i=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),r=!1;break;default:r||(i=!0),r=!1}}return{comment:t,afterEmptyLine:i}}var $s=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,i,n,a)=>{let o=li(r);a?this.warnings.push(new ci.YAMLWarning(o,i,n)):this.errors.push(new ci.YAMLParseError(o,i,n))},this.directives=new gy.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,r){let{comment:i,afterEmptyLine:n}=zd(this.prelude);if(i){let a=t.contents;if(r)t.comment=t.comment?`${t.comment}
106
- ${i}`:i;else if(n||t.directives.docStart||!a)t.commentBefore=i;else if(Wd.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];Wd.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${i}
105
+ `)+(a.substring(1)||" "),r=!0,i=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),r=!1;break;default:r||(i=!0),r=!1}}return{comment:t,afterEmptyLine:i}}var zs=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,i,n,a)=>{let o=gi(r);a?this.warnings.push(new vi.YAMLWarning(o,i,n)):this.errors.push(new vi.YAMLParseError(o,i,n))},this.directives=new qy.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,r){let{comment:i,afterEmptyLine:n}=of(this.prelude);if(i){let a=t.contents;if(r)t.comment=t.comment?`${t.comment}
106
+ ${i}`:i;else if(n||t.directives.docStart||!a)t.commentBefore=i;else if(af.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];af.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${i}
107
107
  ${s}`:i}else{let o=a.commentBefore;a.commentBefore=o?`${i}
108
- ${o}`:i}}if(r){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:zd(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,r=!1,i=-1){for(let n of t)yield*this.next(n);yield*this.end(r,i)}*next(t){switch(vy.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(r,i,n)=>{let a=li(t);a[0]+=r,this.onError(a,"BAD_DIRECTIVE",i,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let r=yy.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!r.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(r,!1),this.doc&&(yield this.doc),this.doc=r,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let r=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,i=new ci.YAMLParseError(li(t),"UNEXPECTED_TOKEN",r);this.atDirectives||!this.doc?this.errors.push(i):this.doc.errors.push(i);break}case"doc-end":{if(!this.doc){let i="Unexpected doc-end without preceding document";this.errors.push(new ci.YAMLParseError(li(t),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let r=Ny.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),r.comment){let i=this.doc.comment;this.doc.comment=i?`${i}
109
- ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new ci.YAMLParseError(li(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,r=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let i=Object.assign({_directives:this.directives},this.options),n=new wy.Document(void 0,i);this.atDirectives&&this.onError(r,"MISSING_CHAR","Missing directives-end indicator line"),n.range=[0,r,r],this.decorate(n,!1),yield n}}};Jd.Composer=$s});var Kd=b(Gn=>{"use strict";var by=As(),ky=Is(),Sy=oi(),Gd=Jr();function Ey(e,t=!0,r){if(e){let i=(n,a,o)=>{let s=typeof n=="number"?n:Array.isArray(n)?n[0]:n.offset;if(r)r(s,a,o);else throw new Sy.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return ky.resolveFlowScalar(e,t,i);case"block-scalar":return by.resolveBlockScalar({options:{strict:t}},e,i)}}return null}function xy(e,t){let{implicitKey:r=!1,indent:i,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=Gd.stringifyString({type:o,value:e},{implicitKey:r,indent:i>0?" ".repeat(i):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:i,source:`
108
+ ${o}`:i}}if(r){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:of(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,r=!1,i=-1){for(let n of t)yield*this.next(n);yield*this.end(r,i)}*next(t){switch(Fy.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(r,i,n)=>{let a=gi(t);a[0]+=r,this.onError(a,"BAD_DIRECTIVE",i,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let r=zy.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!r.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(r,!1),this.doc&&(yield this.doc),this.doc=r,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let r=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,i=new vi.YAMLParseError(gi(t),"UNEXPECTED_TOKEN",r);this.atDirectives||!this.doc?this.errors.push(i):this.doc.errors.push(i);break}case"doc-end":{if(!this.doc){let i="Unexpected doc-end without preceding document";this.errors.push(new vi.YAMLParseError(gi(t),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let r=Jy.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),r.comment){let i=this.doc.comment;this.doc.comment=i?`${i}
109
+ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new vi.YAMLParseError(gi(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,r=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let i=Object.assign({_directives:this.directives},this.options),n=new Wy.Document(void 0,i);this.atDirectives&&this.onError(r,"MISSING_CHAR","Missing directives-end indicator line"),n.range=[0,r,r],this.decorate(n,!1),yield n}}};sf.Composer=zs});var uf=k(ra=>{"use strict";var Gy=Vs(),Uy=Fs(),Ky=hi(),cf=ei();function Yy(e,t=!0,r){if(e){let i=(n,a,o)=>{let s=typeof n=="number"?n:Array.isArray(n)?n[0]:n.offset;if(r)r(s,a,o);else throw new Ky.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Uy.resolveFlowScalar(e,t,i);case"block-scalar":return Gy.resolveBlockScalar({options:{strict:t}},e,i)}}return null}function Xy(e,t){let{implicitKey:r=!1,indent:i,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=cf.stringifyString({type:o,value:e},{implicitKey:r,indent:i>0?" ".repeat(i):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:i,source:`
110
110
  `}];switch(s[0]){case"|":case">":{let l=s.indexOf(`
111
- `),f=s.substring(0,l),d=s.substring(l+1)+`
112
- `,u=[{type:"block-scalar-header",offset:a,indent:i,source:f}];return Ud(u,c)||u.push({type:"newline",offset:-1,indent:i,source:`
113
- `}),{type:"block-scalar",offset:a,indent:i,props:u,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:i,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:i,source:s,end:c};default:return{type:"scalar",offset:a,indent:i,source:s,end:c}}}function Py(e,t,r={}){let{afterKey:i=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=r,s="indent"in e?e.indent:null;if(i&&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=Gd.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">":Cy(e,c);break;case'"':Hs(e,c,"double-quoted-scalar");break;case"'":Hs(e,c,"single-quoted-scalar");break;default:Hs(e,c,"scalar")}}function Cy(e,t){let r=t.indexOf(`
111
+ `),f=s.substring(0,l),u=s.substring(l+1)+`
112
+ `,d=[{type:"block-scalar-header",offset:a,indent:i,source:f}];return lf(d,c)||d.push({type:"newline",offset:-1,indent:i,source:`
113
+ `}),{type:"block-scalar",offset:a,indent:i,props:d,source:u}}case'"':return{type:"double-quoted-scalar",offset:a,indent:i,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:i,source:s,end:c};default:return{type:"scalar",offset:a,indent:i,source:s,end:c}}}function Qy(e,t,r={}){let{afterKey:i=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=r,s="indent"in e?e.indent:null;if(i&&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=cf.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">":Zy(e,c);break;case'"':Gs(e,c,"double-quoted-scalar");break;case"'":Gs(e,c,"single-quoted-scalar");break;default:Gs(e,c,"scalar")}}function Zy(e,t){let r=t.indexOf(`
114
114
  `),i=t.substring(0,r),n=t.substring(r+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=i,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:i}];Ud(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 Ud(e,t){if(t)for(let r of t)switch(r.type){case"space":case"comment":e.push(r);break;case"newline":return e.push(r),!0}return!1}function Hs(e,t,r){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=r,e.source=t;break;case"block-scalar":{let i=e.props.slice(1),n=t.length;e.props[0].type==="block-scalar-header"&&(n-=e.props[0].source.length);for(let a of i)a.offset+=n;delete e.props,Object.assign(e,{type:r,source:t,end:i});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:r,source:t,end:[n]});break}default:{let i="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:r,indent:i,source:t,end:n})}}}Gn.createScalarToken=xy;Gn.resolveAsScalar=Ey;Gn.setScalarValue=Py});var Xd=b(Yd=>{"use strict";var Ry=e=>"type"in e?Kn(e):Un(e);function Kn(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=Kn(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=Un(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=Un(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=Un(e);if(e.end)for(let r of e.end)t+=r.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let r of e.end)t+=r.source;return t}}}function Un({start:e,key:t,sep:r,value:i}){let n="";for(let a of e)n+=a.source;if(t&&(n+=Kn(t)),r)for(let a of r)n+=a.source;return i&&(n+=Kn(i)),n}Yd.stringify=Ry});var tf=b(ef=>{"use strict";var Ds=Symbol("break visit"),Ay=Symbol("skip children"),Qd=Symbol("remove item");function qt(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Zd(Object.freeze([]),e,t)}qt.BREAK=Ds;qt.SKIP=Ay;qt.REMOVE=Qd;qt.itemAtPath=(e,t)=>{let r=e;for(let[i,n]of t){let a=r?.[i];if(a&&"items"in a)r=a.items[n];else return}return r};qt.parentCollection=(e,t)=>{let r=qt.itemAtPath(e,t.slice(0,-1)),i=t[t.length-1][0],n=r?.[i];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function Zd(e,t,r){let i=r(t,e);if(typeof i=="symbol")return i;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=Zd(Object.freeze(e.concat([[n,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===Ds)return Ds;s===Qd&&(a.items.splice(o,1),o-=1)}}typeof i=="function"&&n==="key"&&(i=i(t,e))}}return typeof i=="function"?i(t,e):i}ef.visit=qt});var Yn=b(he=>{"use strict";var Bs=Kd(),_y=Xd(),Iy=tf(),Ls="\uFEFF",Vs="",Ms="",Fs="",Ty=e=>!!e&&"items"in e,jy=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function $y(e){switch(e){case Ls:return"<BOM>";case Vs:return"<DOC>";case Ms:return"<FLOW_END>";case Fs:return"<SCALAR>";default:return JSON.stringify(e)}}function Oy(e){switch(e){case Ls:return"byte-order-mark";case Vs:return"doc-mode";case Ms:return"flow-error-end";case Fs: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=i,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:i}];lf(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 lf(e,t){if(t)for(let r of t)switch(r.type){case"space":case"comment":e.push(r);break;case"newline":return e.push(r),!0}return!1}function Gs(e,t,r){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=r,e.source=t;break;case"block-scalar":{let i=e.props.slice(1),n=t.length;e.props[0].type==="block-scalar-header"&&(n-=e.props[0].source.length);for(let a of i)a.offset+=n;delete e.props,Object.assign(e,{type:r,source:t,end:i});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:r,source:t,end:[n]});break}default:{let i="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:r,indent:i,source:t,end:n})}}}ra.createScalarToken=Xy;ra.resolveAsScalar=Yy;ra.setScalarValue=Qy});var ff=k(df=>{"use strict";var eN=e=>"type"in e?na(e):ia(e);function na(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=na(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=ia(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=ia(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=ia(e);if(e.end)for(let r of e.end)t+=r.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let r of e.end)t+=r.source;return t}}}function ia({start:e,key:t,sep:r,value:i}){let n="";for(let a of e)n+=a.source;if(t&&(n+=na(t)),r)for(let a of r)n+=a.source;return i&&(n+=na(i)),n}df.stringify=eN});var vf=k(mf=>{"use strict";var Us=Symbol("break visit"),tN=Symbol("skip children"),pf=Symbol("remove item");function Ut(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),hf(Object.freeze([]),e,t)}Ut.BREAK=Us;Ut.SKIP=tN;Ut.REMOVE=pf;Ut.itemAtPath=(e,t)=>{let r=e;for(let[i,n]of t){let a=r?.[i];if(a&&"items"in a)r=a.items[n];else return}return r};Ut.parentCollection=(e,t)=>{let r=Ut.itemAtPath(e,t.slice(0,-1)),i=t[t.length-1][0],n=r?.[i];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function hf(e,t,r){let i=r(t,e);if(typeof i=="symbol")return i;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=hf(Object.freeze(e.concat([[n,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===Us)return Us;s===pf&&(a.items.splice(o,1),o-=1)}}typeof i=="function"&&n==="key"&&(i=i(t,e))}}return typeof i=="function"?i(t,e):i}mf.visit=Ut});var aa=k(me=>{"use strict";var Ks=uf(),rN=ff(),iN=vf(),Ys="\uFEFF",Xs="",Qs="",Zs="",nN=e=>!!e&&"items"in e,aN=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function oN(e){switch(e){case Ys:return"<BOM>";case Xs:return"<DOC>";case Qs:return"<FLOW_END>";case Zs:return"<SCALAR>";default:return JSON.stringify(e)}}function sN(e){switch(e){case Ys:return"byte-order-mark";case Xs:return"doc-mode";case Qs:return"flow-error-end";case Zs: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}he.createScalarToken=Bs.createScalarToken;he.resolveAsScalar=Bs.resolveAsScalar;he.setScalarValue=Bs.setScalarValue;he.stringify=_y.stringify;he.visit=Iy.visit;he.BOM=Ls;he.DOCUMENT=Vs;he.FLOW_END=Ms;he.SCALAR=Fs;he.isCollection=Ty;he.isScalar=jy;he.prettyToken=$y;he.tokenType=Oy});var zs=b(nf=>{"use strict";var ui=Yn();function Ie(e){switch(e){case void 0:case" ":case`
120
- `:case"\r":case" ":return!0;default:return!1}}var rf=new Set("0123456789ABCDEFabcdef"),Hy=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Xn=new Set(",[]{}"),Dy=new Set(` ,[]{}
121
- \r `),qs=e=>!e||Dy.has(e),Ws=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,r=!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=!r;let i=this.next??"stream";for(;i&&(r||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let t=this.pos,r=this.buffer[t];for(;r===" "||r===" ";)r=this.buffer[++t];return!r||r==="#"||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}me.createScalarToken=Ks.createScalarToken;me.resolveAsScalar=Ks.resolveAsScalar;me.setScalarValue=Ks.setScalarValue;me.stringify=rN.stringify;me.visit=iN.visit;me.BOM=Ys;me.DOCUMENT=Xs;me.FLOW_END=Qs;me.SCALAR=Zs;me.isCollection=nN;me.isScalar=aN;me.prettyToken=oN;me.tokenType=sN});var rc=k(wf=>{"use strict";var wi=aa();function Oe(e){switch(e){case void 0:case" ":case`
120
+ `:case"\r":case" ":return!0;default:return!1}}var gf=new Set("0123456789ABCDEFabcdef"),cN=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),oa=new Set(",[]{}"),lN=new Set(` ,[]{}
121
+ \r `),ec=e=>!e||lN.has(e),tc=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,r=!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=!r;let i=this.next??"stream";for(;i&&(r||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let t=this.pos,r=this.buffer[t];for(;r===" "||r===" ";)r=this.buffer[++t];return!r||r==="#"||r===`
122
122
  `?!0:r==="\r"?this.buffer[t+1]===`
123
123
  `:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let r=this.buffer[t];if(this.indentNext>0){let i=0;for(;r===" ";)r=this.buffer[++i+t];if(r==="\r"){let n=this.buffer[i+t+1];if(n===`
124
124
  `||!n&&!this.atEnd)return t+i+1}return r===`
125
- `||i>=this.indentNext||!r&&!this.atEnd?t+i:-1}if(r==="-"||r==="."){let i=this.buffer.substr(t,3);if((i==="---"||i==="...")&&Ie(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]===ui.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let r=t.length,i=t.indexOf("#");for(;i!==-1;){let a=t[i-1];if(a===" "||a===" "){r=i-1;break}else i=t.indexOf("#",i+1)}for(;;){let a=t[r-1];if(a===" "||a===" ")r-=1;else break}let n=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let r=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-r),yield*this.pushNewline(),"stream"}return yield ui.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 r=this.peek(3);if((r==="---"||r==="...")&&Ie(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,r==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Ie(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,r]=this.peek(2);if(!r&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&Ie(r)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let r=yield*this.pushIndicators();switch(t[r]){case"#":yield*this.pushCount(t.length-r);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(qs),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return r+=yield*this.parseBlockScalarHeader(),r+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-r),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,r,i=-1;do t=yield*this.pushNewline(),t>0?(r=yield*this.pushSpaces(!1),this.indentValue=i=r):r=0,r+=yield*this.pushSpaces(!0);while(t+r>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((i!==-1&&i<this.indentNext&&n[0]!=="#"||i===0&&(n.startsWith("---")||n.startsWith("..."))&&Ie(n[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield ui.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(qs),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Ie(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),r=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;r!==-1&&this.buffer[r+1]==="'";)r=this.buffer.indexOf("'",r+2);else for(;r!==-1;){let a=0;for(;this.buffer[r-1-a]==="\\";)a+=1;if(a%2===0)break;r=this.buffer.indexOf('"',r+1)}let i=this.buffer.substring(0,r),n=i.indexOf(`
125
+ `||i>=this.indentNext||!r&&!this.atEnd?t+i:-1}if(r==="-"||r==="."){let i=this.buffer.substr(t,3);if((i==="---"||i==="...")&&Oe(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]===wi.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let r=t.length,i=t.indexOf("#");for(;i!==-1;){let a=t[i-1];if(a===" "||a===" "){r=i-1;break}else i=t.indexOf("#",i+1)}for(;;){let a=t[r-1];if(a===" "||a===" ")r-=1;else break}let n=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let r=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-r),yield*this.pushNewline(),"stream"}return yield wi.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 r=this.peek(3);if((r==="---"||r==="...")&&Oe(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,r==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Oe(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,r]=this.peek(2);if(!r&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&Oe(r)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let r=yield*this.pushIndicators();switch(t[r]){case"#":yield*this.pushCount(t.length-r);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(ec),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return r+=yield*this.parseBlockScalarHeader(),r+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-r),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,r,i=-1;do t=yield*this.pushNewline(),t>0?(r=yield*this.pushSpaces(!1),this.indentValue=i=r):r=0,r+=yield*this.pushSpaces(!0);while(t+r>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((i!==-1&&i<this.indentNext&&n[0]!=="#"||i===0&&(n.startsWith("---")||n.startsWith("..."))&&Oe(n[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield wi.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(ec),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Oe(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),r=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;r!==-1&&this.buffer[r+1]==="'";)r=this.buffer.indexOf("'",r+2);else for(;r!==-1;){let a=0;for(;this.buffer[r-1-a]==="\\";)a+=1;if(a%2===0)break;r=this.buffer.indexOf('"',r+1)}let i=this.buffer.substring(0,r),n=i.indexOf(`
127
127
  `,this.pos);if(n!==-1){for(;n!==-1;){let a=this.continueScalar(n+1);if(a===-1)break;n=i.indexOf(`
128
- `,a)}n!==-1&&(r=n-(i[n-1]==="\r"?2:1))}if(r===-1){if(!this.atEnd)return this.setNext("quoted-scalar");r=this.buffer.length}return yield*this.pushToIndex(r+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let r=this.buffer[++t];if(r==="+")this.blockScalarKeep=!0;else if(r>"0"&&r<="9")this.blockScalarIndent=Number(r)-1;else if(r!=="-")break}return yield*this.pushUntil(r=>Ie(r)||r==="#")}*parseBlockScalar(){let t=this.pos-1,r=0,i;e:for(let a=this.pos;i=this.buffer[a];++a)switch(i){case" ":r+=1;break;case`
128
+ `,a)}n!==-1&&(r=n-(i[n-1]==="\r"?2:1))}if(r===-1){if(!this.atEnd)return this.setNext("quoted-scalar");r=this.buffer.length}return yield*this.pushToIndex(r+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let r=this.buffer[++t];if(r==="+")this.blockScalarKeep=!0;else if(r>"0"&&r<="9")this.blockScalarIndent=Number(r)-1;else if(r!=="-")break}return yield*this.pushUntil(r=>Oe(r)||r==="#")}*parseBlockScalar(){let t=this.pos-1,r=0,i;e:for(let a=this.pos;i=this.buffer[a];++a)switch(i){case" ":r+=1;break;case`
129
129
  `:t=a,r=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(!i&&!this.atEnd)return this.setNext("block-scalar");if(r>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=r: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(i=this.buffer[n];i===" ";)i=this.buffer[++n];if(i===" "){for(;i===" "||i===" "||i==="\r"||i===`
132
132
  `;)i=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+r>s)t=a;else break}while(!0);return yield ui.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,r=this.pos-1,i=this.pos-1,n;for(;n=this.buffer[++i];)if(n===":"){let a=this.buffer[i+1];if(Ie(a)||t&&Xn.has(a))break;r=i}else if(Ie(n)){let a=this.buffer[i+1];if(n==="\r"&&(a===`
133
+ `&&a>=this.pos&&a+1+r>s)t=a;else break}while(!0);return yield wi.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,r=this.pos-1,i=this.pos-1,n;for(;n=this.buffer[++i];)if(n===":"){let a=this.buffer[i+1];if(Oe(a)||t&&oa.has(a))break;r=i}else if(Oe(n)){let a=this.buffer[i+1];if(n==="\r"&&(a===`
134
134
  `?(i+=1,n=`
135
- `,a=this.buffer[i+1]):r=i),a==="#"||t&&Xn.has(a))break;if(n===`
136
- `){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&Xn.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield ui.SCALAR,yield*this.pushToIndex(r+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,r){let i=this.buffer.slice(this.pos,t);return i?(yield i,this.pos+=i.length,i.length):(r&&(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(qs),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(Ie(i)||r&&Xn.has(i)){r?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,r=this.buffer[t];for(;!Ie(r)&&r!==">";)r=this.buffer[++t];return yield*this.pushToIndex(r===">"?t+1:t,!1)}else{let t=this.pos+1,r=this.buffer[t];for(;r;)if(Hy.has(r))r=this.buffer[++t];else if(r==="%"&&rf.has(this.buffer[t+1])&&rf.has(this.buffer[t+2]))r=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[i+1]):r=i),a==="#"||t&&oa.has(a))break;if(n===`
136
+ `){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&oa.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield wi.SCALAR,yield*this.pushToIndex(r+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,r){let i=this.buffer.slice(this.pos,t);return i?(yield i,this.pos+=i.length,i.length):(r&&(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(ec),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(Oe(i)||r&&oa.has(i)){r?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,r=this.buffer[t];for(;!Oe(r)&&r!==">";)r=this.buffer[++t];return yield*this.pushToIndex(r===">"?t+1:t,!1)}else{let t=this.pos+1,r=this.buffer[t];for(;r;)if(cN.has(r))r=this.buffer[++t];else if(r==="%"&&gf.has(this.buffer[t+1])&&gf.has(this.buffer[t+2]))r=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 r=this.pos-1,i;do i=this.buffer[++r];while(i===" "||t&&i===" ");let n=r-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=r),n}*pushUntil(t){let r=this.pos,i=this.buffer[r];for(;!t(i);)i=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};nf.Lexer=Ws});var Gs=b(af=>{"use strict";var Js=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let r=0,i=this.lineStarts.length;for(;r<i;){let a=r+i>>1;this.lineStarts[a]<t?r=a+1:i=a}if(this.lineStarts[r]===t)return{line:r+1,col:1};if(r===0)return{line:0,col:t};let n=this.lineStarts[r-1];return{line:r,col:t-n+1}}}};af.LineCounter=Js});var Ks=b(uf=>{"use strict";var By=tn("process"),of=Yn(),Ly=zs();function St(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function sf(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 lf(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 Qn(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 fr(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 Zn(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let r=0;r<t.length;++r)e.push(t[r])}function cf(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!St(t.start,"explicit-key-ind")&&!St(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,lf(t.value)?t.value.end?Zn(t.value.end,t.sep):t.value.end=t.sep:Zn(t.start,t.sep),delete t.sep)}var Us=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 Ly.Lexer,this.onNewLine=t}*parse(t,r=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let i of this.lexer.lex(t,r))yield*this.next(i);r||(yield*this.end())}*next(t){if(this.source=t,By.env.LOG_TOKENS&&console.log("|",of.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=of.tokenType(t);if(r)if(r==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=r,yield*this.step(),r){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 i=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:i,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 r=t??this.stack.pop();if(!r)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield r;else{let i=this.peek(1);switch(r.type==="block-scalar"?r.indent="indent"in i?i.indent:0:r.type==="flow-collection"&&i.type==="document"&&(r.indent=0),r.type==="flow-collection"&&cf(r),i.type){case"document":i.value=r;break;case"block-scalar":i.props.push(r);break;case"block-map":{let n=i.items[i.items.length-1];if(n.value){i.items.push({start:[],key:r,sep:[]}),this.onKeyLine=!0;return}else if(n.sep)n.value=r;else{Object.assign(n,{key:r,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case"block-seq":{let n=i.items[i.items.length-1];n.value?i.items.push({start:[],value:r}):n.value=r;break}case"flow-collection":{let n=i.items[i.items.length-1];!n||n.value?i.items.push({start:[],key:r,sep:[]}):n.sep?n.value=r:Object.assign(n,{key:r,sep:[]});return}default:yield*this.pop(),yield*this.pop(r)}if((i.type==="document"||i.type==="block-map"||i.type==="block-seq")&&(r.type==="block-map"||r.type==="block-seq")){let n=r.items[r.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&sf(n.start)===-1&&(r.indent===0||n.start.every(a=>a.type!=="comment"||a.indent<r.indent))&&(i.type==="document"?i.end=n.start:i.items.push({start:n.start}),r.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":{sf(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 r=this.startBlockValue(t);r?this.stack.push(r):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 r=Qn(this.peek(2)),i=fr(r),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:i,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 r=this.source.indexOf(`
138
+ `?yield*this.pushCount(2):0}*pushSpaces(t){let r=this.pos-1,i;do i=this.buffer[++r];while(i===" "||t&&i===" ");let n=r-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=r),n}*pushUntil(t){let r=this.pos,i=this.buffer[r];for(;!t(i);)i=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};wf.Lexer=tc});var nc=k(yf=>{"use strict";var ic=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let r=0,i=this.lineStarts.length;for(;r<i;){let a=r+i>>1;this.lineStarts[a]<t?r=a+1:i=a}if(this.lineStarts[r]===t)return{line:r+1,col:1};if(r===0)return{line:0,col:t};let n=this.lineStarts[r-1];return{line:r,col:t-n+1}}}};yf.LineCounter=ic});var oc=k(Ef=>{"use strict";var uN=dn("process"),Nf=aa(),dN=rc();function Rt(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function bf(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 Sf(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function sa(e){switch(e.type){case"document":return e.start;case"block-map":{let t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function yr(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 ca(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let r=0;r<t.length;++r)e.push(t[r])}function kf(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Rt(t.start,"explicit-key-ind")&&!Rt(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Sf(t.value)?t.value.end?ca(t.value.end,t.sep):t.value.end=t.sep:ca(t.start,t.sep),delete t.sep)}var ac=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 dN.Lexer,this.onNewLine=t}*parse(t,r=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let i of this.lexer.lex(t,r))yield*this.next(i);r||(yield*this.end())}*next(t){if(this.source=t,uN.env.LOG_TOKENS&&console.log("|",Nf.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=Nf.tokenType(t);if(r)if(r==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=r,yield*this.step(),r){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 i=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:i,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 r=t??this.stack.pop();if(!r)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield r;else{let i=this.peek(1);switch(r.type==="block-scalar"?r.indent="indent"in i?i.indent:0:r.type==="flow-collection"&&i.type==="document"&&(r.indent=0),r.type==="flow-collection"&&kf(r),i.type){case"document":i.value=r;break;case"block-scalar":i.props.push(r);break;case"block-map":{let n=i.items[i.items.length-1];if(n.value){i.items.push({start:[],key:r,sep:[]}),this.onKeyLine=!0;return}else if(n.sep)n.value=r;else{Object.assign(n,{key:r,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case"block-seq":{let n=i.items[i.items.length-1];n.value?i.items.push({start:[],value:r}):n.value=r;break}case"flow-collection":{let n=i.items[i.items.length-1];!n||n.value?i.items.push({start:[],key:r,sep:[]}):n.sep?n.value=r:Object.assign(n,{key:r,sep:[]});return}default:yield*this.pop(),yield*this.pop(r)}if((i.type==="document"||i.type==="block-map"||i.type==="block-seq")&&(r.type==="block-map"||r.type==="block-seq")){let n=r.items[r.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&bf(n.start)===-1&&(r.indent===0||n.start.every(a=>a.type!=="comment"||a.indent<r.indent))&&(i.type==="document"?i.end=n.start:i.items.push({start:n.start}),r.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":{bf(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 r=this.startBlockValue(t);r?this.stack.push(r):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 r=sa(this.peek(2)),i=yr(r),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:i,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 r=this.source.indexOf(`
139
139
  `)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
140
- `,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else if(r.sep)r.sep.push(this.sourceToken);else{if(this.atIndentedComment(r.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){Zn(n,r.start),n.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let i=!this.onKeyLine&&this.indent===t.indent,n=i&&(r.sep||r.explicitKey)&&this.type!=="seq-item-ind",a=[];if(n&&r.sep&&!r.value){let o=[];for(let s=0;s<r.sep.length;++s){let c=r.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=r.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":n||r.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"explicit-key-ind":!r.sep&&!r.explicitKey?(r.start.push(this.sourceToken),r.explicitKey=!0):n||r.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(r.explicitKey)if(r.sep)if(r.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(St(r.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(lf(r.key)&&!St(r.sep,"newline")){let o=fr(r.start),s=r.key,c=r.sep;c.push(this.sourceToken),delete r.key,delete r.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?r.sep=r.sep.concat(a,this.sourceToken):r.sep.push(this.sourceToken);else if(St(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=fr(r.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else r.sep?r.value||n?t.items.push({start:a,key:null,sep:[this.sourceToken]}):St(r.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):r.sep.push(this.sourceToken):Object.assign(r,{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||r.value?(t.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):r.sep?this.stack.push(o):(Object.assign(r,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!r.explicitKey&&r.sep&&!St(r.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 i&&t.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(r.value){let i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(r.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){Zn(n,r.start),n.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return;case"anchor":case"tag":if(r.value||this.indent<=t.indent)break;r.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;r.value||St(r.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return}if(this.indent>t.indent){let i=this.startBlockValue(t);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let r=t.items[t.items.length-1];if(this.type==="flow-error-end"){let i;do yield*this.pop(),i=this.peek(1);while(i?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!r||r.sep?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return;case"map-value-ind":!r||r.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!r||r.value?t.items.push({start:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let n=this.flowScalar(this.type);!r||r.value?t.items.push({start:[],key:n,sep:[]}):r.sep?this.stack.push(n):Object.assign(r,{key:n,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let i=this.startBlockValue(t);i?this.stack.push(i):(yield*this.pop(),yield*this.step())}else{let i=this.peek(2);if(i.type==="block-map"&&(this.type==="map-value-ind"&&i.indent===t.indent||this.type==="newline"&&!i.items[i.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&i.type!=="flow-collection"){let n=Qn(i),a=fr(n);cf(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 r=this.source.indexOf(`
140
+ `,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else if(r.sep)r.sep.push(this.sourceToken);else{if(this.atIndentedComment(r.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){ca(n,r.start),n.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let i=!this.onKeyLine&&this.indent===t.indent,n=i&&(r.sep||r.explicitKey)&&this.type!=="seq-item-ind",a=[];if(n&&r.sep&&!r.value){let o=[];for(let s=0;s<r.sep.length;++s){let c=r.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=r.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":n||r.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"explicit-key-ind":!r.sep&&!r.explicitKey?(r.start.push(this.sourceToken),r.explicitKey=!0):n||r.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(r.explicitKey)if(r.sep)if(r.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Rt(r.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(Sf(r.key)&&!Rt(r.sep,"newline")){let o=yr(r.start),s=r.key,c=r.sep;c.push(this.sourceToken),delete r.key,delete r.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?r.sep=r.sep.concat(a,this.sourceToken):r.sep.push(this.sourceToken);else if(Rt(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=yr(r.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else r.sep?r.value||n?t.items.push({start:a,key:null,sep:[this.sourceToken]}):Rt(r.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):r.sep.push(this.sourceToken):Object.assign(r,{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||r.value?(t.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):r.sep?this.stack.push(o):(Object.assign(r,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!r.explicitKey&&r.sep&&!Rt(r.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 i&&t.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(r.value){let i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(r.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){ca(n,r.start),n.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return;case"anchor":case"tag":if(r.value||this.indent<=t.indent)break;r.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;r.value||Rt(r.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return}if(this.indent>t.indent){let i=this.startBlockValue(t);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let r=t.items[t.items.length-1];if(this.type==="flow-error-end"){let i;do yield*this.pop(),i=this.peek(1);while(i?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!r||r.sep?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return;case"map-value-ind":!r||r.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!r||r.value?t.items.push({start:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let n=this.flowScalar(this.type);!r||r.value?t.items.push({start:[],key:n,sep:[]}):r.sep?this.stack.push(n):Object.assign(r,{key:n,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let i=this.startBlockValue(t);i?this.stack.push(i):(yield*this.pop(),yield*this.step())}else{let i=this.peek(2);if(i.type==="block-map"&&(this.type==="map-value-ind"&&i.indent===t.indent||this.type==="newline"&&!i.items[i.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&i.type!=="flow-collection"){let n=sa(i),a=yr(n);kf(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 r=this.source.indexOf(`
141
141
  `)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
142
- `,r)+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 r=Qn(t),i=fr(r);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let r=Qn(t),i=fr(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,r){return this.type!=="comment"||this.indent<=r?!1:t.every(i=>i.type==="newline"||i.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())}}};uf.Parser=Us});var mf=b(fi=>{"use strict";var df=Os(),Vy=ii(),di=oi(),My=jo(),Fy=R(),qy=Gs(),ff=Ks();function hf(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new qy.LineCounter||null,prettyErrors:t}}function Wy(e,t={}){let{lineCounter:r,prettyErrors:i}=hf(t),n=new ff.Parser(r?.addNewLine),a=new df.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach(di.prettifyError(e,r)),s.warnings.forEach(di.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function pf(e,t={}){let{lineCounter:r,prettyErrors:i}=hf(t),n=new ff.Parser(r?.addNewLine),a=new df.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 di.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(di.prettifyError(e,r)),o.warnings.forEach(di.prettifyError(e,r))),o}function zy(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=pf(e,r);if(!n)return null;if(n.warnings.forEach(a=>My.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:i},r))}function Jy(e,t,r){let i=null;if(typeof t=="function"||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r=="string"&&(r=r.length),typeof r=="number"){let n=Math.round(r);r=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=r??t??{};if(!n)return}return Fy.isDocument(e)&&!i?e.toString(r):new Vy.Document(e,i,r).toString(r)}fi.parse=zy;fi.parseAllDocuments=Wy;fi.parseDocument=pf;fi.stringify=Jy});var hr=b(I=>{"use strict";var Gy=Os(),Uy=ii(),Ky=ms(),Ys=oi(),Yy=Mr(),Et=R(),Xy=yt(),Qy=W(),Zy=bt(),eN=kt(),tN=Yn(),rN=zs(),iN=Gs(),nN=Ks(),ea=mf(),vf=Dr();I.Composer=Gy.Composer;I.Document=Uy.Document;I.Schema=Ky.Schema;I.YAMLError=Ys.YAMLError;I.YAMLParseError=Ys.YAMLParseError;I.YAMLWarning=Ys.YAMLWarning;I.Alias=Yy.Alias;I.isAlias=Et.isAlias;I.isCollection=Et.isCollection;I.isDocument=Et.isDocument;I.isMap=Et.isMap;I.isNode=Et.isNode;I.isPair=Et.isPair;I.isScalar=Et.isScalar;I.isSeq=Et.isSeq;I.Pair=Xy.Pair;I.Scalar=Qy.Scalar;I.YAMLMap=Zy.YAMLMap;I.YAMLSeq=eN.YAMLSeq;I.CST=tN;I.Lexer=rN.Lexer;I.LineCounter=iN.LineCounter;I.Parser=nN.Parser;I.parse=ea.parse;I.parseAllDocuments=ea.parseAllDocuments;I.parseDocument=ea.parseDocument;I.stringify=ea.stringify;I.visit=vf.visit;I.visitAsync=vf.visitAsync});var Qc=Hr(hr(),1);import{promises as tp}from"node:fs";import Ae from"node:path";import{execFileSync as aN}from"child_process";import hi from"path";function xt(e,t){return aN("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function oN(e,t){let r=hi.normalize(e),i=hi.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function F(e){try{let t=hi.resolve(xt(e,["rev-parse","--show-toplevel"])),i=xt(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?hi.resolve(i.slice(9)):t,a=null;try{a=xt(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!oN(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function ta(e){try{xt(e,["rev-parse","--is-inside-work-tree"]);let t=xt(e,["worktree","list","--porcelain"]).split(/\r?\n/u),r=[],i=null;for(let n of t)n.startsWith("worktree ")?(i&&r.push(i),i={root:hi.resolve(n.slice(9)),branch:null,detached:!1}):i&&n.startsWith("branch refs/heads/")?i.branch=n.slice(18):i&&n==="detached"&&(i.detached=!0);return i&&r.push(i),r}catch{return[]}}function Wt(e){return ta(e).map(t=>t.root)}function pr(e,t){try{return xt(e,["check-ref-format","--branch",t]),xt(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function mr(e,t){try{let r=xt(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}import{execFileSync as sN}from"node:child_process";var cN=3e4,lN=8*1024*1024,Xs=class extends Error{constructor(r,i,n){super(`git ${i.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=r;this.args=i;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr};function uN(e,t){try{return sN("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:cN,maxBuffer:lN,windowsHide:!0})}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new Xs(e,t,i)}}function A(e,t){return uN(e,t).trim()}function at(e){return A(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function Qs(e,t){A(e,["check-ref-format","--branch",t])}import{createHash as pN}from"node:crypto";import{promises as Te}from"node:fs";import Ee from"node:path";import{TextDecoder as mN}from"node:util";var dN=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),fN=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function hN(e){return e.toLowerCase().startsWith(".env")}function pi(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>hN(i))?"environment-file":r.some(i=>fN.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>dN.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}function Pt(e){return e!==0&&e!==0n&&e!=="0"}function ze(e,t){return Pt(e.dev)&&Pt(t.dev)&&Pt(e.ino)&&Pt(t.ino)}function V(e,t){let r=Pt(e.dev)&&Pt(t.dev);if(r&&e.dev!==t.dev)return!1;let i=Pt(e.ino)&&Pt(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var ia=1024*1024;function Zs(e,t){let r=Ee.relative(e,t);return r===""||!Ee.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ee.sep}`)}function vN(e){let t=Ee.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})||Ee.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 r=e.toLowerCase(),i=pi(e);if(i||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${i??"native-runtime"}): ${e}`);return e}function gN(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function wN(e,t){return V({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ra(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return ze(r,i)?V(r,i):V(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function gf(e){let t=await Te.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Te.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function yN(e,t){let r=Ee.resolve(e),i=Ee.resolve(t);if(!Zs(r,i))throw new Error("Native artifact path is outside its root");let n=[await gf(r)],a=r;for(let o of Ee.relative(r,i).split(Ee.sep).filter(Boolean)){a=Ee.join(a,o);let s=await gf(a);if(!Zs(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function wf(e){for(let t of e){let r=await Te.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!wN(t,r)||await Te.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function J(e){let t=vN(e.ref),r=e.maxBytes===null?null:gN(e.maxBytes??ia),i=Ee.resolve(e.root,...t.split("/")),n=await yN(e.root,Ee.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await Te.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(r!==null&&a.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);let o=await Te.realpath(i);if(!Zs(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Te.open(i,"r");try{let[c,l,f]=await Promise.all([s.stat(),Te.lstat(i),Te.realpath(i)]);if(await wf(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||f!==o||!ra(a,c)||!ra(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],u=0,h=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let w=r===null?h.length:r+1-u,k=await s.read(h,0,Math.min(h.length,w),null);if(k.bytesRead===0)break;if(u+=k.bytesRead,r!==null&&u>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);d.push(Buffer.from(h.subarray(0,k.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,m,p]=await Promise.all([s.stat(),Te.lstat(i),Te.realpath(i)]);if(await wf(n),!m.isFile()||m.isSymbolicLink()||p!==o||!ra(c,v)||!ra(c,m))throw new Error(`Native artifact changed while reading: ${t}`);let y=Buffer.concat(d,u),g;try{g=new mN("utf-8",{fatal:!0}).decode(y)}catch(w){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:w})}return{ref:t,size:u,hash:e.includeHash===!1?null:pN("sha256").update(y).digest("hex"),text:g}}finally{await s.close()}}import{createHash as NN}from"crypto";function je(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function bN(e,t){t.has(e)&&je("cyclic structures are not supported"),t.add(e);try{let r=Object.keys(e);for(let i=0;i<e.length;i+=1)Object.prototype.hasOwnProperty.call(e,i)||je("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&je("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&je("symbol properties are not supported"),`[${e.map(i=>ec(i,t)).join(",")}]`}finally{t.delete(e)}}function kN(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&je("only plain objects are supported"),t.has(e)&&je("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&je("symbol properties are not supported"),t.add(e);try{let i=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=i[o];return(!s||!("value"in s))&&je("accessor properties are not supported"),`${JSON.stringify(o)}:${ec(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function ec(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)||je("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?bN(e,t):kN(e,t);case"bigint":case"function":case"symbol":case"undefined":return je(`${typeof e} values are not supported`)}return je("unsupported value type")}function tc(e){return ec(e,new Set)}function pe(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 NN("sha256").update(`${e}
143
- ${tc(t)}`).digest("hex")}import ab from"path";var vi=Hr(hr(),1);import Ct from"path";var gi=64*1024,na=1024,aa=64,yf=1024,Nf=64,ic=5,mi={learning:!0,retrieval:!0},nc={provider:"local"},SN=12e4,bf=6e5,EN=[".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/**"],xN=["**/.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"],PN=[...EN,...xN].sort((e,t)=>e.localeCompare(t,"en"));var ye={include:["**/*"],exclude:[...PN],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},vr={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it.
142
+ `,r)+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 r=sa(t),i=yr(r);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let r=sa(t),i=yr(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,r){return this.type!=="comment"||this.indent<=r?!1:t.every(i=>i.type==="newline"||i.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())}}};Ef.Parser=ac});var Af=k(Ni=>{"use strict";var xf=Js(),fN=di(),yi=hi(),pN=Wo(),hN=A(),mN=nc(),Cf=oc();function Pf(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new mN.LineCounter||null,prettyErrors:t}}function vN(e,t={}){let{lineCounter:r,prettyErrors:i}=Pf(t),n=new Cf.Parser(r?.addNewLine),a=new xf.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach(yi.prettifyError(e,r)),s.warnings.forEach(yi.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Rf(e,t={}){let{lineCounter:r,prettyErrors:i}=Pf(t),n=new Cf.Parser(r?.addNewLine),a=new xf.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 yi.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(yi.prettifyError(e,r)),o.warnings.forEach(yi.prettifyError(e,r))),o}function gN(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=Rf(e,r);if(!n)return null;if(n.warnings.forEach(a=>pN.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:i},r))}function wN(e,t,r){let i=null;if(typeof t=="function"||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r=="string"&&(r=r.length),typeof r=="number"){let n=Math.round(r);r=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=r??t??{};if(!n)return}return hN.isDocument(e)&&!i?e.toString(r):new fN.Document(e,i,r).toString(r)}Ni.parse=gN;Ni.parseAllDocuments=vN;Ni.parseDocument=Rf;Ni.stringify=wN});var Nr=k($=>{"use strict";var yN=Js(),NN=di(),bN=Cs(),sc=hi(),kN=Kr(),At=A(),SN=Et(),EN=J(),xN=Ct(),CN=Pt(),PN=aa(),RN=rc(),AN=nc(),_N=oc(),la=Af(),_f=zr();$.Composer=yN.Composer;$.Document=NN.Document;$.Schema=bN.Schema;$.YAMLError=sc.YAMLError;$.YAMLParseError=sc.YAMLParseError;$.YAMLWarning=sc.YAMLWarning;$.Alias=kN.Alias;$.isAlias=At.isAlias;$.isCollection=At.isCollection;$.isDocument=At.isDocument;$.isMap=At.isMap;$.isNode=At.isNode;$.isPair=At.isPair;$.isScalar=At.isScalar;$.isSeq=At.isSeq;$.Pair=SN.Pair;$.Scalar=EN.Scalar;$.YAMLMap=xN.YAMLMap;$.YAMLSeq=CN.YAMLSeq;$.CST=PN;$.Lexer=RN.Lexer;$.LineCounter=AN.LineCounter;$.Parser=_N.Parser;$.parse=la.parse;$.parseAllDocuments=la.parseAllDocuments;$.parseDocument=la.parseDocument;$.stringify=la.stringify;$.visit=_f.visit;$.visitAsync=_f.visitAsync});var sl=Wr(Nr(),1);import{promises as mh}from"node:fs";import Ie from"node:path";import{execFileSync as IN}from"child_process";import bi from"path";function _t(e,t){return IN("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function TN(e,t){let r=bi.normalize(e),i=bi.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function W(e){try{let t=bi.resolve(_t(e,["rev-parse","--show-toplevel"])),i=_t(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?bi.resolve(i.slice(9)):t,a=null;try{a=_t(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!TN(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function ua(e){try{_t(e,["rev-parse","--is-inside-work-tree"]);let t=_t(e,["worktree","list","--porcelain"]).split(/\r?\n/u),r=[],i=null;for(let n of t)n.startsWith("worktree ")?(i&&r.push(i),i={root:bi.resolve(n.slice(9)),branch:null,detached:!1}):i&&n.startsWith("branch refs/heads/")?i.branch=n.slice(18):i&&n==="detached"&&(i.detached=!0);return i&&r.push(i),r}catch{return[]}}function Kt(e){return ua(e).map(t=>t.root)}function br(e,t){try{return _t(e,["check-ref-format","--branch",t]),_t(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function kr(e,t){try{let r=_t(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}import{execFileSync as jN}from"node:child_process";var $N=3e4,ON=8*1024*1024,cc=class extends Error{constructor(r,i,n){super(`git ${i.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=r;this.args=i;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr};function HN(e,t){try{return jN("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:$N,maxBuffer:ON,windowsHide:!0})}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new cc(e,t,i)}}function _(e,t){return HN(e,t).trim()}function ut(e){return _(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function lc(e,t){_(e,["check-ref-format","--branch",t])}import{createHash as VN}from"node:crypto";import{promises as He}from"node:fs";import Ce from"node:path";import{TextDecoder as MN}from"node:util";var DN=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),BN=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function LN(e){return e.toLowerCase().startsWith(".env")}function ki(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>LN(i))?"environment-file":r.some(i=>BN.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>DN.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}function It(e){return e!==0&&e!==0n&&e!=="0"}function Ke(e,t){return It(e.dev)&&It(t.dev)&&It(e.ino)&&It(t.ino)}function M(e,t){let r=It(e.dev)&&It(t.dev);if(r&&e.dev!==t.dev)return!1;let i=It(e.ino)&&It(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var fa=1024*1024;function uc(e,t){let r=Ce.relative(e,t);return r===""||!Ce.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ce.sep}`)}function FN(e){let t=Ce.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})||Ce.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 r=e.toLowerCase(),i=ki(e);if(i||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${i??"native-runtime"}): ${e}`);return e}function qN(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function WN(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function da(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Ke(r,i)?M(r,i):M(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function If(e){let t=await He.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await He.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function zN(e,t){let r=Ce.resolve(e),i=Ce.resolve(t);if(!uc(r,i))throw new Error("Native artifact path is outside its root");let n=[await If(r)],a=r;for(let o of Ce.relative(r,i).split(Ce.sep).filter(Boolean)){a=Ce.join(a,o);let s=await If(a);if(!uc(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function Tf(e){for(let t of e){let r=await He.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!WN(t,r)||await He.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function Y(e){let t=FN(e.ref),r=e.maxBytes===null?null:qN(e.maxBytes??fa),i=Ce.resolve(e.root,...t.split("/")),n=await zN(e.root,Ce.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await He.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(r!==null&&a.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);let o=await He.realpath(i);if(!uc(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await He.open(i,"r");try{let[c,l,f]=await Promise.all([s.stat(),He.lstat(i),He.realpath(i)]);if(await Tf(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||f!==o||!da(a,c)||!da(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let u=[],d=0,p=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let y=r===null?p.length:r+1-d,S=await s.read(p,0,Math.min(p.length,y),null);if(S.bytesRead===0)break;if(d+=S.bytesRead,r!==null&&d>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);u.push(Buffer.from(p.subarray(0,S.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,m,h]=await Promise.all([s.stat(),He.lstat(i),He.realpath(i)]);if(await Tf(n),!m.isFile()||m.isSymbolicLink()||h!==o||!da(c,v)||!da(c,m))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(u,d),w;try{w=new MN("utf-8",{fatal:!0}).decode(g)}catch(y){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:y})}return{ref:t,size:d,hash:e.includeHash===!1?null:VN("sha256").update(g).digest("hex"),text:w}}finally{await s.close()}}import{createHash as JN}from"crypto";function De(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function GN(e,t){t.has(e)&&De("cyclic structures are not supported"),t.add(e);try{let r=Object.keys(e);for(let i=0;i<e.length;i+=1)Object.prototype.hasOwnProperty.call(e,i)||De("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&De("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&De("symbol properties are not supported"),`[${e.map(i=>dc(i,t)).join(",")}]`}finally{t.delete(e)}}function UN(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&De("only plain objects are supported"),t.has(e)&&De("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&De("symbol properties are not supported"),t.add(e);try{let i=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=i[o];return(!s||!("value"in s))&&De("accessor properties are not supported"),`${JSON.stringify(o)}:${dc(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function dc(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)||De("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?GN(e,t):UN(e,t);case"bigint":case"function":case"symbol":case"undefined":return De(`${typeof e} values are not supported`)}return De("unsupported value type")}function fc(e){return dc(e,new Set)}function ve(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 JN("sha256").update(`${e}
143
+ ${fc(t)}`).digest("hex")}import Tb from"path";var Ei=Wr(Nr(),1);import Tt from"path";var xi=64*1024,pa=1024,ha=64,jf=1024,$f=64,hc=5,Si={learning:!0,retrieval:!0},mc={provider:"local"},KN=12e4,Of=6e5,YN=[".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/**"],XN=["**/.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"],QN=[...YN,...XN].sort((e,t)=>e.localeCompare(t,"en"));var ke={include:["**/*"],exclude:[...QN],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},Sr={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it.
144
144
  # ambient_resume: true | false`,memory:"# Project policy for automatic personal-memory learning and retrieval.","memory.learning":`# Allows workflow events in this project to form new personal memories automatically.
145
145
  # learning: true | false`,"memory.retrieval":`# Allows personal memories to be injected into Agent context for this project.
146
146
  # retrieval: true | false`,knowledge:"# Project knowledge retrieval provider used by ordinary Comet tasks.","knowledge.provider":`# Provider for project knowledge.
@@ -164,28 +164,28 @@ ${tc(t)}`).digest("hex")}import ab from"path";var vi=Hr(hr(),1);import Ct from"p
164
164
  # 可选值:en | zh-CN`,"classic.context_compression":`# 新建 Classic change 是否启用 beta 上下文压缩。
165
165
  # 可选值:off | beta`,"classic.review_mode":`# 新建 Classic change 默认使用的审查深度。
166
166
  # 可选值:off | standard | thorough`,"classic.auto_transition":`# Classic 阶段通过后是否自动进入下一阶段。
167
- # 可选值:true | false`}};function Sf(e,t){return vr[t][e]}function CN(e,t,r,i){let n=/^(\s*)([a-z_]+):/u.exec(e);if(!n)return null;let a=n[1].length,o=n[2];if(a===0&&o in vr.en)return o;if(a===2&&t){let s=`${t}.${o}`;if(s in vr.en)return s}if(a===4&&t==="knowledge"&&i==="remote"){let s=`knowledge.remote.${o}`;if(s in vr.en)return s}if(a===4&&t==="knowledge"&&i==="local"){let s=`knowledge.local.${o}`;if(s in vr.en)return s}if(a===2&&t===null&&o==="hook")return"hook";if(a===2&&t==="hook"&&o==="allow_paths")return"hook.allow_paths";if(a===4&&t==="native"&&r==="snapshot"){let s=`native.snapshot.${o}`;if(s in vr.en)return s}return null}function wi(e,t){let r=[],i=null,n=null,a=null;for(let o of(0,vi.stringify)(e).trimEnd().split(`
168
- `)){let s=CN(o,i,n,a);if(s){let c=o.match(/^\s*/u)?.[0]??"";for(let l of Sf(s,t).split(`
167
+ # 可选值:true | false`}};function Df(e,t){return Sr[t][e]}function ZN(e,t,r,i){let n=/^(\s*)([a-z_]+):/u.exec(e);if(!n)return null;let a=n[1].length,o=n[2];if(a===0&&o in Sr.en)return o;if(a===2&&t){let s=`${t}.${o}`;if(s in Sr.en)return s}if(a===4&&t==="knowledge"&&i==="remote"){let s=`knowledge.remote.${o}`;if(s in Sr.en)return s}if(a===4&&t==="knowledge"&&i==="local"){let s=`knowledge.local.${o}`;if(s in Sr.en)return s}if(a===2&&t===null&&o==="hook")return"hook";if(a===2&&t==="hook"&&o==="allow_paths")return"hook.allow_paths";if(a===4&&t==="native"&&r==="snapshot"){let s=`native.snapshot.${o}`;if(s in Sr.en)return s}return null}function Ci(e,t){let r=[],i=null,n=null,a=null;for(let o of(0,Ei.stringify)(e).trimEnd().split(`
168
+ `)){let s=ZN(o,i,n,a);if(s){let c=o.match(/^\s*/u)?.[0]??"";for(let l of Df(s,t).split(`
169
169
  `))r.push(`${c}${l}`)}r.push(o),/^[a-z_]+:/u.test(o)?(o.startsWith("native:")?i="native":o.startsWith("classic:")?i="classic":o.startsWith("hook:")?i="hook":o.startsWith("memory:")?i="memory":o.startsWith("knowledge:")?i="knowledge":i=null,n=null,a=null):/^ {2}[a-z_]+:/u.test(o)&&(i==="native"&&(n=o.startsWith(" snapshot:")?"snapshot":null),i==="knowledge"&&(a=o.startsWith(" local:")?"local":o.startsWith(" remote:")?"remote":null))}return r.push(""),r.join(`
170
- `)}function RN(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||Ct.posix.isAbsolute(r)||Ct.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be a project-relative path`);if(r===".")return[];let i=r.replaceAll("\\","/").split("/");if(i.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(i.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return i}function zt(e){let t=RN(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Ef(e,t="docs"){let r=e??t;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function oa(e,t,r=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim().replaceAll("\\","/");if(i.length===0||Ct.posix.isAbsolute(i)||Ct.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be relative to its declared path base`);let n=i.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(!r&&/[*?]/u.test(i))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function ot(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function xf(e,t,r){let i=e??t;if(i!=="en"&&i!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return i}function ac(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>na)throw new Error(`${t} exceeds ${na} characters`);let r=0;for(let i=0;i<e.length;i+=1)e[i]==="?"?r+=1:e[i]==="*"&&(r+=1,e[i+1]==="*"&&(i+=1));if(r>aa)throw new Error(`${t} contains more than ${aa} wildcard tokens`);return e}function kf(e,t,r){if(e===void 0)return[...r];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(i=>ac(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function rc(e,t,r){let i=e??t;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${r} must be a positive integer`);return i}function AN(e){if(e===void 0)return{...ye,include:[...ye.include],exclude:[...ye.exclude]};let t=ot(e,"native.snapshot");return{include:kf(t.include,"native.snapshot.include",ye.include),exclude:kf(t.exclude,"native.snapshot.exclude",ye.exclude),max_files:rc(t.max_files,ye.max_files,"native.snapshot.max_files"),max_total_bytes:rc(t.max_total_bytes,ye.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:rc(t.max_duration_ms,ye.max_duration_ms,"native.snapshot.max_duration_ms")}}function _N(e){if(e===void 0)return;let t=ot(e,"native.pending_root_move"),r=t.id,i=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof r!="string"||!/^[a-f0-9-]{8,}$/u.test(r))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="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=ot(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,f=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 f!="string"||!/^[a-f0-9]{64}$/u.test(f))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:f}}return{id:r,fromArtifactRoot:zt(i),toArtifactRoot:zt(n),stage:a,...o?{cleanup:o}:{}}}function IN(e){if(e===void 0)return;let t=ot(e,"native.finish");if(t.pull_request===void 0)return{};let r=ot(t.pull_request,"native.finish.pull_request");if(r.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(r.command)||r.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(r.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let i=r.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(Ct.posix.isAbsolute(i[0])||Ct.win32.isAbsolute(i[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=r.timeout_ms??SN;if(!Number.isSafeInteger(n)||n<1||n>bf)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${bf}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function TN(e,t={}){let r=ot(e,"native"),i=r.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let n=r.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=r.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=r.max_verify_failures??ic;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=_N(r.pending_root_move),c=IN(r.finish);return{artifact_root:zt(i),language:xf(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:AN(r.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function jN(e){let t=ot(e,"classic"),r=t.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let i=t.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="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:Ef(t.artifact_layout),language:xf(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n}}function $N(e){let r=ot(e,"hook").allow_paths??[];if(!Array.isArray(r))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(r.map((i,n)=>oa(i,`hook.allow_paths[${n}]`)))]}}function ON(e){if(e===void 0)return{...mi};let t=ot(e,"memory"),r=t.learning??mi.learning,i=t.retrieval??mi.retrieval;if(typeof r!="boolean")throw new Error("memory.learning must be true or false");if(typeof i!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:r,retrieval:i}}function oc(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function HN(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||r.includes("\\")||r.includes("\0")||Ct.posix.isAbsolute(r)||Ct.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!r.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(r.length>yf)throw new Error(`${t} exceeds ${yf} characters`);let i=0;for(let n=0;n<r.length;n+=1)r[n]==="?"?i+=1:r[n]==="*"&&(i+=1,r[n+1]==="*"&&(n+=1));if(i>Nf)throw new Error(`${t} contains more than ${Nf} wildcard tokens`);return r}function DN(e){let r=oc(e,"knowledge.local").include??[];if(!Array.isArray(r))throw new Error("knowledge.local.include must be an array");return{include:[...new Set(r.map((i,n)=>HN(i,`knowledge.local.include[${n}]`)))]}}function BN(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 r=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),i=r==="localhost"||r==="127.0.0.1"||r==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&i))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function LN(e){let t=oc(e,"knowledge.remote"),r=BN(t.endpoint),i=t.token_env;if(i!==void 0&&(typeof i!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(i)))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:r,...i===void 0?{}:{token_env:i},...n===void 0?{}:{scope:n},timeout_ms:a}}function VN(e){if(e===void 0)return{...nc};let t=oc(e,"knowledge"),r=t.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let i=t.local===void 0?void 0:DN(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:LN(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:r,...i?{local:i}:{},remote:n}}function MN(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function FN(e,t,r,i,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 f=e.workflows??[e.default_workflow];if(!Array.isArray(f)||f.length===0||f.some(u=>u!=="native"&&u!=="classic"))throw new Error("workflows must contain native and/or classic");let d=[...new Set(f)];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:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function gr(e,t={}){let r=(0,vi.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${r.errors[0].message}`);let i=r.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=i,a=MN(n.ambient_resume),o=n.hook===void 0?void 0:$N(n.hook),s=ON(n.memory),c=VN(n.knowledge),l=n.native===void 0?void 0:TN(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),f=n.classic===void 0?void 0:jN(n.classic),d=FN(n,o,s,c,l,f,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...f?{classic:f}:{}}}function Pf(e){return{id:e.id,from_artifact_root:e.fromArtifactRoot,to_artifact_root:e.toArtifactRoot,stage:e.stage,...e.cleanup?{cleanup:{kind:e.cleanup.kind,state:e.cleanup.state,manifest_hash:e.cleanup.manifestHash}}:{}}}function Cf(e){let t=e.knowledge??{...nc};return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,memory:e.memory??{...mi},knowledge:{provider:t.provider,...t.local&&t.local.include.length>0?{local:{include:[...t.local.include]}}:{},...t.remote?{remote:{endpoint:t.remote.endpoint,timeout_ms:t.remote.timeout_ms,...t.remote.token_env===void 0?{}:{token_env:t.remote.token_env},...t.remote.scope===void 0?{}:{scope:t.remote.scope}}}:{}},...e.hook?{hook:{allow_paths:[...e.hook.allow_paths]}}:{},...e.native?{native:{artifact_root:e.native.artifact_root,language:e.native.language,clarification_mode:e.native.clarification_mode,archive_confirmation:e.native.archive_confirmation,max_verify_failures:e.native.max_verify_failures,...e.native.finish?.pull_request?{finish:{pull_request:{provider:e.native.finish.pull_request.provider,command:[...e.native.finish.pull_request.command],timeout_ms:e.native.finish.pull_request.timeout_ms}}}:{},...e.native.pending_root_move?{pending_root_move:Pf(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition}}:{}}}function we(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function yi(e,t){let r=Cf(t),i=gr((0,vi.stringify)(r)).config;if(!i)throw new Error("Unsupported Comet project schema");let n={...e,schema:i.schema,default_workflow:i.default_workflow,workflows:i.workflows,ambient_resume:i.ambient_resume};if(i.hook&&(n.hook={...we(e.hook),allow_paths:[...i.hook.allow_paths]}),i.memory){let a=we(e.memory);n.memory={...a,learning:i.memory.learning,retrieval:i.memory.retrieval}}if(i.knowledge){let a=we(e.knowledge),o={...a,provider:i.knowledge.provider};if(i.knowledge.local&&i.knowledge.local.include.length>0?o.local={...we(a.local),include:[...i.knowledge.local.include]}:delete o.local,i.knowledge.remote){let c={...we(a.remote),endpoint:i.knowledge.remote.endpoint,timeout_ms:i.knowledge.remote.timeout_ms,...i.knowledge.remote.token_env===void 0?{}:{token_env:i.knowledge.remote.token_env},...i.knowledge.remote.scope===void 0?{}:{scope:i.knowledge.remote.scope}};i.knowledge.remote.token_env===void 0&&delete c.token_env,i.knowledge.remote.scope===void 0&&delete c.scope,o.remote=c}else delete o.remote;n.knowledge=o}if(i.native){let a=we(e.native),o={...a,artifact_root:i.native.artifact_root,language:i.native.language,clarification_mode:i.native.clarification_mode,archive_confirmation:i.native.archive_confirmation,max_verify_failures:i.native.max_verify_failures};if(i.native.finish?.pull_request){let s=we(a.finish);o.finish={...s,pull_request:{...we(s.pull_request),provider:i.native.finish.pull_request.provider,command:[...i.native.finish.pull_request.command],timeout_ms:i.native.finish.pull_request.timeout_ms}}}else{let s={...we(a.finish)};delete s.pull_request,Object.keys(s).length>0?o.finish=s:delete o.finish}if(delete o.snapshot,i.native.pending_root_move){let s=we(a.pending_root_move),c=Pf(i.native.pending_root_move),l=we(s.cleanup),f=we(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...f}}:{}}}else delete o.pending_root_move;n.native=o}return i.classic&&(n.classic={...we(e.classic),artifact_layout:i.classic.artifact_layout,language:i.classic.language,context_compression:i.classic.context_compression,review_mode:i.classic.review_mode,auto_transition:i.classic.auto_transition}),n}function sa(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...mi},knowledge:{...nc},native:{artifact_root:zt(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:ic,snapshot:{...ye,include:[...ye.include],exclude:[...ye.exclude]}}}}import{createHash as WN}from"crypto";import{promises as ua}from"fs";import Rt from"path";import{constants as ca,promises as Jt}from"fs";var $e=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}};function sc(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Rf(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function Ni(e){return{dev:e.dev,ino:e.ino,birthtime:sc(e)}}function la(e,t){let r=Ni(e),i=Ni(t);return ze(r,i)?V(r,i):V(r,i)&&sc(e)===sc(t)&&Rf(e)===Rf(t)&&e.size===t.size}async function wr(e,t,r={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let i=r.label??"file",n=r.bigint===!0,a=await Jt.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new $e("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new $e("too-large",`${i} exceeds ${t} bytes`);let o=await Jt.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:Ni(a)});let s=process.platform==="win32"?ca.O_RDONLY:ca.O_RDONLY|ca.O_NOFOLLOW|ca.O_NONBLOCK,c;try{c=await Jt.open(e,s)}catch(l){throw l.code==="ELOOP"?new $e("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,f,d]=await Promise.all([c.stat({bigint:n}),Jt.lstat(e,{bigint:n}),Jt.realpath(e)]);if(!l.isFile()||!f.isFile()||f.isSymbolicLink()||d!==o||!la(a,l)||!la(a,f))throw new $e("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:Ni(l)}),await r.hooks?.afterOpen?.();let u=[],h=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let g=t+1-h,{bytesRead:w}=await c.read(v,0,Math.min(v.length,g),null);if(w===0)break;if(h+=w,h>t)throw new $e("too-large",`${i} exceeds ${t} bytes`);u.push(Buffer.from(v.subarray(0,w)))}await r.hooks?.beforeFinalCheck?.();let[m,p,y]=await Promise.all([c.stat({bigint:n}),Jt.lstat(e,{bigint:n}),Jt.realpath(e)]);if(!p.isFile()||p.isSymbolicLink()||y!==o||!la(a,m)||!la(a,p))throw new $e("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:y,identity:Ni(m)}),{bytes:Buffer.concat(u,h),stat:m,realPath:y}}finally{await c.close()}}function qN(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function cc(e,t){let r=Rt.relative(e,t);return r===""||!Rt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Rt.sep}`)}async function Af(e,t){let r=Rt.resolve(e),i=await ua.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return ua.realpath(r)}async function _f(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=Rt.join(n,r[a]);let o;try{o=await ua.lstat(n)}catch(f){if(qN(f))return{exists:!1,kind:"missing"};throw f}let s=Rt.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${i.label} crosses a symbolic link or junction at ${s}`);let c=a===r.length-1;if(!c&&!o.isDirectory())throw new Error(`${i.label} ancestor ${s} must be a real directory`);if(c&&(i.expected==="file"&&!o.isFile()||i.expected==="directory"&&!o.isDirectory()||i.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${i.label} must be a real ${i.expected}`);let l=await ua.realpath(n);if(!cc(t,l))throw new Error(`${i.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 yr(e,t,r){let i=oa(t,r.label),n=Rt.resolve(e),a=await Af(n,r.label),o=i.split("/"),s=Rt.resolve(n,...o);if(!cc(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await _f(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function At(e,t,r,i){let n=await yr(e,t,{label:i.label,expected:"file"});if(!n.exists){let o=new Error(`${i.label} does not exist`);throw o.code="ENOENT",o}let a=await Af(n.projectRoot,i.label);return wr(n.target,r,{...i,verify:async(o,s)=>{if(!cc(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await _f(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var bi=".comet/config.yaml";function lc(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function zN(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function da(e,t={}){return(await ki(e,t)).document}async function If(e){try{return(await At(e,bi,gi,{label:bi})).bytes}catch(t){if(zN(t))return null;throw t}}function Tf(e){return e?{exists:!0,sha256:WN("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function fa(e){return Tf(await If(e))}async function ki(e,t={}){let r=await If(e);return{document:r?gr(r.toString("utf8"),t):null,identity:Tf(r)}}async function uc(e){return(await da(e))?.config??null}var iR=16*1024;async function dc(e,t){if(!t)return;let r=await fa(e);if(!lc(r,t))throw new Error("Project config changed before commit; rerun the operation")}import{randomUUID as KN}from"crypto";import{promises as ie}from"fs";import Oe from"path";function fc(e,t){let r=Oe.relative(e,t);return r===""||!Oe.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Oe.sep}`)}function YN(e,t){return V({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function hc(e,t){return V({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function XN(e,t){return hc(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function jf(e){let t=await ie.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 ie.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Ei(e){for(let t of e){let r=await ie.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!YN(t,r)||await ie.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function QN(e,t){let r=Oe.resolve(e),i=Oe.resolve(t);if(!fc(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await jf(r)],a=Oe.relative(r,i).split(Oe.sep).filter(Boolean),o=r;for(let s of a){await Ei(n),o=Oe.join(o,s);try{await ie.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await jf(o);if(!fc(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Ei(n),n}async function ZN(e){let t;try{t=await ie.open(e,"r"),await t.sync()}catch(r){let i=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw r}finally{await t?.close()}}async function eb(e,t,r={}){let i=Oe.dirname(e),n=r.containedRoot?await QN(r.containedRoot,i):null;n||await ie.mkdir(i,{recursive:!0});let a=Oe.join(i,`.${Oe.basename(e)}.${KN()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await ie.open(a,"wx"),s=await o.stat(),n){let[l,f]=await Promise.all([ie.lstat(a),ie.realpath(a)]);if(await Ei(n),!l.isFile()||l.isSymbolicLink()||!hc(s,l)||!fc(n[0].realPath,f))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(),!hc(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.beforeCommit?.(),n){await Ei(n);let l=await ie.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!XN(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await ie.link(a,e),await ie.unlink(a)):await ie.rename(a,e),await ZN(i)}catch(l){if(await o?.close(),!n)await ie.rm(a,{force:!0});else try{await Ei(n),await ie.rm(a,{force:!0})}catch{}throw l}}async function xe(e,t,r={}){await eb(e,t,r)}async function me(e,t,r={}){await xe(e,JSON.stringify(t,null,2)+`
171
- `,r)}import{existsSync as $f,promises as Gt}from"fs";import T from"path";import tb from"os";var xi=".comet/config.yaml",rb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function pc(e){try{return await Gt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function ib(e){try{let t=await Gt.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function br(e,t){let r=T.relative(e,t);return r===""||!T.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${T.sep}`)}async function Nr(e){let t=[],r=e;for(;!await pc(r);){let n=T.dirname(r);if(n===r)break;t.push(T.basename(r)),r=n}let i=await Gt.realpath(r);return T.resolve(i,...t.reverse())}async function mc(e){try{return(await Gt.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function ha(e){let t=T.resolve(e);try{(await Gt.stat(t)).isDirectory()||(t=T.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=T.resolve(tb.homedir());for(;;){if(!(t===i&&r!==i)){let o=T.join(t,...xi.split("/")),s=t===r||await ib(o);if(await pc(o)&&s)return t}if(await pc(T.join(t,".git")))return t;let a=T.dirname(t);if(a===t)return r;t=a}}function pa(e){return zt(e)}async function nb(e,t){let r=pa(t),i=T.resolve(e,...r.split("/")),n=await Gt.realpath(e),a=await Nr(i);if(!br(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function _t(e,t){let r=pa(t),i=await nb(e,r),n=T.join(i,"comet");if(await mc(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Nr(i),Nr(n)]);if(!br(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=T.resolve(e),c=T.join(s,".comet","runtime","native");if(await mc(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,f]=await Promise.all([Gt.realpath(s),Nr(c)]);if(!br(l,f))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:T.join(e,...xi.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:T.join(n,"specs"),changesDir:T.join(n,"changes"),archiveDir:T.join(n,"archive"),runtimeDir:c,changesRuntimeDir:T.join(c,"changes"),locksDir:T.join(c,"locks"),transactionsDir:T.join(c,"transactions")}}function Of(e){if(!rb.test(e))throw new Error(`Invalid Native change name: ${e}`)}function He(e,t){Of(t);let r=T.join(e.changesRuntimeDir,t);if(!se(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function vc(e,t){Of(t);let r=T.join(e.changesDir,t,"runtime");if(!se(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function Je(e,t){let r=He(e,t);if($f(r))return r;let i=vc(e,t);return $f(i)?i:r}function Ge(e,t){let r=T.resolve(t);if(se(e.runtimeDir,r))return e.runtimeDir;if(se(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function se(e,t){return br(T.resolve(e),T.resolve(t))}async function q(e,t){let r=T.resolve(e),i=T.resolve(t);if(!br(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await mc(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Nr(r),Nr(i)]);if(!br(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}function ob(e="docs",t="en"){return sa(e,t)}async function ve(e){let t=(await da(e))?.config??null;return t?.native?t:null}async function ma(e){let t=await ve(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 va(e,t,r={}){let i=await ki(e,{allowPartialProject:!0}),n=yi(i.document?.value??{},t),a=ab.join(e,...xi.split("/"));await xe(a,wi(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await r.beforeCommit?.(),await dc(e,i.identity)}})}async function Hf(e){let t=await ha(e.startPath),r=await ve(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${xi} was not found`);if(r?.native.pending_root_move)throw new Error(`Native root move ${r.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let i=e.explicitArtifactRoot?pa(e.explicitArtifactRoot):void 0;if(r&&i&&i!==r.native.artifact_root)throw new Error(`Configured Native artifact root is ${r.native.artifact_root}; refusing conflicting root ${i}`);let n=r??ob(i??"docs"),a=await _t(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}var Na=Hr(hr(),1);import{promises as sb}from"node:fs";var kr="comet.native.v4",Pi="comet.native.local-execution.v4";var ga=["multi-session","single-session"];function gc(){return{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}}}var cb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,lb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ub=/^A[1-9][0-9]*$/u,db=/^[a-f0-9]{64}$/u,fb=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"]),ya=class extends Error{constructor(r,i){super(`Native state version conflict: expected ${r}, got ${i}`);this.expectedStateVersion=r;this.actualStateVersion=i;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};function ce(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function le(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function X(e,t,r){if(typeof e!="string"||!r?.empty&&e.length===0)throw new Error(`${t} must be ${r?.empty?"a string":"a non-empty string"}`);return e}function yc(e,t){return e===null?null:X(e,t)}function hb(e,t){let r=X(e,t);if(!db.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function Sr(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function M(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function pb(e,t){return e===null?null:M(e,t,Number.MIN_SAFE_INTEGER)}function G(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Ue(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function ba(e,t){return Ue(e,t,(r,i)=>X(r,`${t}[${i}]`))}function Ut(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Er(e,t){let r=X(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function Nc(e,t,r=!1){let i=X(e,t);if(i.includes("\\")||i.startsWith("/")||/^[A-Za-z]:/u.test(i)||i.split("/").includes("..")||!r&&(i==="."||i.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return i}function Pe(e,t){let r=ce(e,t);return le(r,new Set(["text","truncated"]),t),{text:X(r.text,`${t}.text`,{empty:!0}),truncated:Sr(r.truncated,`${t}.truncated`)}}function mb(e,t){let r=`Native spec_changes[${t}]`,i=ce(e,r);le(i,new Set(["capability","operation","source"]),r);let n=X(i.capability,`${r}.capability`);if(!lb.test(n))throw new Error(`${r}.capability is invalid`);let a=G(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:Nc(i.source,`${r}.source`);if(a==="remove"&&o!==null)throw new Error(`${r} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${r} ${a} requires a source`);return{capability:n,operation:a,source:o}}function vb(e){let t="Native workspace",r=ce(e,t);le(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=G(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=yc(r.change_branch,`${t}.change_branch`),a=yc(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:G(r.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(i==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(i==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(i!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:i,change_branch:n,target_branch:a,finish:o}}function gb(e){let t="Native loop",r=ce(e,t);le(r,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 i=ba(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);return Ut(i,`${t}.previous_unresolved_ids`),{stage:G(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:M(r.goal_cycle,`${t}.goal_cycle`,1),iteration:M(r.iteration,`${t}.iteration`),attempt:M(r.attempt,`${t}.attempt`),retry_epoch:M(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:M(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:M(r.no_progress_count,`${t}.no_progress_count`),execution_failure_count:M(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:yc(r.next_action,`${t}.next_action`)}}function wb(e,t){let r=`Native acceptance[${t}]`,i=ce(e,r);le(i,new Set(["id","source","text","result","reason"]),r);let n=X(i.id,`${r}.id`);if(!ub.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:Nc(i.source,`${r}.source`),text:X(i.text,`${r}.text`),result:G(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:Pe(i.reason,`${r}.reason`)}}function yb(e,t){let r=`Native builder_handoff.checks[${t}]`,i=ce(e,r);return le(i,new Set(["name","result","note"]),r),{name:Pe(i.name,`${r}.name`),result:G(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:Pe(i.note,`${r}.note`)}}function Nb(e){let t="Native builder_handoff",r=ce(e,t);le(r,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 i=ba(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);Ut(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:ce(r.review,`${t}.review`);return n&&le(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:X(r.candidate_id,`${t}.candidate_id`),identity_provider:X(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:X(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:M(r.iteration,`${t}.iteration`,1),summary:Pe(r.summary,`${t}.summary`),addressed_acceptance_ids:i,checks:Ue(r.checks,`${t}.checks`,yb),checks_truncated:Sr(r.checks_truncated,`${t}.checks_truncated`),known_limits:Ue(r.known_limits,`${t}.known_limits`,(a,o)=>Pe(a,`${t}.known_limits[${o}]`)),known_limits_truncated:Sr(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:G(n.status,["passed"],`${t}.review.status`),summary:Pe(n.summary,`${t}.review.summary`),reviewer_execution_ref:X(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:Er(r.submitted_at,`${t}.submitted_at`)}}function bb(e,t){let r=`Native blockers[${t}]`,i=ce(e,r);le(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=ba(i.acceptance_ids,`${r}.acceptance_ids`);return Ut(n,`${r}.acceptance_ids`),{owner:G(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:Pe(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:G(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function kb(e,t){let r=`Native verification.checks[${t}]`,i=ce(e,r);return le(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:X(i.id,`${r}.id`),name:Pe(i.name,`${r}.name`),argv_display:Ue(i.argv_display,`${r}.argv_display`,(n,a)=>Pe(n,`${r}.argv_display[${a}]`)),argv_truncated:Sr(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:Nc(i.cwd_ref,`${r}.cwd_ref`,!0),status:G(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:pb(i.exit_code,`${r}.exit_code`),duration_ms:M(i.duration_ms,`${r}.duration_ms`)}}function Sb(e){let t="Native verification",r=ce(e,t);le(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=Ue(r.checks,`${t}.checks`,kb);Ut(i.map(a=>a.id),`${t}.checks IDs`);let n=X(r.identity_provider,`${t}.identity_provider`);return{candidate_id:X(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:X(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:M(r.iteration,`${t}.iteration`,1),attempt:M(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":G(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:G(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:Pe(r.summary,`${t}.summary`),risks:Ue(r.risks,`${t}.risks`,(a,o)=>Pe(a,`${t}.risks[${o}]`)),risks_truncated:Sr(r.risks_truncated,`${t}.risks_truncated`),completed_at:Er(r.completed_at,`${t}.completed_at`)}}function Df(e,t){let r=`Native history[${t}]`,i=ce(e,r);le(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=ba(i.unresolved_ids,`${r}.unresolved_ids`);return Ut(n,`${r}.unresolved_ids`),{goal_cycle:M(i.goal_cycle,`${r}.goal_cycle`,1),iteration:M(i.iteration,`${r}.iteration`),attempt:M(i.attempt,`${r}.attempt`),outcome:G(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:Pe(i.summary,`${r}.summary`),completed_at:Er(i.completed_at,`${r}.completed_at`)}}function Eb(e){let t="Native history_overflow.outcome_counts",r=ce(e,t),i=["pass","fail","blocked","execution-error","recovery"];return le(r,new Set(i),t),{pass:M(r.pass,`${t}.pass`),fail:M(r.fail,`${t}.fail`),blocked:M(r.blocked,`${t}.blocked`),"execution-error":M(r["execution-error"],`${t}.execution-error`),recovery:M(r.recovery,`${t}.recovery`)}}function xb(e){let t="Native history_overflow",r=ce(e,t);le(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=M(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:Er(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:Er(r.last_dropped_at,`${t}.last_dropped_at`);if(i===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(i>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=Eb(r.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==i)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:i,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function Pb(e){let t=new Set(e.acceptance.map(r=>r.id));for(let r of e.loop.previous_unresolved_ids)if(!t.has(r))throw new Error(`Native loop references unknown acceptance ID ${r}`);for(let r of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(r))throw new Error(`Native builder handoff references unknown ID ${r}`);for(let r of e.blockers)for(let i of r.acceptance_ids)if(!t.has(i))throw new Error(`Native blocker references unknown ID ${i}`);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 i=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(!i&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function Cb(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 r=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(r!==null&&e.loop.stage!==r)throw new Error(`Native status ${e.status} requires loop stage ${r}`);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(i=>i.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(i=>i.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 C(e){let t=ce(e,"Native portable state");if(le(t,fb,"Native portable state"),t.schema!==kr)throw new Error(`Native portable state schema must be ${kr}`);let r=X(t.name,"Native state name");if(!cb.test(r))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let i=Ue(t.spec_changes,"Native spec_changes",mb);Ut(i.map(s=>s.capability),"Native spec change capabilities");let n=Ue(t.acceptance,"Native acceptance",wb);Ut(n.map(s=>s.id),"Native acceptance IDs");let a=Ue(t.history,"Native history",Df);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:kr,name:r,language:G(t.language,["en","zh-CN"],"Native state language"),phase:G(t.phase,["shape","build","verify","archive"],"Native state phase"),status:G(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:M(t.state_version,"Native state_version",1),brief:"brief.md",...t.children_contract_hash===void 0?{}:{children_contract_hash:hb(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:G(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:vb(t.workspace),loop:gb(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:Nb(t.builder_handoff),blockers:Ue(t.blockers,"Native blockers",bb),verification:t.verification===null?null:Sb(t.verification),history:a,history_overflow:xb(t.history_overflow),verification_result:G(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:G(t.verification_report,["verification.md"],"Native verification_report"),archived:Sr(t.archived,"Native archived"),created_at:Er(t.created_at,"Native created_at")};return Pb(o),Cb(o),o}function Ne(e,t){let r=C(e),i=Df(t,r.history.length),n=[...r.history,i],a={...r.history_overflow,outcome_counts:{...r.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return C({...r,history:n,history_overflow:a})}function Rb(e,t){let r=(0,Na.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`${t} is invalid YAML: ${r.errors[0].message}`);return r.toJS({mapAsMap:!1})}async function De(e){let t=await sb.readFile(e,"utf8");return C(Rb(t,"Native portable state"))}async function ka(e,t,r={}){let i=C(t);await xe(e,(0,Na.stringify)(i),r)}var wa=new Map;async function Ab(e,t){let r=wa.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);wa.set(e,a),await r;try{return await t()}finally{i(),wa.get(e)===a&&wa.delete(e)}}async function Ci(e){return Ab(e.file,async()=>{let t=M(e.expectedStateVersion,"Native expected state version",1),r=C(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await De(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new ya(t,i.state_version);return await ka(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await De(e.file);if(n.state_version!==t)throw new ya(t,n.state_version)}}),r})}import Xt from"node:path";import{randomUUID as kS}from"node:crypto";import{promises as Bh}from"node:fs";import{promises as mS}from"fs";import vS from"path";import{AsyncLocalStorage as _b}from"async_hooks";import{randomUUID as Vf}from"crypto";import{promises as Ce}from"fs";import Mf from"os";import Q from"path";var Bf=16*1024,Ff=".coordinator",Ib=5e3,Lf=new _b,Sa=new Map;function Tb(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function jb(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let r=e;if(typeof r.id!="string"||r.id.length===0||typeof r.pid!="number"||!Number.isSafeInteger(r.pid)||r.pid<1||typeof r.hostname!="string"||r.hostname.length===0||typeof r.createdAt!="string"||r.createdAt.length===0||typeof r.operation!="string"||r.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return r}function qf(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 bc(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return ze(r,i)?V(r,i):V(r,i)&&e.size===t.size}function kc(e,t){return bc(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function st(e){let t,r;try{let i=await wr(e,Bf,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof $e?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${Bf} bytes: ${e}`,{cause:i}):i.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:i}):new Error(`Native lock changed while reading: ${e}`,{cause:i}):i}return{file:e,owner:jb(JSON.parse(t.toString("utf8")),e),identity:qf(r)}}async function $b(e){return(await st(e))?.owner??null}function Wf(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==Mf.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=Vb(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function Ob(e,t){try{await Ce.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await Ce.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function Sc(e,t){let r=await st(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!kc(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await Ce.mkdir(t,{recursive:!0});let i=Q.join(t,`${Q.basename(e.file)}.${e.owner.id}.${Vf()}.removed`);try{await Ce.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await st(i);if(!n||n.owner.id!==e.owner.id||!bc(n.identity,e.identity))throw await Ob(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await Ce.rm(i,{force:!0}),"removed"}function zf(e){return{id:Vf(),pid:process.pid,hostname:Mf.hostname(),createdAt:new Date().toISOString(),operation:e}}async function Jf(e,t){let r;try{r=await Ce.open(e,"wx")}catch(i){if(i.code==="EEXIST"){let n=await $b(e);throw new Error(`Native lock is already held: ${e}${n?` by pid ${n.pid} for ${n.operation}`:""}`,{cause:i})}throw i}try{return await r.writeFile(JSON.stringify(t,null,2)+`
172
- `,"utf8"),await r.sync(),qf(await r.stat({bigint:!0}))}finally{await r.close()}}async function Hb(e,t){let r=await q(e.runtimeDir,e.locksDir);await Ce.mkdir(r,{recursive:!0});let i=await q(e.runtimeDir,Q.join(r,Ff));await Ce.mkdir(i,{recursive:!0});let n=zf(t),a=Q.join(i,`.${n.id}.tmp`),o=Q.join(i,`${n.id}.claim`);try{let s=await Jf(a,n);await Ce.rename(a,o);let c=await st(o);if(!c||!bc(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:r,owner:n,identity:c.identity}}finally{await Ce.rm(a,{force:!0})}}async function Db(e){let t=Q.dirname(e.file),r=!1,i=Q.basename(e.file);for(let n of await Ce.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=Q.join(t,n.name);if(Q.resolve(a)!==Q.resolve(e.file))try{let o=await st(a),s=Wf(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Sc(o,t);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function Gf(e){let t=await st(e.file);if(t){if(t.owner.id!==e.owner.id||!kc(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await Sc(t,Q.dirname(e.file))}}async function Bb(e,t){let r=Date.now()+Ib;for(;;){let i=await Hb(e,t);if(!await Db(i))return i;if(await Gf(i),Date.now()>=r)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function Lb(e){let t=Sa.get(e)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=t.then(()=>i);return Sa.set(e,n),await t,()=>{r(),Sa.get(e)===n&&Sa.delete(e)}}async function Ec(e,t,r){let i=Q.resolve(e.locksDir),n=Lf.getStore();if(n?.has(i))return r();let a=await Lb(i);try{let o=await Bb(e,t),s=new Map(n??[]);return s.set(i,o),await Lf.run(s,async()=>{try{return await r()}finally{await Gf(o)}})}finally{a()}}async function Uf(e,t,r){let i=[...new Map(e.map(a=>[Q.resolve(a.locksDir),a])).values()].sort((a,o)=>Q.resolve(a.locksDir).localeCompare(Q.resolve(o.locksDir))),n=async a=>{let o=i[a];return o?Ec(o,t,()=>n(a+1)):r()};return n(0)}async function Ea(e,t,r){return Ec(e,`acquire ${t}`,async()=>{let i=await q(e.runtimeDir,e.locksDir);await Ce.mkdir(i,{recursive:!0});let n=await q(e.runtimeDir,Q.join(i,Tb(t))),a=zf(r),o=await Jf(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:i,owner:a,identity:o}})}async function xa(e){await st(e.file)&&await Ec({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${Q.basename(e.file)}`,async()=>{let t=await st(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!kc(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let r=Q.join(e.locksDir,Ff);await Sc(t,r)})}function Vb(e){try{return process.kill(e,0),!0}catch(t){let r=t.code;return r==="ESRCH"?!1:r==="EPERM"?!0:null}}async function Kf(e){return Wf(await st(e))}import Vc from"node:path";import $k from"node:path";var $c=Hr(hr(),1);import Cr from"path";var xc={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:"验证预期"}},Xf={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:"结论"}},Qf={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:"结论"}},Zf=new Map,Yf=new Map;for(let e of Object.keys(xc)){for(let[t,r]of Object.entries(xc[e]))Zf.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(Xf[e]))Yf.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(Qf[e]))Yf.set(r.toLocaleLowerCase("en-US"),t)}function Mb(e,t){return xc[e][t]}function Pc(e,t){return Xf[e][t]??Qf[e][t]}function Cc(e){return Zf.get(e.trim().toLocaleLowerCase("en-US"))??null}function Pa(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(r=>`# ${Mb(e,r)}
170
+ `)}function eb(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||Tt.posix.isAbsolute(r)||Tt.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be a project-relative path`);if(r===".")return[];let i=r.replaceAll("\\","/").split("/");if(i.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(i.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return i}function Yt(e){let t=eb(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Bf(e,t="docs"){let r=e??t;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function ma(e,t,r=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim().replaceAll("\\","/");if(i.length===0||Tt.posix.isAbsolute(i)||Tt.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be relative to its declared path base`);let n=i.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(!r&&/[*?]/u.test(i))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function dt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Lf(e,t,r){let i=e??t;if(i!=="en"&&i!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return i}function vc(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.startsWith("/")||e.split("/").includes(".."))throw new Error(`${t} contains an unsafe pattern`);if(e.length>pa)throw new Error(`${t} exceeds ${pa} characters`);let r=0;for(let i=0;i<e.length;i+=1)e[i]==="?"?r+=1:e[i]==="*"&&(r+=1,e[i+1]==="*"&&(i+=1));if(r>ha)throw new Error(`${t} contains more than ${ha} wildcard tokens`);return e}function Hf(e,t,r){if(e===void 0)return[...r];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(i=>vc(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function pc(e,t,r){let i=e??t;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${r} must be a positive integer`);return i}function tb(e){if(e===void 0)return{...ke,include:[...ke.include],exclude:[...ke.exclude]};let t=dt(e,"native.snapshot");return{include:Hf(t.include,"native.snapshot.include",ke.include),exclude:Hf(t.exclude,"native.snapshot.exclude",ke.exclude),max_files:pc(t.max_files,ke.max_files,"native.snapshot.max_files"),max_total_bytes:pc(t.max_total_bytes,ke.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:pc(t.max_duration_ms,ke.max_duration_ms,"native.snapshot.max_duration_ms")}}function rb(e){if(e===void 0)return;let t=dt(e,"native.pending_root_move"),r=t.id,i=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof r!="string"||!/^[a-f0-9-]{8,}$/u.test(r))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="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=dt(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,f=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 f!="string"||!/^[a-f0-9]{64}$/u.test(f))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:f}}return{id:r,fromArtifactRoot:Yt(i),toArtifactRoot:Yt(n),stage:a,...o?{cleanup:o}:{}}}function ib(e){if(e===void 0)return;let t=dt(e,"native.finish");if(t.pull_request===void 0)return{};let r=dt(t.pull_request,"native.finish.pull_request");if(r.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(r.command)||r.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(r.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let i=r.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(Tt.posix.isAbsolute(i[0])||Tt.win32.isAbsolute(i[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=r.timeout_ms??KN;if(!Number.isSafeInteger(n)||n<1||n>Of)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Of}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function nb(e,t={}){let r=dt(e,"native"),i=r.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let n=r.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=r.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=r.max_verify_failures??hc;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=rb(r.pending_root_move),c=ib(r.finish);return{artifact_root:Yt(i),language:Lf(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:tb(r.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function ab(e){let t=dt(e,"classic"),r=t.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let i=t.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="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:Bf(t.artifact_layout),language:Lf(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n}}function ob(e){let r=dt(e,"hook").allow_paths??[];if(!Array.isArray(r))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(r.map((i,n)=>ma(i,`hook.allow_paths[${n}]`)))]}}function sb(e){if(e===void 0)return{...Si};let t=dt(e,"memory"),r=t.learning??Si.learning,i=t.retrieval??Si.retrieval;if(typeof r!="boolean")throw new Error("memory.learning must be true or false");if(typeof i!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:r,retrieval:i}}function gc(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function cb(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||r.includes("\\")||r.includes("\0")||Tt.posix.isAbsolute(r)||Tt.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!r.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(r.length>jf)throw new Error(`${t} exceeds ${jf} characters`);let i=0;for(let n=0;n<r.length;n+=1)r[n]==="?"?i+=1:r[n]==="*"&&(i+=1,r[n+1]==="*"&&(n+=1));if(i>$f)throw new Error(`${t} contains more than ${$f} wildcard tokens`);return r}function lb(e){let r=gc(e,"knowledge.local").include??[];if(!Array.isArray(r))throw new Error("knowledge.local.include must be an array");return{include:[...new Set(r.map((i,n)=>cb(i,`knowledge.local.include[${n}]`)))]}}function ub(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 r=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),i=r==="localhost"||r==="127.0.0.1"||r==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&i))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function db(e){let t=gc(e,"knowledge.remote"),r=ub(t.endpoint),i=t.token_env;if(i!==void 0&&(typeof i!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(i)))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:r,...i===void 0?{}:{token_env:i},...n===void 0?{}:{scope:n},timeout_ms:a}}function fb(e){if(e===void 0)return{...mc};let t=gc(e,"knowledge"),r=t.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let i=t.local===void 0?void 0:lb(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:db(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:r,...i?{local:i}:{},remote:n}}function pb(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function hb(e,t,r,i,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 f=e.workflows??[e.default_workflow];if(!Array.isArray(f)||f.length===0||f.some(d=>d!=="native"&&d!=="classic"))throw new Error("workflows must contain native and/or classic");let u=[...new Set(f)];if(!u.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(u.includes("native")&&!n)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:u,ambient_resume:o,...t?{hook:t}:{},memory:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function Er(e,t={}){let r=(0,Ei.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${r.errors[0].message}`);let i=r.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=i,a=pb(n.ambient_resume),o=n.hook===void 0?void 0:ob(n.hook),s=sb(n.memory),c=fb(n.knowledge),l=n.native===void 0?void 0:nb(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),f=n.classic===void 0?void 0:ab(n.classic),u=hb(n,o,s,c,l,f,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:u,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...f?{classic:f}:{}}}function Vf(e){return{id:e.id,from_artifact_root:e.fromArtifactRoot,to_artifact_root:e.toArtifactRoot,stage:e.stage,...e.cleanup?{cleanup:{kind:e.cleanup.kind,state:e.cleanup.state,manifest_hash:e.cleanup.manifestHash}}:{}}}function Mf(e){let t=e.knowledge??{...mc};return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,memory:e.memory??{...Si},knowledge:{provider:t.provider,...t.local&&t.local.include.length>0?{local:{include:[...t.local.include]}}:{},...t.remote?{remote:{endpoint:t.remote.endpoint,timeout_ms:t.remote.timeout_ms,...t.remote.token_env===void 0?{}:{token_env:t.remote.token_env},...t.remote.scope===void 0?{}:{scope:t.remote.scope}}}:{}},...e.hook?{hook:{allow_paths:[...e.hook.allow_paths]}}:{},...e.native?{native:{artifact_root:e.native.artifact_root,language:e.native.language,clarification_mode:e.native.clarification_mode,archive_confirmation:e.native.archive_confirmation,max_verify_failures:e.native.max_verify_failures,...e.native.finish?.pull_request?{finish:{pull_request:{provider:e.native.finish.pull_request.provider,command:[...e.native.finish.pull_request.command],timeout_ms:e.native.finish.pull_request.timeout_ms}}}:{},...e.native.pending_root_move?{pending_root_move:Vf(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition}}:{}}}function be(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Pi(e,t){let r=Mf(t),i=Er((0,Ei.stringify)(r)).config;if(!i)throw new Error("Unsupported Comet project schema");let n={...e,schema:i.schema,default_workflow:i.default_workflow,workflows:i.workflows,ambient_resume:i.ambient_resume};if(i.hook&&(n.hook={...be(e.hook),allow_paths:[...i.hook.allow_paths]}),i.memory){let a=be(e.memory);n.memory={...a,learning:i.memory.learning,retrieval:i.memory.retrieval}}if(i.knowledge){let a=be(e.knowledge),o={...a,provider:i.knowledge.provider};if(i.knowledge.local&&i.knowledge.local.include.length>0?o.local={...be(a.local),include:[...i.knowledge.local.include]}:delete o.local,i.knowledge.remote){let c={...be(a.remote),endpoint:i.knowledge.remote.endpoint,timeout_ms:i.knowledge.remote.timeout_ms,...i.knowledge.remote.token_env===void 0?{}:{token_env:i.knowledge.remote.token_env},...i.knowledge.remote.scope===void 0?{}:{scope:i.knowledge.remote.scope}};i.knowledge.remote.token_env===void 0&&delete c.token_env,i.knowledge.remote.scope===void 0&&delete c.scope,o.remote=c}else delete o.remote;n.knowledge=o}if(i.native){let a=be(e.native),o={...a,artifact_root:i.native.artifact_root,language:i.native.language,clarification_mode:i.native.clarification_mode,archive_confirmation:i.native.archive_confirmation,max_verify_failures:i.native.max_verify_failures};if(i.native.finish?.pull_request){let s=be(a.finish);o.finish={...s,pull_request:{...be(s.pull_request),provider:i.native.finish.pull_request.provider,command:[...i.native.finish.pull_request.command],timeout_ms:i.native.finish.pull_request.timeout_ms}}}else{let s={...be(a.finish)};delete s.pull_request,Object.keys(s).length>0?o.finish=s:delete o.finish}if(delete o.snapshot,i.native.pending_root_move){let s=be(a.pending_root_move),c=Vf(i.native.pending_root_move),l=be(s.cleanup),f=be(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...f}}:{}}}else delete o.pending_root_move;n.native=o}return i.classic&&(n.classic={...be(e.classic),artifact_layout:i.classic.artifact_layout,language:i.classic.language,context_compression:i.classic.context_compression,review_mode:i.classic.review_mode,auto_transition:i.classic.auto_transition}),n}function va(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...Si},knowledge:{...mc},native:{artifact_root:Yt(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:hc,snapshot:{...ke,include:[...ke.include],exclude:[...ke.exclude]}}}}import{createHash as vb}from"crypto";import{promises as ya}from"fs";import jt from"path";import{constants as ga,promises as Xt}from"fs";var Be=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}};function wc(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Ff(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function Ri(e){return{dev:e.dev,ino:e.ino,birthtime:wc(e)}}function wa(e,t){let r=Ri(e),i=Ri(t);return Ke(r,i)?M(r,i):M(r,i)&&wc(e)===wc(t)&&Ff(e)===Ff(t)&&e.size===t.size}async function xr(e,t,r={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let i=r.label??"file",n=r.bigint===!0,a=await Xt.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Be("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Be("too-large",`${i} exceeds ${t} bytes`);let o=await Xt.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:Ri(a)});let s=process.platform==="win32"?ga.O_RDONLY:ga.O_RDONLY|ga.O_NOFOLLOW|ga.O_NONBLOCK,c;try{c=await Xt.open(e,s)}catch(l){throw l.code==="ELOOP"?new Be("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,f,u]=await Promise.all([c.stat({bigint:n}),Xt.lstat(e,{bigint:n}),Xt.realpath(e)]);if(!l.isFile()||!f.isFile()||f.isSymbolicLink()||u!==o||!wa(a,l)||!wa(a,f))throw new Be("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:u,identity:Ri(l)}),await r.hooks?.afterOpen?.();let d=[],p=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let w=t+1-p,{bytesRead:y}=await c.read(v,0,Math.min(v.length,w),null);if(y===0)break;if(p+=y,p>t)throw new Be("too-large",`${i} exceeds ${t} bytes`);d.push(Buffer.from(v.subarray(0,y)))}await r.hooks?.beforeFinalCheck?.();let[m,h,g]=await Promise.all([c.stat({bigint:n}),Xt.lstat(e,{bigint:n}),Xt.realpath(e)]);if(!h.isFile()||h.isSymbolicLink()||g!==o||!wa(a,m)||!wa(a,h))throw new Be("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:g,identity:Ri(m)}),{bytes:Buffer.concat(d,p),stat:m,realPath:g}}finally{await c.close()}}function mb(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function yc(e,t){let r=jt.relative(e,t);return r===""||!jt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${jt.sep}`)}async function qf(e,t){let r=jt.resolve(e),i=await ya.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return ya.realpath(r)}async function Wf(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=jt.join(n,r[a]);let o;try{o=await ya.lstat(n)}catch(f){if(mb(f))return{exists:!1,kind:"missing"};throw f}let s=jt.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${i.label} crosses a symbolic link or junction at ${s}`);let c=a===r.length-1;if(!c&&!o.isDirectory())throw new Error(`${i.label} ancestor ${s} must be a real directory`);if(c&&(i.expected==="file"&&!o.isFile()||i.expected==="directory"&&!o.isDirectory()||i.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${i.label} must be a real ${i.expected}`);let l=await ya.realpath(n);if(!yc(t,l))throw new Error(`${i.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 Cr(e,t,r){let i=ma(t,r.label),n=jt.resolve(e),a=await qf(n,r.label),o=i.split("/"),s=jt.resolve(n,...o);if(!yc(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await Wf(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function $t(e,t,r,i){let n=await Cr(e,t,{label:i.label,expected:"file"});if(!n.exists){let o=new Error(`${i.label} does not exist`);throw o.code="ENOENT",o}let a=await qf(n.projectRoot,i.label);return xr(n.target,r,{...i,verify:async(o,s)=>{if(!yc(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Wf(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var Ai=".comet/config.yaml";function Nc(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function gb(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Na(e,t={}){return(await _i(e,t)).document}async function zf(e){try{return(await $t(e,Ai,xi,{label:Ai})).bytes}catch(t){if(gb(t))return null;throw t}}function Jf(e){return e?{exists:!0,sha256:vb("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function ba(e){return Jf(await zf(e))}async function _i(e,t={}){let r=await zf(e);return{document:r?Er(r.toString("utf8"),t):null,identity:Jf(r)}}async function bc(e){return(await Na(e))?.config??null}var FR=16*1024;async function kc(e,t){if(!t)return;let r=await ba(e);if(!Nc(r,t))throw new Error("Project config changed before commit; rerun the operation")}import{randomUUID as bb}from"crypto";import{promises as ee}from"fs";import Le from"path";function ka(e,t){let r=Le.relative(e,t);return r===""||!Le.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Le.sep}`)}function kb(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Sa(e,t){return M({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function Sb(e,t){return Sa(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Gf(e){let t=await ee.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 ee.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Pr(e){for(let t of e){let r=await ee.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!kb(t,r)||await ee.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function Eb(e,t,r){let[i,n]=await Promise.all([ee.lstat(e),ee.realpath(e),r?Pr(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!Sa(i,t)||r&&!ka(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function xb(e,t){let r=Le.resolve(e),i=Le.resolve(t);if(!ka(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await Gf(r)],a=Le.relative(r,i).split(Le.sep).filter(Boolean),o=r;for(let s of a){await Pr(n),o=Le.join(o,s);try{await ee.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Gf(o);if(!ka(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Pr(n),n}async function Cb(e){let t;try{t=await ee.open(e,"r"),await t.sync()}catch(r){let i=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw r}finally{await t?.close()}}async function Pb(e,t,r={}){let i=Le.dirname(e),n=r.containedRoot?await xb(r.containedRoot,i):null;n||await ee.mkdir(i,{recursive:!0});let a=Le.join(i,`.${Le.basename(e)}.${bb()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await ee.open(a,"wx"),s=await o.stat(),n){let[l,f]=await Promise.all([ee.lstat(a),ee.realpath(a)]);if(await Pr(n),!l.isFile()||l.isSymbolicLink()||!Sa(s,l)||!ka(n[0].realPath,f))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(),!Sa(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Native atomic write temporary file was not written");if(c=await Eb(a,c,n),await r.beforeCommit?.(),n){await Pr(n);let l=await ee.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!Sb(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await ee.link(a,e),await ee.unlink(a)):await ee.rename(a,e),await Cb(i)}catch(l){if(await o?.close(),!n)await ee.rm(a,{force:!0});else try{await Pr(n),await ee.rm(a,{force:!0})}catch{}throw l}}async function Pe(e,t,r={}){await Pb(e,t,r)}async function ge(e,t,r={}){await Pe(e,JSON.stringify(t,null,2)+`
171
+ `,r)}import{existsSync as Uf,promises as Qt}from"fs";import O from"path";import Rb from"os";var Ti=".comet/config.yaml",Ab=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function Sc(e){try{return await Qt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function _b(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 Ar(e,t){let r=O.relative(e,t);return r===""||!O.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${O.sep}`)}async function Rr(e){let t=[],r=e;for(;!await Sc(r);){let n=O.dirname(r);if(n===r)break;t.push(O.basename(r)),r=n}let i=await Qt.realpath(r);return O.resolve(i,...t.reverse())}async function Ec(e){try{return(await Qt.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Ea(e){let t=O.resolve(e);try{(await Qt.stat(t)).isDirectory()||(t=O.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=O.resolve(Rb.homedir());for(;;){if(!(t===i&&r!==i)){let o=O.join(t,...Ti.split("/")),s=t===r||await _b(o);if(await Sc(o)&&s)return t}if(await Sc(O.join(t,".git")))return t;let a=O.dirname(t);if(a===t)return r;t=a}}function xa(e){return Yt(e)}async function Ib(e,t){let r=xa(t),i=O.resolve(e,...r.split("/")),n=await Qt.realpath(e),a=await Rr(i);if(!Ar(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function Ot(e,t){let r=xa(t),i=await Ib(e,r),n=O.join(i,"comet");if(await Ec(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Rr(i),Rr(n)]);if(!Ar(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=O.resolve(e),c=O.join(s,".comet","runtime","native");if(await Ec(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,f]=await Promise.all([Qt.realpath(s),Rr(c)]);if(!Ar(l,f))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:O.join(e,...Ti.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:O.join(n,"specs"),changesDir:O.join(n,"changes"),archiveDir:O.join(n,"archive"),runtimeDir:c,changesRuntimeDir:O.join(c,"changes"),locksDir:O.join(c,"locks"),transactionsDir:O.join(c,"transactions")}}function Kf(e){if(!Ab.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Ve(e,t){Kf(t);let r=O.join(e.changesRuntimeDir,t);if(!ce(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function xc(e,t){Kf(t);let r=O.join(e.changesDir,t,"runtime");if(!ce(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function Ye(e,t){let r=Ve(e,t);if(Uf(r))return r;let i=xc(e,t);return Uf(i)?i:r}function Xe(e,t){let r=O.resolve(t);if(ce(e.runtimeDir,r))return e.runtimeDir;if(ce(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function ce(e,t){return Ar(O.resolve(e),O.resolve(t))}async function z(e,t){let r=O.resolve(e),i=O.resolve(t);if(!Ar(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await Ec(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Rr(r),Rr(i)]);if(!Ar(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}function jb(e="docs",t="en"){return va(e,t)}async function we(e){let t=(await Na(e))?.config??null;return t?.native?t:null}async function Ca(e){let t=await we(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function Pa(e,t,r={}){let i=await _i(e,{allowPartialProject:!0}),n=Pi(i.document?.value??{},t),a=Tb.join(e,...Ti.split("/"));await Pe(a,Ci(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await r.beforeCommit?.(),await kc(e,i.identity)}})}async function Yf(e){let t=await Ea(e.startPath),r=await we(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${Ti} was not found`);if(r?.native.pending_root_move)throw new Error(`Native root move ${r.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let i=e.explicitArtifactRoot?xa(e.explicitArtifactRoot):void 0;if(r&&i&&i!==r.native.artifact_root)throw new Error(`Configured Native artifact root is ${r.native.artifact_root}; refusing conflicting root ${i}`);let n=r??jb(i??"docs"),a=await Ot(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}var Ia=Wr(Nr(),1);import{promises as $b}from"node:fs";var _r="comet.native.v4",ji="comet.native.local-execution.v4";var Ra=["multi-session","single-session"];function Cc(){return{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}}}var Ob=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Hb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Db=/^A[1-9][0-9]*$/u,Bb=/^[a-f0-9]{64}$/u,Lb=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"]),_a=class extends Error{constructor(r,i){super(`Native state version conflict: expected ${r}, got ${i}`);this.expectedStateVersion=r;this.actualStateVersion=i;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};function le(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ue(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function te(e,t,r){if(typeof e!="string"||!r?.empty&&e.length===0)throw new Error(`${t} must be ${r?.empty?"a string":"a non-empty string"}`);return e}function Rc(e,t){return e===null?null:te(e,t)}function Vb(e,t){let r=te(e,t);if(!Bb.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function Ir(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function q(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function Mb(e,t){return e===null?null:q(e,t,Number.MIN_SAFE_INTEGER)}function G(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Qe(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function Ta(e,t){return Qe(e,t,(r,i)=>te(r,`${t}[${i}]`))}function Zt(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Tr(e,t){let r=te(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function Ac(e,t,r=!1){let i=te(e,t);if(i.includes("\\")||i.startsWith("/")||/^[A-Za-z]:/u.test(i)||i.split("/").includes("..")||!r&&(i==="."||i.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return i}function Re(e,t){let r=le(e,t);return ue(r,new Set(["text","truncated"]),t),{text:te(r.text,`${t}.text`,{empty:!0}),truncated:Ir(r.truncated,`${t}.truncated`)}}function Fb(e,t){let r=`Native spec_changes[${t}]`,i=le(e,r);ue(i,new Set(["capability","operation","source"]),r);let n=te(i.capability,`${r}.capability`);if(!Hb.test(n))throw new Error(`${r}.capability is invalid`);let a=G(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:Ac(i.source,`${r}.source`);if(a==="remove"&&o!==null)throw new Error(`${r} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${r} ${a} requires a source`);return{capability:n,operation:a,source:o}}function qb(e){let t="Native workspace",r=le(e,t);ue(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=G(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=Rc(r.change_branch,`${t}.change_branch`),a=Rc(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:G(r.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(i==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(i==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(i!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:i,change_branch:n,target_branch:a,finish:o}}function Wb(e){let t="Native loop",r=le(e,t);ue(r,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 i=Ta(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);Zt(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:G(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:G(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:q(r.goal_cycle,`${t}.goal_cycle`,1),iteration:q(r.iteration,`${t}.iteration`),attempt:q(r.attempt,`${t}.attempt`),retry_epoch:q(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:q(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:q(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:q(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:Rc(r.next_action,`${t}.next_action`)}}function zb(e,t){let r=`Native acceptance[${t}]`,i=le(e,r);ue(i,new Set(["id","source","text","result","reason"]),r);let n=te(i.id,`${r}.id`);if(!Db.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:Ac(i.source,`${r}.source`),text:te(i.text,`${r}.text`),result:G(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:Re(i.reason,`${r}.reason`)}}function Jb(e,t){let r=`Native builder_handoff.checks[${t}]`,i=le(e,r);return ue(i,new Set(["name","result","note"]),r),{name:Re(i.name,`${r}.name`),result:G(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:Re(i.note,`${r}.note`)}}function Gb(e){let t="Native builder_handoff",r=le(e,t);ue(r,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 i=Ta(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);Zt(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:le(r.review,`${t}.review`);return n&&ue(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:te(r.candidate_id,`${t}.candidate_id`),identity_provider:te(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:te(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:q(r.iteration,`${t}.iteration`,1),summary:Re(r.summary,`${t}.summary`),addressed_acceptance_ids:i,checks:Qe(r.checks,`${t}.checks`,Jb),checks_truncated:Ir(r.checks_truncated,`${t}.checks_truncated`),known_limits:Qe(r.known_limits,`${t}.known_limits`,(a,o)=>Re(a,`${t}.known_limits[${o}]`)),known_limits_truncated:Ir(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:G(n.status,["passed"],`${t}.review.status`),summary:Re(n.summary,`${t}.review.summary`),reviewer_execution_ref:te(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:Tr(r.submitted_at,`${t}.submitted_at`)}}function Ub(e,t){let r=`Native blockers[${t}]`,i=le(e,r);ue(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=Ta(i.acceptance_ids,`${r}.acceptance_ids`);return Zt(n,`${r}.acceptance_ids`),{owner:G(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:Re(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:G(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function Kb(e,t){let r=`Native verification.checks[${t}]`,i=le(e,r);return ue(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:te(i.id,`${r}.id`),name:Re(i.name,`${r}.name`),argv_display:Qe(i.argv_display,`${r}.argv_display`,(n,a)=>Re(n,`${r}.argv_display[${a}]`)),argv_truncated:Ir(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:Ac(i.cwd_ref,`${r}.cwd_ref`,!0),status:G(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:Mb(i.exit_code,`${r}.exit_code`),duration_ms:q(i.duration_ms,`${r}.duration_ms`)}}function Yb(e){let t="Native verification",r=le(e,t);ue(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=Qe(r.checks,`${t}.checks`,Kb);Zt(i.map(a=>a.id),`${t}.checks IDs`);let n=te(r.identity_provider,`${t}.identity_provider`);return{candidate_id:te(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:te(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:q(r.iteration,`${t}.iteration`,1),attempt:q(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":G(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:G(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:Re(r.summary,`${t}.summary`),risks:Qe(r.risks,`${t}.risks`,(a,o)=>Re(a,`${t}.risks[${o}]`)),risks_truncated:Ir(r.risks_truncated,`${t}.risks_truncated`),completed_at:Tr(r.completed_at,`${t}.completed_at`)}}function Xf(e,t){let r=`Native history[${t}]`,i=le(e,r);ue(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=Ta(i.unresolved_ids,`${r}.unresolved_ids`);return Zt(n,`${r}.unresolved_ids`),{goal_cycle:q(i.goal_cycle,`${r}.goal_cycle`,1),iteration:q(i.iteration,`${r}.iteration`),attempt:q(i.attempt,`${r}.attempt`),outcome:G(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:Re(i.summary,`${r}.summary`),completed_at:Tr(i.completed_at,`${r}.completed_at`)}}function Xb(e){let t="Native history_overflow.outcome_counts",r=le(e,t),i=["pass","fail","blocked","execution-error","recovery"];return ue(r,new Set(i),t),{pass:q(r.pass,`${t}.pass`),fail:q(r.fail,`${t}.fail`),blocked:q(r.blocked,`${t}.blocked`),"execution-error":q(r["execution-error"],`${t}.execution-error`),recovery:q(r.recovery,`${t}.recovery`)}}function Qb(e){let t="Native history_overflow",r=le(e,t);ue(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=q(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:Tr(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:Tr(r.last_dropped_at,`${t}.last_dropped_at`);if(i===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(i>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=Xb(r.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==i)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:i,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function Zb(e){let t=new Set(e.acceptance.map(r=>r.id));for(let r of e.loop.previous_unresolved_ids)if(!t.has(r))throw new Error(`Native loop references unknown acceptance ID ${r}`);for(let r of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(r))throw new Error(`Native builder handoff references unknown ID ${r}`);for(let r of e.blockers)for(let i of r.acceptance_ids)if(!t.has(i))throw new Error(`Native blocker references unknown ID ${i}`);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 i=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(!i&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function ek(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 r=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(r!==null&&e.loop.stage!==r)throw new Error(`Native status ${e.status} requires loop stage ${r}`);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(i=>i.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(i=>i.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 P(e){let t=le(e,"Native portable state");if(ue(t,Lb,"Native portable state"),t.schema!==_r)throw new Error(`Native portable state schema must be ${_r}`);let r=te(t.name,"Native state name");if(!Ob.test(r))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let i=Qe(t.spec_changes,"Native spec_changes",Fb);Zt(i.map(s=>s.capability),"Native spec change capabilities");let n=Qe(t.acceptance,"Native acceptance",zb);Zt(n.map(s=>s.id),"Native acceptance IDs");let a=Qe(t.history,"Native history",Xf);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:_r,name:r,language:G(t.language,["en","zh-CN"],"Native state language"),phase:G(t.phase,["shape","build","verify","archive"],"Native state phase"),status:G(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:q(t.state_version,"Native state_version",1),brief:"brief.md",...t.children_contract_hash===void 0?{}:{children_contract_hash:Vb(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:G(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:qb(t.workspace),loop:Wb(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:Gb(t.builder_handoff),blockers:Qe(t.blockers,"Native blockers",Ub),verification:t.verification===null?null:Yb(t.verification),history:a,history_overflow:Qb(t.history_overflow),verification_result:G(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:G(t.verification_report,["verification.md"],"Native verification_report"),archived:Ir(t.archived,"Native archived"),created_at:Tr(t.created_at,"Native created_at")};return Zb(o),ek(o),o}function de(e,t){let r=P(e),i=Xf(t,r.history.length),n=[...r.history,i],a={...r.history_overflow,outcome_counts:{...r.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return P({...r,history:n,history_overflow:a})}function tk(e,t){let r=(0,Ia.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`${t} is invalid YAML: ${r.errors[0].message}`);return r.toJS({mapAsMap:!1})}async function Me(e){let t=await $b.readFile(e,"utf8");return P(tk(t,"Native portable state"))}async function ja(e,t,r={}){let i=P(t);await Pe(e,(0,Ia.stringify)(i),r)}var Aa=new Map;async function rk(e,t){let r=Aa.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);Aa.set(e,a),await r;try{return await t()}finally{i(),Aa.get(e)===a&&Aa.delete(e)}}async function $i(e){return rk(e.file,async()=>{let t=q(e.expectedStateVersion,"Native expected state version",1),r=P(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await Me(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new _a(t,i.state_version);return await ja(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Me(e.file);if(n.state_version!==t)throw new _a(t,n.state_version)}}),r})}import rr from"node:path";import{randomUUID as KS}from"node:crypto";import{promises as Xp}from"node:fs";import{promises as FS}from"fs";import qS from"path";import{AsyncLocalStorage as ik}from"async_hooks";import{randomUUID as ep}from"crypto";import{promises as Ae}from"fs";import tp from"os";import re from"path";var Qf=16*1024,rp=".coordinator",nk=5e3,Zf=new ik,$a=new Map;function ak(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function ok(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let r=e;if(typeof r.id!="string"||r.id.length===0||typeof r.pid!="number"||!Number.isSafeInteger(r.pid)||r.pid<1||typeof r.hostname!="string"||r.hostname.length===0||typeof r.createdAt!="string"||r.createdAt.length===0||typeof r.operation!="string"||r.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return r}function ip(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 Oa(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Ke(r,i)?M(r,i):M(r,i)&&e.size===t.size}function _c(e,t){return Oa(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function Ze(e){let t,r;try{let i=await xr(e,Qf,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof Be?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${Qf} bytes: ${e}`,{cause:i}):i.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:i}):new Error(`Native lock changed while reading: ${e}`,{cause:i}):i}return{file:e,owner:ok(JSON.parse(t.toString("utf8")),e),identity:ip(r)}}async function sk(e){return(await Ze(e))?.owner??null}function np(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==tp.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=pk(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function ck(e,t){try{await Ae.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await Ae.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function Ic(e,t){let r=await Ze(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!_c(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await Ae.mkdir(t,{recursive:!0});let i=re.join(t,`${re.basename(e.file)}.${e.owner.id}.${ep()}.removed`);try{await Ae.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await Ze(i);if(!n||n.owner.id!==e.owner.id||!Oa(n.identity,e.identity))throw await ck(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await Ae.rm(i,{force:!0}),"removed"}function ap(e){return{id:ep(),pid:process.pid,hostname:tp.hostname(),createdAt:new Date().toISOString(),operation:e}}async function op(e,t){let r;try{r=await Ae.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await sk(e);throw new Error(`Native lock is already held: ${e}${o?` by pid ${o.pid} for ${o.operation}`:""}`,{cause:a})}throw a}let i;try{await r.writeFile(JSON.stringify(t,null,2)+`
172
+ `,"utf8"),await r.sync(),i=ip(await r.stat({bigint:!0}))}finally{await r.close()}let n=await Ze(e);if(!i||!n||n.owner.id!==t.id||!Oa(n.identity,i))throw new Error(`Native lock changed after write: ${e}`);return n.identity}async function lk(e,t){let r=await z(e.runtimeDir,e.locksDir);await Ae.mkdir(r,{recursive:!0});let i=await z(e.runtimeDir,re.join(r,rp));await Ae.mkdir(i,{recursive:!0});let n=ap(t),a=re.join(i,`.${n.id}.tmp`),o=re.join(i,`${n.id}.claim`);try{let s=await op(a,n);await Ae.rename(a,o);let c=await Ze(o);if(!c||!Oa(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:r,owner:n,identity:c.identity}}finally{await Ae.rm(a,{force:!0})}}async function uk(e){let t=re.dirname(e.file),r=!1,i=re.basename(e.file);for(let n of await Ae.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=re.join(t,n.name);if(re.resolve(a)!==re.resolve(e.file))try{let o=await Ze(a),s=np(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Ic(o,t);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function sp(e){let t=await Ze(e.file);if(t){if(t.owner.id!==e.owner.id||!_c(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await Ic(t,re.dirname(e.file))}}async function dk(e,t){let r=Date.now()+nk;for(;;){let i=await lk(e,t);if(!await uk(i))return i;if(await sp(i),Date.now()>=r)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function fk(e){let t=$a.get(e)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=t.then(()=>i);return $a.set(e,n),await t,()=>{r(),$a.get(e)===n&&$a.delete(e)}}async function Tc(e,t,r){let i=re.resolve(e.locksDir),n=Zf.getStore();if(n?.has(i))return r();let a=await fk(i);try{let o=await dk(e,t),s=new Map(n??[]);return s.set(i,o),await Zf.run(s,async()=>{try{return await r()}finally{await sp(o)}})}finally{a()}}async function cp(e,t,r){let i=[...new Map(e.map(a=>[re.resolve(a.locksDir),a])).values()].sort((a,o)=>re.resolve(a.locksDir).localeCompare(re.resolve(o.locksDir))),n=async a=>{let o=i[a];return o?Tc(o,t,()=>n(a+1)):r()};return n(0)}async function Ha(e,t,r){return Tc(e,`acquire ${t}`,async()=>{let i=await z(e.runtimeDir,e.locksDir);await Ae.mkdir(i,{recursive:!0});let n=await z(e.runtimeDir,re.join(i,ak(t))),a=ap(r),o=await op(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:i,owner:a,identity:o}})}async function Da(e){await Ze(e.file)&&await Tc({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${re.basename(e.file)}`,async()=>{let t=await Ze(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!_c(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let r=re.join(e.locksDir,rp);await Ic(t,r)})}function pk(e){try{return process.kill(e,0),!0}catch(t){let r=t.code;return r==="ESRCH"?!1:r==="EPERM"?!0:null}}async function lp(e){return np(await Ze(e))}import Uc from"node:path";import sS from"node:path";var Fc=Wr(Nr(),1);import Or from"path";var jc={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:"验证预期"}},dp={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:"结论"}},fp={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:"结论"}},pp=new Map,up=new Map;for(let e of Object.keys(jc)){for(let[t,r]of Object.entries(jc[e]))pp.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(dp[e]))up.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(fp[e]))up.set(r.toLocaleLowerCase("en-US"),t)}function hk(e,t){return jc[e][t]}function $c(e,t){return dp[e][t]??fp[e][t]}function Oc(e){return pp.get(e.trim().toLocaleLowerCase("en-US"))??null}function Ba(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(r=>`# ${hk(e,r)}
173
173
  `).join(`
174
- `)}function Be(e,t,r){return e==="zh-CN"?r:t}import{createHash as Fb}from"node:crypto";import{constants as Ca,promises as Le}from"node:fs";import Ve from"node:path";function Aa(e,t){let r=Ve.relative(e,t);return r===""||!Ve.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ve.sep}`)}function qb(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function Wb(e,t){return V({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function zb(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Ra(e,t){return V({...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 Rc(e,t){let r=await Le.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await Le.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function Jb(e,t,r){let i=Ve.resolve(e),n=Ve.resolve(t);if(!Aa(i,n))throw new Error(`${r} is outside its managed root`);let a=[await Rc(i,r)],o=i;for(let s of Ve.relative(i,n).split(Ve.sep).filter(Boolean)){await Kt(a,r),o=Ve.join(o,s);let c=await Rc(o,r);if(!Aa(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await Kt(a,r),a}async function Kt(e,t){for(let r of e){let i=await Le.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!Wb(r,i)||await Le.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function Gb(e,t,r){let i=[],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(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function xr(e){let t=qb(e.maxBytes),r=Ve.resolve(e.file),i=await Jb(e.root,Ve.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(f=>Rc(Ve.resolve(f),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Kt(i,e.label);let a=await Le.lstat(r);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=zb(a),s=await Le.realpath(r);if(!Aa(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(f=>Aa(f.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Ca.O_RDONLY:Ca.O_RDONLY|Ca.O_NOFOLLOW|Ca.O_NONBLOCK,l=await Le.open(r,c);try{let f=await l.stat();await e.hooks?.afterOpen?.();let[d,u]=await Promise.all([Le.lstat(r),Le.realpath(r)]);if(await Kt(i,e.label),await Kt(n,e.label),!f.isFile()||!d.isFile()||d.isSymbolicLink()||u!==s||!Ra(o,f)||!Ra(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let h=await Gb(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,m,p]=await Promise.all([l.stat(),Le.lstat(r),Le.realpath(r)]);if(await Kt(i,e.label),await Kt(n,e.label),!m.isFile()||m.isSymbolicLink()||p!==s||!Ra(o,v)||!Ra(o,m))throw new Error(`${e.label} changed while reading`);return{bytes:h,hash:Fb("sha256").update(h).digest("hex"),size:h.length}}finally{await l.close()}}import{createHash as Ub}from"crypto";function Re(e){return Ub("sha256").update(e).digest("hex")}var uA={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024};var dA=8*1024*1024;var fA=64*1024,hA=64*1024;var pA={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},mA={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};var vA=(1n<<256n)-1n;var tk=Hr(hr(),1);var TA=4*1024*1024;var rk=null;function ik(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function eh(e,t){return(...r)=>{let i=rk;if(i===null)return t(...r);let n=ik(`async:${e}`,r),a=i.entries.get(n);if(a)return a.value;let o=t(...r).catch(s=>{throw i.entries.delete(n),s});return i.entries.set(n,{value:o}),o}}var DA=eh("hookWritePolicy",async e=>(await uc(e))?.hook??{allow_paths:[]});var __=256*1024;var q_={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};import Pr from"node:path";var Ri=/^[a-f0-9]{64}$/u,rh=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,ak=16*1024,nI=process.platform;function ok(e,t){let r=Pr.relative(e,t);return Pr.isAbsolute(r)||r===".."||r.startsWith(`..${Pr.sep}`)?null:r.replaceAll("\\","/")||"."}function ih(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function nh(e,t){if(e.length===0||ih(e)||e.includes("\\")||Pr.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let r=Pr.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function sk(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 Ac(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||ih(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function ck(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Ac(e.changeBranch,"Native workspace change branch"),Ac(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 lk(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,r=new Set(["provider","baseCommit","targetBranch","targetCommit"]),i=Object.keys(t).filter(n=>!r.has(n));if(i.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${i.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!rh.test(t.baseCommit)||typeof t.targetCommit!="string"||!rh.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");Ac(t.targetBranch,"Native workspace Git target branch")}function uk(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,r=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),i=Object.keys(t).filter(o=>!r.has(o));if(i.length>0)throw new Error(`Native workspace identity has unknown field(s): ${i.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"||!Ri.test(String(t.projectRootId))||!Ri.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");sk(t.capturedAt),nh(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&&!Ri.test(String(t.projectRootPathId))||a&&!Ri.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Ri.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&lk(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(ck(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 dk(e,t){return Pr.join(Je(e,t),"workspace.json")}function fk(e,t){let r=dk(e,t),i=Ge(e,r),n=ok(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:nh(n,"Native workspace file ref")}}async function hk(e,t){try{let r=fk(e,t),i=await J({root:r.root,ref:r.ref,maxBytes:ak});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Ai(e,t){let r=await hk(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(uk(r),r)}var ct="comet.native.v3",Ke="comet.native.v2",Ye="comet.native.v1";var ah=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],mk=new Set(ah),oh=new Set([...ah,"minimum_runtime_version","revision"]),vk=new Set([...oh,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),gk=new Set(["capability","operation","source","base_hash"]),wk=new Set(["shape","build","verify","archive"]),yk=new Set(["implicit","confirmed"]),Nk=new Set(["pending","pass","fail"]),Yt="comet-state.yaml",Ic=/^[a-f0-9]{64}$/u,sh=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,bk=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Tc=class extends Error{constructor(r,i){super(`Native change ${r} uses ${i}; run comet native doctor ${r} --repair before mutating it`);this.change=r;this.schema=i;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},Rr=class extends Error{constructor(r,i){super(r!==ct||i===null?`Unsupported Native change schema ${r} for runtime protocol ${3}`:`Native change ${r} requires runtime protocol ${i}; current protocol is ${3}`);this.schema=r;this.minimumRuntimeVersion=i;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},_a=class extends Error{constructor(r,i,n){super(`Native change ${r} revision conflict: expected ${i}, actual ${n}`);this.change=r;this.expectedRevision=i;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},_i=class extends Error{constructor(r,i){super(`Native working directory already contains active change${i.length===1?"":"s"} ${i.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=r;this.activeChanges=i;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},Ia=class extends Error{constructor(r,i,n,a,o,s=null,c=null){super(`Native change ${r} baseline is incomplete (${i} omitted entr${i===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=r;this.omittedCount=i;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"},II=Pa("en");function Ti(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function ch(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Oc(e){if(!sh.test(e))throw new Error(`Invalid Native change name: ${e}`)}function kk(e){if(!sh.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function lh(e,t){if(e.length===0||Cr.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function Sk(e,t){let r=Ti(e,`spec_changes[${t}]`);if(ch(r,gk,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(kk(r.capability),r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`Invalid spec operation for ${r.capability}`);let i=r.source,n=r.base_hash;if(i!==void 0&&typeof i!="string")throw new Error(`Spec source for ${r.capability} must be a string`);if(typeof i=="string"&&lh(i,`Spec source for ${r.capability}`),r.operation==="create"){if(!i)throw new Error(`Create spec ${r.capability} requires source`);if(n!==null)throw new Error(`Create spec ${r.capability} requires null base_hash`)}else if(r.operation==="replace"){if(!i)throw new Error(`Replace spec ${r.capability} requires source`);if(typeof n!="string"||!Ic.test(n))throw new Error(`Replace spec ${r.capability} requires a SHA-256 base_hash`)}else{if(i!==void 0)throw new Error(`Remove spec ${r.capability} forbids source`);if(typeof n!="string"||!Ic.test(n))throw new Error(`Remove spec ${r.capability} requires a SHA-256 base_hash`)}return{capability:r.capability,operation:r.operation,...typeof i=="string"?{source:i}:{},base_hash:n}}function Ek(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 Hc(e,t){if(ch(e,t,Yt),typeof e.name!="string")throw new Error("Native change name is required");if(Oc(e.name),e.language!=="en"&&e.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof e.phase!="string"||!wk.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&&!yk.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 r=e.spec_changes.map(Sk),i=r.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(i.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(i)].join(", ")}`);if(typeof e.verification_result!="string"||!Nk.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"&&lh(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!Ek(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:r,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function ji(e){let t=Ti(e,Yt);if(t.schema!==Ye)throw new Error(`Expected ${Ye}`);return{schema:Ye,...Hc(t,mk)}}function Ii(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function _c(e,t,r){if(e===null)return null;let i=typeof e=="string"?bk.exec(e):null;if(!i||i[1]!==r)throw new Error(`${t} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return e}function xk(e){if(e==null)return null;if(typeof e!="string"||!Ic.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function Pk(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 $i(e){let t=Ti(e,Yt);if(t.schema!==Ke)throw new Error(`Expected ${Ke}`);if(Ii(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Ke} minimum_runtime_version must be 2`);return{schema:Ke,minimum_runtime_version:2,revision:Ii(t.revision,"Native v2 revision"),...Hc(t,oh)}}function Oi(e){let t=Ti(e,Yt);if(t.schema!==ct){if(t.schema===Ye||t.schema===Ke){let o=t.schema===Ye?ji(t):$i(t);throw new Tc(o.name,o.schema)}throw new Rr(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=Ii(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new Rr(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=Ii(t.revision,"Native revision"),n=Hc(t,vk),a=xk(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:ct,minimum_runtime_version:3,revision:i,verification_protocol:Pk(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:_c(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:_c(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:_c(t.partial_allowance,"Native partial_allowance","allowances")}}function Ck(e){let t=Ti(e,Yt);if(t.schema===Ye){let n=ji(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${ct}`}}if(t.schema===Ke){let n=$i(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${ct}`}}if(t.schema!==ct){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 Rr(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=Ii(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new Rr(t.schema,r).message};let i=Oi(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}function Xe(e,t){Oc(t);let r=Cr.join(e.changesDir,t);if(!se(e.changesDir,r))throw new Error("Native change path escaped");return r}async function Rk(e,t=Cr.dirname(e)){let r=Cr.relative(t,e).split(Cr.sep).join("/"),i=await J({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,$c.parseDocument)(i.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 uh(e,t){let r=Cr.join(Xe(e,t),Yt);await q(e.nativeRoot,r);let i=Ck(await Rk(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}import vh from"node:path";var Ak="comet.native.acceptance.v1";var OI=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),ja=Object.freeze({maxCriteria:1024});function hh(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 dh(e,t){let r=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!r)return t;let i=r[1][0];return t===null?{marker:i,length:r[1].length}:i===t.marker&&r[1].length>=t.length&&r[2].trim().length===0?null:t}function fh(e){return e.includes("-->")||e.includes("--!>")}function*Ta(e){let t=null,r=!1,i=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
174
+ `)}function Fe(e,t,r){return e==="zh-CN"?r:t}import{createHash as mk}from"node:crypto";import{constants as La,promises as qe}from"node:fs";import We from"node:path";function Ma(e,t){let r=We.relative(e,t);return r===""||!We.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${We.sep}`)}function vk(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function gk(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function wk(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Va(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 Hc(e,t){let r=await qe.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await qe.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function yk(e,t,r){let i=We.resolve(e),n=We.resolve(t);if(!Ma(i,n))throw new Error(`${r} is outside its managed root`);let a=[await Hc(i,r)],o=i;for(let s of We.relative(i,n).split(We.sep).filter(Boolean)){await er(a,r),o=We.join(o,s);let c=await Hc(o,r);if(!Ma(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await er(a,r),a}async function er(e,t){for(let r of e){let i=await qe.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!gk(r,i)||await qe.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function Nk(e,t,r){let i=[],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(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function jr(e){let t=vk(e.maxBytes),r=We.resolve(e.file),i=await yk(e.root,We.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(f=>Hc(We.resolve(f),e.label)));await e.hooks?.afterParentChainCaptured?.(),await er(i,e.label);let a=await qe.lstat(r);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=wk(a),s=await qe.realpath(r);if(!Ma(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(f=>Ma(f.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?La.O_RDONLY:La.O_RDONLY|La.O_NOFOLLOW|La.O_NONBLOCK,l=await qe.open(r,c);try{let f=await l.stat();await e.hooks?.afterOpen?.();let[u,d]=await Promise.all([qe.lstat(r),qe.realpath(r)]);if(await er(i,e.label),await er(n,e.label),!f.isFile()||!u.isFile()||u.isSymbolicLink()||d!==s||!Va(o,f)||!Va(o,u))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await Nk(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,m,h]=await Promise.all([l.stat(),qe.lstat(r),qe.realpath(r)]);if(await er(i,e.label),await er(n,e.label),!m.isFile()||m.isSymbolicLink()||h!==s||!Va(o,v)||!Va(o,m))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:mk("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}import{createHash as bk}from"crypto";function _e(e){return bk("sha256").update(e).digest("hex")}var KA={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024};var YA=8*1024*1024;var XA=64*1024,QA=64*1024;var ZA={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},e_={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};var t_=(1n<<256n)-1n;var Rk=Wr(Nr(),1);var g_=4*1024*1024;var Ak=null;function _k(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function hp(e,t){return(...r)=>{let i=Ak;if(i===null)return t(...r);let n=_k(`async:${e}`,r),a=i.entries.get(n);if(a)return a.value;let o=t(...r).catch(s=>{throw i.entries.delete(n),s});return i.entries.set(n,{value:o}),o}}var k_=hp("hookWritePolicy",async e=>(await bc(e))?.hook??{allow_paths:[]});var gI=256*1024;var _I={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};import $r from"node:path";var Oi=/^[a-f0-9]{64}$/u,vp=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,Tk=16*1024,zI=process.platform;function jk(e,t){let r=$r.relative(e,t);return $r.isAbsolute(r)||r===".."||r.startsWith(`..${$r.sep}`)?null:r.replaceAll("\\","/")||"."}function gp(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function wp(e,t){if(e.length===0||gp(e)||e.includes("\\")||$r.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let r=$r.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function $k(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 Dc(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||gp(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function Ok(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Dc(e.changeBranch,"Native workspace change branch"),Dc(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 Hk(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,r=new Set(["provider","baseCommit","targetBranch","targetCommit"]),i=Object.keys(t).filter(n=>!r.has(n));if(i.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${i.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!vp.test(t.baseCommit)||typeof t.targetCommit!="string"||!vp.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");Dc(t.targetBranch,"Native workspace Git target branch")}function Dk(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,r=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),i=Object.keys(t).filter(o=>!r.has(o));if(i.length>0)throw new Error(`Native workspace identity has unknown field(s): ${i.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"||!Oi.test(String(t.projectRootId))||!Oi.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");$k(t.capturedAt),wp(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&&!Oi.test(String(t.projectRootPathId))||a&&!Oi.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Oi.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&Hk(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(Ok(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 Bk(e,t){return $r.join(Ye(e,t),"workspace.json")}function Lk(e,t){let r=Bk(e,t),i=Xe(e,r),n=jk(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:wp(n,"Native workspace file ref")}}async function Vk(e,t){try{let r=Lk(e,t),i=await Y({root:r.root,ref:r.ref,maxBytes:Tk});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Hi(e,t){let r=await Vk(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(Dk(r),r)}var ft="comet.native.v3",et="comet.native.v2",tt="comet.native.v1";var yp=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],Fk=new Set(yp),Np=new Set([...yp,"minimum_runtime_version","revision"]),qk=new Set([...Np,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),Wk=new Set(["capability","operation","source","base_hash"]),zk=new Set(["shape","build","verify","archive"]),Jk=new Set(["implicit","confirmed"]),Gk=new Set(["pending","pass","fail"]),tr="comet-state.yaml",Lc=/^[a-f0-9]{64}$/u,bp=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Uk=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Vc=class extends Error{constructor(r,i){super(`Native change ${r} uses ${i}; run comet native doctor ${r} --repair before mutating it`);this.change=r;this.schema=i;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},Hr=class extends Error{constructor(r,i){super(r!==ft||i===null?`Unsupported Native change schema ${r} for runtime protocol ${3}`:`Native change ${r} requires runtime protocol ${i}; current protocol is ${3}`);this.schema=r;this.minimumRuntimeVersion=i;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},Fa=class extends Error{constructor(r,i,n){super(`Native change ${r} revision conflict: expected ${i}, actual ${n}`);this.change=r;this.expectedRevision=i;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},Di=class extends Error{constructor(r,i){super(`Native working directory already contains active change${i.length===1?"":"s"} ${i.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=r;this.activeChanges=i;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},qa=class extends Error{constructor(r,i,n,a,o,s=null,c=null){super(`Native change ${r} baseline is incomplete (${i} omitted entr${i===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=r;this.omittedCount=i;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"},wT=Ba("en");function Li(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function kp(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function qc(e){if(!bp.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Kk(e){if(!bp.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Sp(e,t){if(e.length===0||Or.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function Yk(e,t){let r=Li(e,`spec_changes[${t}]`);if(kp(r,Wk,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(Kk(r.capability),r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`Invalid spec operation for ${r.capability}`);let i=r.source,n=r.base_hash;if(i!==void 0&&typeof i!="string")throw new Error(`Spec source for ${r.capability} must be a string`);if(typeof i=="string"&&Sp(i,`Spec source for ${r.capability}`),r.operation==="create"){if(!i)throw new Error(`Create spec ${r.capability} requires source`);if(n!==null)throw new Error(`Create spec ${r.capability} requires null base_hash`)}else if(r.operation==="replace"){if(!i)throw new Error(`Replace spec ${r.capability} requires source`);if(typeof n!="string"||!Lc.test(n))throw new Error(`Replace spec ${r.capability} requires a SHA-256 base_hash`)}else{if(i!==void 0)throw new Error(`Remove spec ${r.capability} forbids source`);if(typeof n!="string"||!Lc.test(n))throw new Error(`Remove spec ${r.capability} requires a SHA-256 base_hash`)}return{capability:r.capability,operation:r.operation,...typeof i=="string"?{source:i}:{},base_hash:n}}function Xk(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 Wc(e,t){if(kp(e,t,tr),typeof e.name!="string")throw new Error("Native change name is required");if(qc(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"||!zk.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&&!Jk.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 r=e.spec_changes.map(Yk),i=r.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(i.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(i)].join(", ")}`);if(typeof e.verification_result!="string"||!Gk.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"&&Sp(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!Xk(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:r,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function Vi(e){let t=Li(e,tr);if(t.schema!==tt)throw new Error(`Expected ${tt}`);return{schema:tt,...Wc(t,Fk)}}function Bi(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Bc(e,t,r){if(e===null)return null;let i=typeof e=="string"?Uk.exec(e):null;if(!i||i[1]!==r)throw new Error(`${t} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return e}function Qk(e){if(e==null)return null;if(typeof e!="string"||!Lc.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function Zk(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 Mi(e){let t=Li(e,tr);if(t.schema!==et)throw new Error(`Expected ${et}`);if(Bi(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${et} minimum_runtime_version must be 2`);return{schema:et,minimum_runtime_version:2,revision:Bi(t.revision,"Native v2 revision"),...Wc(t,Np)}}function Fi(e){let t=Li(e,tr);if(t.schema!==ft){if(t.schema===tt||t.schema===et){let o=t.schema===tt?Vi(t):Mi(t);throw new Vc(o.name,o.schema)}throw new Hr(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=Bi(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new Hr(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=Bi(t.revision,"Native revision"),n=Wc(t,qk),a=Qk(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:ft,minimum_runtime_version:3,revision:i,verification_protocol:Zk(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Bc(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Bc(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Bc(t.partial_allowance,"Native partial_allowance","allowances")}}function eS(e){let t=Li(e,tr);if(t.schema===tt){let n=Vi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${ft}`}}if(t.schema===et){let n=Mi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${ft}`}}if(t.schema!==ft){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 Hr(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=Bi(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new Hr(t.schema,r).message};let i=Fi(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}function rt(e,t){qc(t);let r=Or.join(e.changesDir,t);if(!ce(e.changesDir,r))throw new Error("Native change path escaped");return r}async function tS(e,t=Or.dirname(e)){let r=Or.relative(t,e).split(Or.sep).join("/"),i=await Y({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,Fc.parseDocument)(i.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 Ep(e,t){let r=Or.join(rt(e,t),tr);await z(e.nativeRoot,r);let i=eS(await tS(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}import _p from"node:path";var rS="comet.native.acceptance.v1";var kT=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),za=Object.freeze({maxCriteria:1024});function Pp(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 xp(e,t){let r=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!r)return t;let i=r[1][0];return t===null?{marker:i,length:r[1].length}:i===t.marker&&r[1].length>=t.length&&r[2].trim().length===0?null:t}function Cp(e){return e.includes("-->")||e.includes("--!>")}function*Wa(e){let t=null,r=!1,i=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
175
175
  `),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
176
- `,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!r&&i===null,index:s},s+=1,t!==null)t=dh(l,t);else if(r)fh(l)&&(r=!1);else if(i!==null)new RegExp(`</${i}\\s*>`,"iu").test(l)&&(i=null);else{let d=dh(l,null);if(d!==null)t=d;else{let u=l.trimStart();if(u.startsWith("<!--")&&!fh(u))r=!0;else{let h=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(u);h&&n.has(h[1].toLowerCase())&&!u.startsWith("</")&&!u.endsWith("/>")&&!new RegExp(`</${h[1]}\\s*>`,"iu").test(u)&&(i=h[1])}}}if(c===-1)break;o=c+1}}function Hi(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function ph(e,t,r,i=[],n="content-hash"){let a=Hi(r),o=t.replaceAll("\\","/").trim(),s=i.map(Hi);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-${pe(Ak,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function mh(e,t,r="content-hash"){let i=new Set;for(let n of e){let a=r==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(i.has(a))throw new Error(`${t} contains duplicate acceptance criteria`);i.add(a)}return e}function _k(e){let t=null,r=null,i=0,n=0;for(let{line:a,body:o,index:s}of Ta(e)){n=s+1;let c=o?hh(a):null;c?.level===1&&(Cc(c.text)==="acceptanceExamples"?(i+=1,i===1&&(t=s+1)):t!==null&&r===null&&(r=s))}if(i===0||t===null)return null;if(i!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:r??n}}function Dc(e,t="brief.md",r=ja.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let n=_k(e);if(n===null)return[];let a=null;for(let{line:l,body:f,index:d}of Ta(e)){if(d<n.start||d>=n.end)continue;let u=f?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(u===null)continue;let h=u[1].length;a=a===null?h:Math.min(a,h)}let o=[],s=null,c=()=>{if(s!==null){if(o.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);o.push(s)}};for(let{line:l,body:f,index:d}of Ta(e)){if(d<n.start||d>=n.end)continue;let u=f?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;u&&u[1].length===a?(c(),s=[u[2]]):s!==null&&s.push(l)}return c(),mh(o.map(l=>ph("brief-example",t,l.join(`
177
- `),[],i)),"Brief",i)}function Bc(e,t="spec.md",r=ja.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=()=>{if(o!==null){if(n.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);n.push(ph("spec-scenario",t,[o.title,...o.body].join(`
178
- `),o.context,i)),o=null}};for(let{line:c,body:l}of Ta(e)){let f=l?hh(c):null,d=f?/^Scenario\s*:\s*(.*)$/iu.exec(f.text):null;if(d){for(s();a.at(-1)&&a.at(-1).level>=f.level;)a.pop();let u=Hi(d[1]);if(u.length===0)throw new Error("Scenario title must not be empty");o={level:f.level,title:u,body:[],context:a.map(h=>h.text)}}else if(f){for(o!==null&&f.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f)}else o!==null&&l&&o.body.push(c)}return s(),mh(n,"Specification",i)}var Ik=/^A[1-9]\d*$/u;function gh(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||vh.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||vh.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function Tk(e,t){return e.localeCompare(t,"en")}function $a(e){let t=gh(e.briefSource??"brief.md","Native brief source"),r=[...e.specs??[]].sort((a,o)=>Tk(a.capability,o.capability));if(new Set(r.map(a=>a.capability)).size!==r.length)throw new Error("Native acceptance sources contain duplicate capabilities");let i=Dc(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of r){let o=gh(a.source,`Native spec source for ${a.capability}`);i.push(...Bc(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})))}let n=new Set;for(let a of i){a.text=Hi(a.text);let o=`${a.source}\0${a.text}`;if(n.has(o))throw new Error(`Native acceptance contains a duplicate criterion: ${a.text}`);n.add(o)}if(i.length===0)throw new Error("Native change must define at least one acceptance criterion");return i.map((a,o)=>({id:`A${o+1}`,source:a.source,text:a.text}))}function wh(e){let t=e.map(({id:r})=>r);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let r=0;r<t.length;r+=1)if(!Ik.test(t[r])||t[r]!==`A${r+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function yh(e,t){return e.length===t.length&&e.every((r,i)=>r.source===t[i]?.source&&r.text===t[i]?.text)}function jk(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function O(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(jk(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let r="",i=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(i+a>t)break;r+=n,i+=a}return{text:r,truncated:!0}}var Oa="comet.native.portable-migration.v1",Ok=new Set(["schema","id","change","fromSchema","status","createdAt"]),Hk=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Dk=/^[a-z0-9][a-z0-9-]{7,127}$/u,Bk=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),Lk=new Set([Ye,Ke,ct]);function Vk(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Mk(e,t){let r=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(r.valueOf()))throw new Error(`${t} must be a valid timestamp`);return r.toISOString()}function Fk(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function qk(e){return e.schema===Ye?ji(e):e.schema===Ke?$i(e):Oi(e)}function Wk(e){return $k.posix.normalize(e.replaceAll("\\","/"))}function zk(e){return e.spec_changes.map(t=>t.operation==="remove"?{capability:t.capability,operation:"remove",source:null}:{capability:t.capability,operation:t.operation==="replace"?"modify":"create",source:Wk(t.source)})}function Jk(e){return e==="shape"?"shape":"build"}function Gk(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function Uk(e,t,r){return e==="zh-CN"?`从旧版 ${t} ${r} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${r} state; prior Loop, verification results, and execution records were not inherited.`}function Nh(e){let t=qk(e.state);wh(e.acceptance);let r=Jk(t.phase),i=r==="shape"?0:1,n=Mk(e.migratedAt??`${t.created_at}T00:00:00.000Z`,"Native portable migration time"),a=e.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return C({schema:kr,name:t.name,language:t.language,phase:r,status:"active",state_version:1,brief:"brief.md",spec_changes:zk(t),workspace:e.workspace,loop:{stage:r==="shape"?"shape":"building",goal_cycle:1,iteration:i,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:Gk(t.language,r)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:i,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:O(Uk(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:gc(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function Lc(e){let t=Vk(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!Ok.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==Oa)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!Dk.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!Hk.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!Lk.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!Bk.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Oa,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:Fk(t.createdAt,"Native portable migration transaction createdAt")}}function bh(e){switch(Lc(e).status){case"prepared":return{action:"commit-portable-yaml",fromStatus:"prepared",nextStatus:"yaml-committed"};case"yaml-committed":return{action:"cleanup-legacy-runtime",fromStatus:"yaml-committed",nextStatus:"legacy-cleanup"};case"legacy-cleanup":return{action:"commit-transaction",fromStatus:"legacy-cleanup",nextStatus:"committed"};case"committed":return{action:"done",fromStatus:"committed",nextStatus:null}}}var kh="comet.native.archive-transaction.v4",Sh="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",Kk=new RegExp(`^portable-archive-(${Sh})\\.json$`,"u"),Yk=new RegExp(`^portable-migration-(${Sh})\\.json$`,"u"),Xk=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Qk=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Zk=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),eS=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),tS=new Set(["capability","operation","source","content"]),Eh=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function xh(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ph(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`);if(Object.keys(e).length!==t.size)throw new Error(`${r} fields are invalid`)}function rS(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=xh(e,r);if(Ph(i,tS,r),typeof i.capability!="string"||!Eh.test(i.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(i.operation)))throw new Error(`${r}.operation is invalid`);let n=i.operation;if(n==="remove"){if(i.source!==null||i.content!==null)throw new Error(`${r} remove requires source and content null`);return{capability:i.capability,operation:n,source:null,content:null}}if(typeof i.source!="string"||i.source.length===0||i.source.includes("\\")||i.source.startsWith("/")||/^[A-Za-z]:/u.test(i.source)||i.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${r}.${n} source is invalid`);if(typeof i.content!="string")throw new Error(`${r}.${n} content is invalid`);return{capability:i.capability,operation:n,source:i.source,content:i.content}}function iS(e){let t=xh(e,"Native portable Archive transaction");if(Ph(t,eS,"Native portable Archive transaction"),t.schema!==kh)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!Xk.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Eh.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"||!Qk.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"||!Zk.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 r=t.spec_changes.map(rS);if(new Set(r.map(({capability:n})=>n)).size!==r.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)>r.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 i=new Date(t.created_at);if(Number.isNaN(i.valueOf())||i.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:kh,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:r,created_at:t.created_at}}function Ha(e){let t=Kk.exec(e);if(t)return{kind:"archive",change:t[1]};let r=Yk.exec(e);return r?{kind:"migration",change:r[1]}:null}function Da(e,t){let r=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,i=Ha(r);if(!i||i.kind!==t.kind||i.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return Vc.join(e.transactionsDir,r)}async function Mc(e,t){let r=Ha(t);if(!r)return null;let i=await J({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=Vc.join(e.transactionsDir,t);if(r.kind==="archive"){let s=iS(n);if(s.change!==r.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:r.change,file:a,journal:s}}let o=Lc(n);if(o.change!==r.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:r.change,file:a,journal:o}}async function Ch(e,t){let r=Da(e,t);try{return await Mc(e,Vc.basename(r))}catch(i){if(i.code==="ENOENT")return null;throw i}}function Rh(e){return e.kind==="archive"||e.journal.status!=="committed"}import lt from"path";import{TextDecoder as aS}from"util";var oS=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),sS=new Set(["id","type","source","target","staged","backup"]),cS=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),lS=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var Ih=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var uS=256*1024,oT=1024*1024,sT=16*1024;var cT=64*1024*1024;var dS=new aS("utf-8",{fatal:!0});function La(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Va(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Th(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Fc(e,t){if(typeof e!="string"||e.length===0||lt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Ba(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function Ah(e,t){if(Fc(e,t),e.includes("\\")||e!==lt.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function fS(e,t){let r=La(e,`transaction operations[${t}]`);if(Va(r,sS,`transaction operations[${t}]`),typeof r.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.id))throw new Error(`transaction operations[${t}].id is invalid`);if(r.type!=="write"&&r.type!=="remove"&&r.type!=="move")throw new Error(`transaction operation ${r.id} has an invalid type`);Fc(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&Fc(r[i],`transaction operation ${r.id} ${i}`);if(r.type==="write"){if(r.staged===void 0||r.source!==void 0)throw new Error(`write operation ${r.id} requires staged and forbids source`)}else if(r.type==="remove"){if(r.source!==void 0||r.staged!==void 0)throw new Error(`remove operation ${r.id} forbids source and staged`)}else if(r.source===void 0||r.staged!==void 0||r.backup!==void 0)throw new Error(`move operation ${r.id} requires source and forbids staged and backup`);return r}function jh(e){let t=La(e,"Native Archive transaction journal");if(Va(t,cS,"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"||!Ih.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(!Th(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Ba(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 r=t.operations.map((s,c)=>{let l=La(s,`Archive transaction operations[${c}]`);if(Va(l,lS,`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`);Ah(l.target,`Archive transaction operation ${l.id} target`);for(let f of["source","staged","backup"])l[f]!==void 0&&Ah(l[f],`Archive transaction operation ${l.id} ${f}`);if(l.expectedTargetHash!==null&&Ba(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(Ba(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`);Ba(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),i=r.map(s=>s.id);if(new Set(i).size!==i.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=r.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)||r.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 r.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:r}}function hS(e){let t=La(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return jh(t);if(Va(t,oS,"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"||!Ih.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!lt.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!lt.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!Th(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 r=t.operations.map(fS),i=r.map(n=>n.id);if(new Set(i).size!==i.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:r}}function pS(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return lt.join(e.transactionsDir,t)}function $h(e,t){let r=pS(e,t);return{directory:r,journal:lt.join(r,"transaction.json"),events:lt.join(r,"events.jsonl"),staged:lt.join(r,"staged"),backups:lt.join(r,"backups")}}async function qc(e,t){let r=$h(e,t);return await Promise.all(Object.values(r).map(i=>q(e.runtimeDir,i))),r}async function Wc(e,t,r={}){let i=await qc(e,t),n=await xr({root:e.runtimeDir,file:i.journal,maxBytes:uS,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(dS.decode(n.bytes)),o=hS(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function gS(e,t,r){let i;try{i=await mS.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await Wc(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of i)if(Ha(n.name))try{let a=await Mc(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(Rh(a))return!0}catch{return!0}return!1}async function wS(e,t){let r=Date.now()+5e3,i=vS.join(e.locksDir,"root-move.lock");for(;;)try{return await Ea(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await Kf(i);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=r)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function P(e,t,r,i){let n=await wS(e,t);try{if(await ma(e.projectRoot),await gS(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{await xa(n)}}import{promises as Di}from"node:fs";import ne from"node:path";var Tt=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};function zc(e,t){let r=ne.normalize(e),i=ne.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function Dh(e,t){let r=ne.relative(e,t);return r===""||!ne.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ne.sep}`)}function Oh(e){return JSON.stringify(e.native)}async function Ma(e,t){let r=await ve(e);if(r&&t){if(Oh(r)!==Oh(t))throw new Error(`Native worktree configuration differs from the source project: ${ne.join(e,".comet","config.yaml")}`);return!1}return!r&&t?(await va(e,t),!0):!1}async function yS(e,t){if(!Dh(e,t))return!1;let i=`/${ne.relative(e,t).replaceAll("\\","/").replace(/\/+$/u,"")}/`,n=A(e,["rev-parse","--git-common-dir"]),a=ne.resolve(e,n),o=ne.join(a,"info","exclude"),s="";try{s=await Di.readFile(o,"utf8")}catch(l){if(l.code!=="ENOENT")throw l}if(s.split(/\r?\n/u).includes(i))return!1;await Di.mkdir(ne.dirname(o),{recursive:!0});let c=s.length===0||s.endsWith(`
176
+ `,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!r&&i===null,index:s},s+=1,t!==null)t=xp(l,t);else if(r)Cp(l)&&(r=!1);else if(i!==null)new RegExp(`</${i}\\s*>`,"iu").test(l)&&(i=null);else{let u=xp(l,null);if(u!==null)t=u;else{let d=l.trimStart();if(d.startsWith("<!--")&&!Cp(d))r=!0;else{let p=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(d);p&&n.has(p[1].toLowerCase())&&!d.startsWith("</")&&!d.endsWith("/>")&&!new RegExp(`</${p[1]}\\s*>`,"iu").test(d)&&(i=p[1])}}}if(c===-1)break;o=c+1}}function qi(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function Rp(e,t,r,i=[],n="content-hash"){let a=qi(r),o=t.replaceAll("\\","/").trim(),s=i.map(qi);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-${ve(rS,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function Ap(e,t,r="content-hash"){let i=new Set;for(let n of e){let a=r==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(i.has(a))throw new Error(`${t} contains duplicate acceptance criteria`);i.add(a)}return e}function iS(e){let t=null,r=null,i=0,n=0;for(let{line:a,body:o,index:s}of Wa(e)){n=s+1;let c=o?Pp(a):null;c?.level===1&&(Oc(c.text)==="acceptanceExamples"?(i+=1,i===1&&(t=s+1)):t!==null&&r===null&&(r=s))}if(i===0||t===null)return null;if(i!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:r??n}}function zc(e,t="brief.md",r=za.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let n=iS(e);if(n===null)return[];let a=null;for(let{line:l,body:f,index:u}of Wa(e)){if(u<n.start||u>=n.end)continue;let d=f?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(d===null)continue;let p=d[1].length;a=a===null?p:Math.min(a,p)}let o=[],s=null,c=()=>{if(s!==null){if(o.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);o.push(s)}};for(let{line:l,body:f,index:u}of Wa(e)){if(u<n.start||u>=n.end)continue;let d=f?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;d&&d[1].length===a?(c(),s=[d[2]]):s!==null&&s.push(l)}return c(),Ap(o.map(l=>Rp("brief-example",t,l.join(`
177
+ `),[],i)),"Brief",i)}function Jc(e,t="spec.md",r=za.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=()=>{if(o!==null){if(n.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);n.push(Rp("spec-scenario",t,[o.title,...o.body].join(`
178
+ `),o.context,i)),o=null}};for(let{line:c,body:l}of Wa(e)){let f=l?Pp(c):null,u=f?/^Scenario\s*:\s*(.*)$/iu.exec(f.text):null;if(u){for(s();a.at(-1)&&a.at(-1).level>=f.level;)a.pop();let d=qi(u[1]);if(d.length===0)throw new Error("Scenario title must not be empty");o={level:f.level,title:d,body:[],context:a.map(p=>p.text)}}else if(f){for(o!==null&&f.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f)}else o!==null&&l&&o.body.push(c)}return s(),Ap(n,"Specification",i)}var nS=/^A[1-9]\d*$/u;function Ip(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||_p.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||_p.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function aS(e,t){return e.localeCompare(t,"en")}function Ja(e){let t=Ip(e.briefSource??"brief.md","Native brief source"),r=[...e.specs??[]].sort((a,o)=>aS(a.capability,o.capability));if(new Set(r.map(a=>a.capability)).size!==r.length)throw new Error("Native acceptance sources contain duplicate capabilities");let i=zc(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of r){let o=Ip(a.source,`Native spec source for ${a.capability}`);i.push(...Jc(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})))}let n=new Set;for(let a of i){a.text=qi(a.text);let o=`${a.source}\0${a.text}`;if(n.has(o))throw new Error(`Native acceptance contains a duplicate criterion: ${a.text}`);n.add(o)}if(i.length===0)throw new Error("Native change must define at least one acceptance criterion");return i.map((a,o)=>({id:`A${o+1}`,source:a.source,text:a.text}))}function Tp(e){let t=e.map(({id:r})=>r);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let r=0;r<t.length;r+=1)if(!nS.test(t[r])||t[r]!==`A${r+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function jp(e,t){return e.length===t.length&&e.every((r,i)=>r.source===t[i]?.source&&r.text===t[i]?.text)}function oS(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function H(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(oS(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let r="",i=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(i+a>t)break;r+=n,i+=a}return{text:r,truncated:!0}}var Ga="comet.native.portable-migration.v1",cS=new Set(["schema","id","change","fromSchema","status","createdAt"]),lS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,uS=/^[a-z0-9][a-z0-9-]{7,127}$/u,dS=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),fS=new Set([tt,et,ft]);function pS(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function hS(e,t){let r=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(r.valueOf()))throw new Error(`${t} must be a valid timestamp`);return r.toISOString()}function mS(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function vS(e){return e.schema===tt?Vi(e):e.schema===et?Mi(e):Fi(e)}function gS(e){return sS.posix.normalize(e.replaceAll("\\","/"))}function wS(e){return e.spec_changes.map(t=>t.operation==="remove"?{capability:t.capability,operation:"remove",source:null}:{capability:t.capability,operation:t.operation==="replace"?"modify":"create",source:gS(t.source)})}function yS(e){return e==="shape"?"shape":"build"}function NS(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function bS(e,t,r){return e==="zh-CN"?`从旧版 ${t} ${r} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${r} state; prior Loop, verification results, and execution records were not inherited.`}function $p(e){let t=vS(e.state);Tp(e.acceptance);let r=yS(t.phase),i=r==="shape"?0:1,n=hS(e.migratedAt??`${t.created_at}T00:00:00.000Z`,"Native portable migration time"),a=e.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return P({schema:_r,name:t.name,language:t.language,phase:r,status:"active",state_version:1,brief:"brief.md",spec_changes:wS(t),workspace:e.workspace,loop:{stage:r==="shape"?"shape":"building",goal_cycle:1,iteration:i,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:NS(t.language,r)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:i,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:H(bS(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:Cc(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function Gc(e){let t=pS(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!cS.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==Ga)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!uS.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!lS.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!fS.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!dS.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Ga,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:mS(t.createdAt,"Native portable migration transaction createdAt")}}function Op(e){switch(Gc(e).status){case"prepared":return{action:"commit-portable-yaml",fromStatus:"prepared",nextStatus:"yaml-committed"};case"yaml-committed":return{action:"cleanup-legacy-runtime",fromStatus:"yaml-committed",nextStatus:"legacy-cleanup"};case"legacy-cleanup":return{action:"commit-transaction",fromStatus:"legacy-cleanup",nextStatus:"committed"};case"committed":return{action:"done",fromStatus:"committed",nextStatus:null}}}var Hp="comet.native.archive-transaction.v4",Dp="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",kS=new RegExp(`^portable-archive-(${Dp})\\.json$`,"u"),SS=new RegExp(`^portable-migration-(${Dp})\\.json$`,"u"),ES=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,xS=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,CS=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),PS=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),RS=new Set(["capability","operation","source","content"]),Bp=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Lp(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Vp(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`);if(Object.keys(e).length!==t.size)throw new Error(`${r} fields are invalid`)}function AS(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=Lp(e,r);if(Vp(i,RS,r),typeof i.capability!="string"||!Bp.test(i.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(i.operation)))throw new Error(`${r}.operation is invalid`);let n=i.operation;if(n==="remove"){if(i.source!==null||i.content!==null)throw new Error(`${r} remove requires source and content null`);return{capability:i.capability,operation:n,source:null,content:null}}if(typeof i.source!="string"||i.source.length===0||i.source.includes("\\")||i.source.startsWith("/")||/^[A-Za-z]:/u.test(i.source)||i.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${r}.${n} source is invalid`);if(typeof i.content!="string")throw new Error(`${r}.${n} content is invalid`);return{capability:i.capability,operation:n,source:i.source,content:i.content}}function _S(e){let t=Lp(e,"Native portable Archive transaction");if(Vp(t,PS,"Native portable Archive transaction"),t.schema!==Hp)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!ES.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Bp.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"||!xS.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"||!CS.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 r=t.spec_changes.map(AS);if(new Set(r.map(({capability:n})=>n)).size!==r.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)>r.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 i=new Date(t.created_at);if(Number.isNaN(i.valueOf())||i.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:Hp,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:r,created_at:t.created_at}}function Ua(e){let t=kS.exec(e);if(t)return{kind:"archive",change:t[1]};let r=SS.exec(e);return r?{kind:"migration",change:r[1]}:null}function Ka(e,t){let r=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,i=Ua(r);if(!i||i.kind!==t.kind||i.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return Uc.join(e.transactionsDir,r)}async function Kc(e,t){let r=Ua(t);if(!r)return null;let i=await Y({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=Uc.join(e.transactionsDir,t);if(r.kind==="archive"){let s=_S(n);if(s.change!==r.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:r.change,file:a,journal:s}}let o=Gc(n);if(o.change!==r.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:r.change,file:a,journal:o}}async function Ya(e,t){let r=Ka(e,t);try{return await Kc(e,Uc.basename(r))}catch(i){if(i.code==="ENOENT")return null;throw i}}function Mp(e){return e.kind==="archive"||e.journal.status!=="committed"}import pt from"path";import{TextDecoder as TS}from"util";var jS=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),$S=new Set(["id","type","source","target","staged","backup"]),OS=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),HS=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var Wp=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var DS=256*1024,GT=1024*1024,UT=16*1024;var KT=64*1024*1024;var BS=new TS("utf-8",{fatal:!0});function Qa(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Za(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function zp(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Yc(e,t){if(typeof e!="string"||e.length===0||pt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Xa(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function Fp(e,t){if(Yc(e,t),e.includes("\\")||e!==pt.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function LS(e,t){let r=Qa(e,`transaction operations[${t}]`);if(Za(r,$S,`transaction operations[${t}]`),typeof r.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.id))throw new Error(`transaction operations[${t}].id is invalid`);if(r.type!=="write"&&r.type!=="remove"&&r.type!=="move")throw new Error(`transaction operation ${r.id} has an invalid type`);Yc(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&Yc(r[i],`transaction operation ${r.id} ${i}`);if(r.type==="write"){if(r.staged===void 0||r.source!==void 0)throw new Error(`write operation ${r.id} requires staged and forbids source`)}else if(r.type==="remove"){if(r.source!==void 0||r.staged!==void 0)throw new Error(`remove operation ${r.id} forbids source and staged`)}else if(r.source===void 0||r.staged!==void 0||r.backup!==void 0)throw new Error(`move operation ${r.id} requires source and forbids staged and backup`);return r}function Jp(e){let t=Qa(e,"Native Archive transaction journal");if(Za(t,OS,"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"||!Wp.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(!zp(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Xa(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 r=t.operations.map((s,c)=>{let l=Qa(s,`Archive transaction operations[${c}]`);if(Za(l,HS,`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`);Fp(l.target,`Archive transaction operation ${l.id} target`);for(let f of["source","staged","backup"])l[f]!==void 0&&Fp(l[f],`Archive transaction operation ${l.id} ${f}`);if(l.expectedTargetHash!==null&&Xa(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(Xa(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`);Xa(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),i=r.map(s=>s.id);if(new Set(i).size!==i.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=r.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)||r.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 r.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:r}}function VS(e){let t=Qa(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Jp(t);if(Za(t,jS,"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"||!Wp.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!pt.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!pt.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!zp(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 r=t.operations.map(LS),i=r.map(n=>n.id);if(new Set(i).size!==i.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:r}}function MS(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return pt.join(e.transactionsDir,t)}function Gp(e,t){let r=MS(e,t);return{directory:r,journal:pt.join(r,"transaction.json"),events:pt.join(r,"events.jsonl"),staged:pt.join(r,"staged"),backups:pt.join(r,"backups")}}async function Xc(e,t){let r=Gp(e,t);return await Promise.all(Object.values(r).map(i=>z(e.runtimeDir,i))),r}async function Qc(e,t,r={}){let i=await Xc(e,t),n=await jr({root:e.runtimeDir,file:i.journal,maxBytes:DS,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(BS.decode(n.bytes)),o=VS(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function WS(e,t,r){let i;try{i=await FS.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await Qc(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of i)if(Ua(n.name))try{let a=await Kc(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(Mp(a))return!0}catch{return!0}return!1}async function zS(e,t){let r=Date.now()+5e3,i=qS.join(e.locksDir,"root-move.lock");for(;;)try{return await Ha(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await lp(i);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=r)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function x(e,t,r,i){let n=await zS(e,t);try{if(await Ca(e.projectRoot),await WS(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{await Da(n)}}import{promises as Wi}from"node:fs";import se from"node:path";var Dt=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};function Zc(e,t){let r=se.normalize(e),i=se.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function Yp(e,t){let r=se.relative(e,t);return r===""||!se.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${se.sep}`)}function Up(e){return JSON.stringify(e.native)}async function eo(e,t){let r=await we(e);if(r&&t){if(Up(r)!==Up(t))throw new Error(`Native worktree configuration differs from the source project: ${se.join(e,".comet","config.yaml")}`);return!1}return!r&&t?(await Pa(e,t),!0):!1}async function JS(e,t){if(!Yp(e,t))return!1;let i=`/${se.relative(e,t).replaceAll("\\","/").replace(/\/+$/u,"")}/`,n=_(e,["rev-parse","--git-common-dir"]),a=se.resolve(e,n),o=se.join(a,"info","exclude"),s="";try{s=await Wi.readFile(o,"utf8")}catch(l){if(l.code!=="ENOENT")throw l}if(s.split(/\r?\n/u).includes(i))return!1;await Wi.mkdir(se.dirname(o),{recursive:!0});let c=s.length===0||s.endsWith(`
179
179
  `)?"":`
180
- `;return await Di.appendFile(o,`${c}${i}
181
- `,"utf8"),!0}function NS(e,t,r){let i=ne.resolve(e,r??ne.join(".worktrees",t)),n=ne.resolve(e,A(e,["rev-parse","--git-common-dir"]));if(Dh(n,i))throw new Error("Native worktree path cannot be inside the Git common directory");if(Wt(e).some(a=>zc(a,i)))throw new Error(`Native worktree path is already registered: ${i}`);return i}async function bS(e){try{throw await Di.lstat(e),new Error(`Native worktree path already exists: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t}}async function Hh(e){try{return await Di.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Jc(e){let t=ne.resolve(e.projectRoot);if(e.isolation==="current"){if(e.changeBranch||e.targetBranch||e.worktreePath)throw new Error("Native current isolation does not accept --change-branch, --target-branch, or --worktree-path");let i=F(t);if(i.isGitWorktree&&i.currentBranch===null)throw new Error("Native workspace binding requires a branch; detached HEAD is not supported");return{projectRoot:t,binding:{isolation:"current",changeBranch:i.currentBranch,targetBranch:i.currentBranch},preparation:{isolation:"current",projectRoot:t,changeBranch:i.currentBranch,targetBranch:i.currentBranch,worktreePath:null,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1}}}let r=await _t(t,e.sourceConfig?.native.artifact_root??"docs");return Uf([{runtimeDir:r.runtimeDir,locksDir:r.locksDir}],`prepare Native ${e.isolation} workspace`,async()=>{let i=F(t);if(!i.isGitWorktree||i.currentBranch===null||i.primaryWorktreeRoot===null||i.currentWorktreeRoot===null)throw new Error("Native branch and worktree isolation require an attached Git branch");let n=e.changeBranch??`comet/${e.name}`;Qs(t,n);let a=i.currentBranch===n,o=e.targetBranch??(a?void 0:i.currentBranch);if(!o)throw new Error("Native isolated workspace already on its change branch requires --target-branch");if(Qs(t,o),!pr(t,o))throw new Error(`Native target branch is not a verified local branch: ${o}`);if(e.isolation==="branch"){if(e.worktreePath)throw new Error("--worktree-path is only valid with --isolation worktree");let h=!1;if(!a){if(!at(t))throw new Error("Native branch isolation requires a clean current working directory");if(pr(t,n))throw new Error(`Native change branch already exists: ${n}`);A(t,["switch","-c",n,o]),h=!0}let v;try{v=await Ma(t,e.sourceConfig)}catch(m){throw new Tt(`Native branch preparation is incomplete: ${m.message}`,{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:h,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:m})}return{projectRoot:t,binding:{isolation:"branch",changeBranch:n,targetBranch:o},preparation:{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:h,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}if(a){if(!i.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree");let h=e.worktreePath?ne.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(h&&!zc(h,i.currentWorktreeRoot))throw new Error(`Native worktree path ${h} does not match the current worktree ${i.currentWorktreeRoot}`);let v;try{v=await Ma(t,e.sourceConfig)}catch(m){throw new Tt(`Native worktree preparation is incomplete: ${m.message}`,{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:m})}return{projectRoot:t,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}let s=ta(i.primaryWorktreeRoot),c=s.find(h=>h.branch===n);if(c&&await Hh(c.root)){let h=e.worktreePath?ne.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(h&&!zc(h,c.root))throw new Error(`Native worktree branch ${n} is already checked out at ${c.root}`);let v;try{v=await Ma(c.root,e.sourceConfig)}catch(m){throw new Tt(`Native worktree preparation is incomplete: ${m.message}`,{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:m})}return{projectRoot:c.root,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}c&&!await Hh(c.root)&&(A(i.primaryWorktreeRoot,["worktree","prune"]),s=ta(i.primaryWorktreeRoot));let l=pr(t,n);if(s.some(h=>h.branch===n))throw new Error(`Native change branch ${n} is already registered to a worktree`);let f=NS(i.primaryWorktreeRoot,e.name,e.worktreePath);await bS(f);let d=await yS(i.primaryWorktreeRoot,f),u={isolation:"worktree",projectRoot:f,changeBranch:n,targetBranch:o,worktreePath:f,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:d,configInitialized:!1};try{A(i.primaryWorktreeRoot,l?["worktree","add",f,n]:["worktree","add","-b",n,f,o]),u.createdBranch=!l,u.createdWorktree=!0,u.configInitialized=await Ma(f,e.sourceConfig)}catch(h){throw new Tt(`Native worktree preparation is incomplete: ${h.message}`,u,{cause:h})}return{projectRoot:f,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:u}})}var Gc="comet.native.supervisor.v2",SS=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function Lh(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`}async function Vh(e){let t=Xt.join(".worktrees",`${e.parent}-integration`);return Jc({projectRoot:e.projectRoot,name:`${e.parent}-integration`,isolation:"worktree",changeBranch:Lh(e.parent),targetBranch:e.targetBranch,worktreePath:t,sourceConfig:e.sourceConfig})}async function ES(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.parent)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.child))throw new Error("Native Supervisor parent and child names are invalid");return Jc({projectRoot:e.projectRoot,name:`${e.parent}-${e.child}`,isolation:"worktree",changeBranch:`comet/supervisor/${e.parent}/${e.child}`,targetBranch:e.targetBranch,worktreePath:Xt.join(".worktrees",`${e.parent}-${e.child}`),sourceConfig:e.sourceConfig})}function xS(e,t){return Xt.join(He(e,t),"supervisor")}function Fa(e,t){return Xt.join(xS(e,t),"state.json")}function Mh(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!==Gc)throw new Error(`Native Supervisor state schema must be ${Gc}`);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(jt(t.integration.targetCommit,"Native Supervisor target commit"),jt(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 r=new Set,i=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(r.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(r.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&&jt(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(jt(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),i.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(i.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 re(e,t){try{let r=await Bh.readFile(Fa(e,t),"utf8"),i=JSON.parse(r);return Mh(i),i}catch(r){if(r.code==="ENOENT")return null;throw r}}async function ae(e,t){Mh(t),await Bh.mkdir(e.changesRuntimeDir,{recursive:!0}),await me(Fa(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function jt(e,t){if(!SS.test(e))throw new Error(`${t} must be a Git commit`)}function Qe(e){return structuredClone(e)}function ut(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function PS(e,t){for(let r of t.dependsOn){let i=e.children.find(({name:n})=>n===r);if(!i||i.status!=="integrated")throw new Error(`Native Supervisor child ${t.name} dependency ${r} is not integrated`)}}function CS(e){let t=new Set(e.children.map(({name:i})=>i)),r=[];for(;t.size>0;){let i=e.children.find(n=>t.has(n.name)&&n.dependsOn.every(a=>!t.has(a)));if(!i)throw new Error("Native Supervisor Child dependencies contain a cycle");r.push(i),t.delete(i.name)}return r}function Uc(e){jt(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:i})=>i)),r=e.contract.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.depends_on],status:i.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 i of r)for(let n of i.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${i.name} depends on unknown child ${n}`);return{schema:Gc,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:r,history:[],finalVerification:{status:"pending",summary:null}}}async function qa(e){let t=Lh(e.parent),r=mr(e.paths.projectRoot,t);if(!r)return null;let i=mr(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=Wt(e.paths.projectRoot).map(o=>Xt.resolve(o)).find(o=>F(o).currentBranch===t);if(!n)return null;let a=Uc({parent:e.parent,targetBranch:e.targetBranch,targetCommit:i,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(r!==i){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=r}return ut(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function Fh(e){let t=Qe(e.state),r=new Map(e.contract.children.map(n=>[n.name,n])),i=new Map(t.children.map(n=>[n.name,n]));for(let n of t.children){let a=r.get(n.name);if(!a){if(n.status!=="archived")throw new Error(`Native Supervisor child ${n.name} cannot be removed before Archive`);continue}if((n.status==="integrated"||n.status==="archived")&&(a.summary!==n.summary||a.depends_on.join("\0")!==n.dependsOn.join("\0")))throw new Error(`Native Supervisor integrated child ${n.name} history is immutable`);n.summary=a.summary,n.dependsOn=[...a.depends_on]}for(let n of e.contract.children)i.has(n.name)||t.children.push({name:n.name,summary:n.summary,dependsOn:[...n.depends_on],status:n.depends_on.every(a=>t.children.some(({name:o,status:s})=>o===a&&s==="integrated"))?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null});return t.stateVersion+=1,t}function Kc(e,t){if(!t.projectRoot.trim()||!t.runId.trim())throw new Error("Native Supervisor task projectRoot and runId are required");let r=Qe(e),i=r.children.find(({name:o})=>o===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(i.task)throw new Error(`Native Supervisor child ${t.child} already has an active task`);let n;if(t.role==="builder"){if(i.status!=="ready")throw new Error(`Native Supervisor child ${t.child} is not ready for a Builder task`);PS(r,i),n=r.integration.headCommit,i.status="active"}else{if(i.status!=="active"&&i.status!=="needs-reverify"||!i.candidateCommit)throw new Error(`Native Supervisor child ${t.child} is not ready for a Verifier task`);n=i.candidateCommit}let a={...t,baseCommit:n};return i.projectRoot=t.projectRoot,i.task=a,i.blocker=null,ut(r,{kind:"task-dispatched",child:i.name,runId:a.runId,summary:`${a.role} task dispatched`}),r.stateVersion+=1,{state:r,task:a}}function RS(e,t){let r=e.children.find(({name:i})=>i===t.child);if(!r?.task||r.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return structuredClone(r.task)}function qh(e,t){let r=RS(e,t),i=Qe(e);return ut(i,{kind:"task-reconnected",child:t.child,runId:t.runId,summary:"existing task reconnected"}),i.stateVersion+=1,{state:i,task:r}}function AS(e,t,r){let i=F(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor child worktree identity is not ${t}`);if(!at(e))throw new Error(`Native Supervisor child worktree is not clean: ${e}`);let n=A(e,["rev-parse","HEAD"]);if(n===r)return;if(!(()=>{try{return A(e,["merge-base","--is-ancestor",n,r]),!0}catch{return!1}})())throw new Error(`Native Supervisor child worktree ${e} cannot be refreshed from integration HEAD`);if((()=>{try{return A(e,["merge-base","--is-ancestor",r,n]),!0}catch{return!1}})())throw new Error(`Native Supervisor child worktree ${e} contains unintegrated commits`);if(A(e,["merge","--ff-only",r]),A(e,["rev-parse","HEAD"])!==r)throw new Error("Native Supervisor child worktree did not reach integration HEAD")}function _S(e){if(!at(e.integration.worktree))throw new Error("Native Supervisor integration worktree must be clean");let t=A(e.integration.worktree,["rev-parse","--show-toplevel"]);if(Xt.resolve(t)!==Xt.resolve(e.integration.worktree))throw new Error("Native Supervisor integration worktree identity is invalid");let r=A(e.integration.worktree,["branch","--show-current"]);if(r!==e.integration.branch)throw new Error(`Native Supervisor integration branch mismatch: expected ${e.integration.branch}, got ${r||"(detached)"}`);return A(e.integration.worktree,["rev-parse","HEAD"])}function IS(e,t,r){let i=F(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor Verifier worktree identity is not ${t}`);if(!at(e))throw new Error(`Native Supervisor Verifier worktree is not clean: ${e}`);if(A(e,["rev-parse","HEAD"])!==r)throw new Error("Native Supervisor Verifier worktree is not at its candidate commit")}function Yc(e,t){if(t.reason.trim().length===0)throw new Error("Native Supervisor cancellation reason is required");let r=Qe(e),i=r.children.find(({name:n})=>n===t.child);if(!i?.task||i.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return i.task.role==="builder"?(i.status="ready",i.candidateCommit=null):i.status="needs-reverify",i.task=null,i.blocker=t.reason,ut(r,{kind:"task-cancelled",child:t.child,runId:t.runId,summary:t.reason}),r.stateVersion+=1,r}function Wa(e,t){if(t.reason.trim().length===0)throw new Error("Native Supervisor blocker reason is required");let r=Qe(e),i=r.children.find(({name:n})=>n===t.child);if(!i?.task||i.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return i.blocker=t.reason,ut(r,{kind:"task-blocked",child:t.child,runId:t.runId,summary:t.reason}),r.stateVersion+=1,r}async function Wh(e){return P(e.paths,`dispatch Native Supervisor children ${e.parent}`,async()=>{let t=await re(e.paths,e.parent);if(!t)throw new Error(`Native Supervisor state is missing for ${e.parent}`);let r=e.maxParallel??2;if(!Number.isSafeInteger(r)||r<1)throw new Error("Native Supervisor maxParallel must be a positive integer");let i=t.children.filter(({task:l})=>l!==null).length,n=Math.max(0,r-i);if(n===0)return{state:t,tasks:[]};let a=await ve(e.paths.projectRoot),o=t,s=[],c=!1;for(let l of t.children){if(s.length>=n)break;if(l.task!==null)continue;let f=l.status==="needs-reverify"&&l.candidateCommit!==null;if(l.status!=="ready"&&!f)continue;let d;try{d=await ES({projectRoot:e.paths.projectRoot,parent:t.parent,child:l.name,targetBranch:t.integration.branch,sourceConfig:a}),f?IS(d.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,l.candidateCommit):AS(d.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,t.integration.headCommit)}catch(h){let v=Qe(o),m=v.children.find(({name:p})=>p===l.name);m&&(m.blocker=h.message,ut(v,{kind:"task-blocked",child:l.name,runId:null,summary:m.blocker}),v.stateVersion+=1,o=v,c=!0);continue}let u=Kc(o,{role:f?"verifier":"builder",child:l.name,projectRoot:d.projectRoot,runId:kS()});o=u.state,s.push(u.task)}return(s.length>0||c)&&await ae(e.paths,o),{state:o,tasks:s}})}function zh(e,t){jt(t.candidateCommit,"Native Supervisor candidate commit");let r=Qe(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(!i.task||i.task.role!=="builder"||i.task.runId!==t.runId)throw new Error(`Native Supervisor Builder result runId is not current for ${t.child}`);if(i.status!=="active")throw new Error(`Native Supervisor child ${t.child} is not active for Builder result`);return i.candidateCommit=t.candidateCommit,i.task=null,i.blocker=null,ut(r,{kind:"builder-result",child:i.name,runId:t.runId,summary:"Builder candidate recorded"}),r.stateVersion+=1,r}function Jh(e,t){if(t.evidence.summary.trim().length===0)throw new Error("Native Supervisor verification summary must not be empty");if(t.verdict==="pass"&&t.evidence.checks.length===0)throw new Error("Native Supervisor verification pass requires at least one check");let r=Qe(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(!i.task||i.task.role!=="verifier"||i.task.runId!==t.runId)throw new Error(`Native Supervisor Verifier result runId is not current for ${t.child}`);if(i.status!=="active"&&i.status!=="needs-reverify"||!i.candidateCommit)throw new Error(`Native Supervisor child ${t.child} is not ready for Verifier result`);return i.verification={summary:t.evidence.summary,checks:[...t.evidence.checks]},i.task=null,t.verdict==="pass"?(i.status="verified",i.verifiedCommit=i.candidateCommit,i.blocker=null):(i.status="needs-reverify",i.blocker=t.evidence.summary),ut(r,{kind:"verifier-result",child:i.name,runId:t.runId,summary:t.evidence.summary}),r.stateVersion+=1,r}function TS(e,t){jt(t.integrationCommit,"Native Supervisor integration commit");let r=Qe(e),i=r.children.find(({name:n})=>n===t.name);if(!i)throw new Error(`Native Supervisor child ${t.name} does not exist`);if(i.status!=="verified"||!i.verifiedCommit)throw new Error(`Native Supervisor child ${t.name} must be verified before integration`);if(t.checks.length===0||t.checks.some(({status:n})=>n!=="passed"))throw new Error(`Native Supervisor child ${t.name} integration checks are incomplete`);i.status="integrated",i.integrationCommit=t.integrationCommit,i.checks=structuredClone(t.checks),i.blocker=null,r.integration.headCommit=t.integrationCommit,ut(r,{kind:"child-integrated",child:i.name,runId:null,summary:"Child integrated into the Supervisor branch"});for(let n of r.children)n.status==="pending"&&n.dependsOn.every(a=>r.children.some(({name:o,status:s})=>o===a&&s==="integrated"))&&(n.status="ready");return r.stateVersion+=1,r}async function Gh(e){return P(e.paths,`integrate Native Supervisor child ${e.name}`,async()=>{let r=await re(e.paths,e.state.parent)??e.state;if(r.stateVersion!==e.state.stateVersion)throw new Error("Native Supervisor state changed before integration; reload status first");let i=r.children.find(({name:c})=>c===e.name);if(!i)throw new Error(`Native Supervisor child ${e.name} does not exist`);let n=CS(r).find(({status:c})=>c!=="integrated"&&c!=="archived");if(n&&n.name!==e.name)throw new Error(`Native Supervisor integration order requires ${n.name} before ${e.name}`);if(i.status!=="verified"||!i.verifiedCommit)throw new Error(`Native Supervisor child ${e.name} must be verified before integration`);let a=_S(r);if(a!==r.integration.headCommit){let c=(()=>{try{return A(r.integration.worktree,["merge-base","--is-ancestor",r.integration.headCommit,a]),!0}catch{return!1}})(),l=(()=>{try{return A(r.integration.worktree,["merge-base","--is-ancestor",i.verifiedCommit,a]),!0}catch{return!1}})();if(!c||!l)throw new Error(`Native Supervisor integration head drifted: expected ${r.integration.headCommit}, got ${a}`)}try{A(r.integration.worktree,["cat-file","-e",`${i.verifiedCommit}^{commit}`])}catch(c){throw new Error(`Native Supervisor verified commit is unavailable: ${i.verifiedCommit}`,{cause:c})}if(a===r.integration.headCommit){try{A(r.integration.worktree,["merge","--no-ff","--no-edit",i.verifiedCommit])}catch(c){throw new Error(`Native Supervisor integration conflict preserved in ${r.integration.worktree}`,{cause:c})}a=A(r.integration.worktree,["rev-parse","HEAD"])}let o=a,s=TS(r,{name:e.name,integrationCommit:o,checks:e.checks});return await ae(e.paths,s),s})}function Uh(e,t){if(jt(t.headCommit,"Native Supervisor final verification head commit"),t.summary.trim().length===0)throw new Error("Native Supervisor final verification summary must not be empty");let r=Qe(e);if(t.headCommit!==r.integration.headCommit)throw new Error("Native Supervisor final verification head is stale");if(t.status==="passed"){if(r.children.some(({status:i})=>i!=="integrated"))throw new Error("Native Supervisor cannot pass final verification before all children integrate");if(t.layers.parentChecks.length===0)throw new Error("Native Supervisor parent verification requires executed parent checks");if(t.layers.childVerification!=="complete"||t.layers.parentIntegration!=="complete"||t.layers.incomplete.length>0)throw new Error("Native Supervisor final verification evidence is incomplete")}return r.finalVerification={status:t.status,summary:t.summary,layers:{childVerification:t.layers.childVerification,parentIntegration:t.layers.parentIntegration,parentChecks:[...t.layers.parentChecks],notRerun:[...t.layers.notRerun],incomplete:[...t.layers.incomplete]}},r.stateVersion+=1,r}function Kh(e){let t=e.children.map(r=>({name:r.name,summary:r.summary,dependsOn:[...r.dependsOn],covers:[],status:r.status,phase:null,projectRoot:r.projectRoot??r.task?.projectRoot??null,message:r.blocker}));return{contractHash:null,confirmed:!0,parentBranch:e.integration.branch,children:t,readyChildren:t.filter(({status:r})=>r==="ready").map(({name:r})=>r),allDone:t.every(({status:r})=>r==="integrated"||r==="archived")}}var Yh="children.yaml",za="comet.native.children.v1",Ar="comet.native.children.v2",jS=Ar,$S=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Xh=new Set(["schema","children"]),OS=new Set(["schema","acceptance_index","children"]),HS=new Set(["name","depends_on","covers"]),DS=new Set(["name","summary","depends_on"]),BS=new Set(["name","depends_on","covers"]);function Ga(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function Ja(e,t,r){let i=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(i.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...i.length>0?[`unexpected ${i.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${r} fields are invalid: ${a.join("; ")}`)}}function Qh(e,t){if(!Array.isArray(e)||!e.every(r=>typeof r=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((r,i)=>r.localeCompare(i,"en"))}function Xc(e,t){let r=Ae.normalize(Ae.resolve(e)),i=Ae.normalize(Ae.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function LS(e){let t=new Map(e.map(a=>[a.name,a])),r=new Set,i=new Set,n=a=>{if(!i.has(a)){if(r.has(a))throw new Error(`Native children dependency cycle includes ${a}`);r.add(a);for(let o of t.get(a).depends_on)n(o);r.delete(a),i.add(a)}};for(let a of e)n(a.name)}function Zh(e,t,r=t){let i=new Set(t);for(let o of e){let s=o.covers.filter(c=>!i.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=r.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function Bi(e){let t=new Set(e.acceptance.filter(({source:r})=>r===e.brief).map(({id:r})=>r));if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let r=[...e.history].reverse().find(({outcome:i})=>i==="fail");for(let i of r?.unresolved_ids??[])t.add(i)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...t]}}function VS(e){let t=Ga(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),r={};for(let[i,n]of Object.entries(t)){let a=Ga(n,`Native children acceptance_index.${i}`);if(Ja(a,new Set(["source","text"]),`Native children acceptance_index.${i}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${i}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${i}.text must be a non-empty string`);r[i]={source:a.source,text:a.text}}return r}function MS(e,t,r){let i=r.requiredAcceptanceIds??t??[],n=Object.keys(e),a=i.filter(c=>!(c in e)),o=n.filter(c=>!i.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((r.acceptanceCatalog??[]).map(c=>[c.id,c]));for(let c of i){let l=s.get(c);if(!l)continue;let f=e[c];if(f.source!==l.source||f.text!==l.text){let d=["source","text"].filter(u=>f[u]!==l[u]);throw new Error(`Native children acceptance_index.${c} does not match the acceptance catalog: copy ${d.join(", ")} exactly from the current acceptance catalog`)}}}function FS(e,t,r={}){let i=(0,Qc.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=Ga(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==za&&a!==Ar)throw Ja(n,Xh,"Native children contract"),new Error(`Native children schema must be ${za} or ${Ar}`);let o=a===za?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(Ja(n,o==="indexed-v2"?OS:Xh,"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,u)=>{let h=Ga(d,`Native child ${u}`);if(Ja(h,o==="indexed-v2"?BS:o==="summary-v2"?DS:HS,`Native ${s} child fields (child ${u})`),typeof h.name!="string"||!$S.test(h.name))throw new Error(`Native child ${u} name is invalid`);let v=o==="summary-v2";if(v){if(typeof h.summary!="string"||h.summary.trim().length===0)throw new Error(`Native child ${h.name} summary must be a non-empty string`);if(h.summary.length>2e3)throw new Error(`Native child ${h.name} summary exceeds 2000 characters`)}return{name:h.name,summary:v?h.summary:null,depends_on:Qh(h.depends_on,`Native child ${h.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?Qh(h.covers,`Native child ${h.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 f=new Set(l);for(let d of c){let u=d.depends_on.filter(h=>!f.has(h));if(u.length>0)throw new Error(`Native child ${d.name} depends on unknown child: ${u.join(", ")}`)}if(LS(c),a===jS){if(o==="indexed-v2"){let d=VS(n.acceptance_index);MS(d,t,r);let u=Object.keys(d);return Zh(c,u,u),{schema:Ar,acceptance_index:d,children:c}}return{schema:Ar,children:c}}return t&&Zh(c,t),{schema:za,children:c}}async function Li(e){let t=Ae.join(e.changeDir,Yh);try{await tp.lstat(t)}catch(i){if(i.code==="ENOENT")return null;throw i}let r=await J({root:e.changeDir,ref:Yh});return{contract:FS(r.text,e.acceptanceIds,e.validation),size:r.size}}function qS(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let r=e.slice(t.index+t[0].length);return r.split(/^#\s+/mu,1)[0]??r}function WS(e){let t=qS(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let r=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),i=t.match(/\bChild\s+\d+\b/giu);return Math.max(r?.length??0,i?.length??0)>=2}async function Zc(e){try{let t=await J({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return WS(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Ua(e){return pe("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:r,text:i})=>({id:t,source:r,text:i})),children:e.children})}async function zS(e){let t=Wt(e.projectRoot);t.some(i=>Xc(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>Ae.resolve(n)))]){let n=await ve(i);n&&r.push({projectRoot:i,paths:await _t(i,n.native.artifact_root),parent:Xc(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function JS(e,t){let r=Ae.join(e.paths.changesDir,t,"comet-state.yaml");try{return await De(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function GS(e,t){let r;try{r=await tp.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=Ae.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await De(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function US(e,t,r){let i=Ae.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${Ae.sep}`))return null;let n=i.split(Ae.sep).join("/");try{let a=(0,Qc.parseDocument)(A(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:C(a.toJS({mapAsMap:!1}))}catch{return null}}function KS(e,t,r){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==r||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 ${r??"(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 ep(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Ze(e){let t=Ae.join(e.paths.changesDir,e.state.name),r=await Zc(t),i=await Li({changeDir:t,validation:Bi(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:p})=>p)}:{}});if(!i)return e.state.children_contract_hash?{...r?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:r?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null;let n=Ua({acceptance:e.state.acceptance,children:i.contract}),a=e.state.workspace.change_branch,o=e.state.phase!=="shape"&&e.state.children_contract_hash===n;if(i.contract.schema===Ar){let p=await re(e.paths,e.state.name);if(!p){let w=e.state.workspace.target_branch??e.state.workspace.change_branch;if(w){let k=await qa({paths:e.paths,parent:e.state.name,targetBranch:w,contract:i.contract});k&&(p=k,await ae(e.paths,k))}}if(p){let w=Kh(p);return e.state.children_contract_hash!==n?{...w,schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:!1,readyChildren:[],allDone:!1,children:w.children.map(k=>({...k,message:"Supervisor child plan changed; Shape confirmation is required"}))}:{...w,schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o}}let y=new Map(i.contract.children.map(w=>[w.name,w])),g=i.contract.children.map(w=>({name:w.name,summary:w.summary,dependsOn:[...w.depends_on],covers:[],status:o&&w.depends_on.every(k=>i.contract.children.filter(({name:S})=>S!==w.name).every(({name:S})=>S!==k))?"ready":"pending",phase:null,projectRoot:null,message:o?null:"Parent Shape confirmation is required"}));for(let w of g){if(w.status!=="ready")continue;y.get(w.name).depends_on.length>0&&(w.status="pending")}return{schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:g,readyChildren:g.filter(({status:w})=>w==="ready").map(({name:w})=>w),allDone:!1}}let s=await zS(e.paths),c=new Set(i.contract.children.map(({name:p})=>p)),l=new Map,f=new Map;for(let p of s){let y=p.parent&&a?`refs/heads/${a}`:"HEAD";for(let g of await GS(p,c)){let w={...g,source:p,committedState:US(p,g.file,y)};l.set(g.state.name,[...l.get(g.state.name)??[],w])}for(let g of c){let w=await JS(p,g);w&&f.set(g,[...f.get(g)??[],{source:p,state:w}])}}let d=new Map;for(let p of i.contract.children){let y=(l.get(p.name)??[]).find(({source:k,committedState:S})=>k.parent&&S?.name===p.name&&ep(S,a));if(y){d.set(p.name,{kind:"done",phase:y.state.phase,projectRoot:y.source.projectRoot,message:null});continue}let g=l.get(p.name)?.[0];if(g){d.set(p.name,{kind:"blocked",phase:g.state.phase,projectRoot:g.source.projectRoot,message:`Native child ${p.name} is archived but not merged into parent branch ${a??"(missing)"}`});continue}let w=f.get(p.name)??[];w.length>1?d.set(p.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${p.name} has multiple active workspace owners`}):w[0]&&d.set(p.name,KS(w[0].state,w[0].source,a))}let u=new Map(i.contract.children.map(p=>[p.name,p])),h=new Map,v=p=>{let y=h.get(p);if(y)return y;let g=u.get(p),k=g.depends_on.map(v).every(({status:Y})=>Y==="done"),S=d.get(p),E=S?.kind==="active"&&k?g.depends_on.filter(Y=>!(l.get(Y)??[]).some(({source:ee,committedState:$})=>Xc(ee.projectRoot,S.projectRoot)&&$?.name===Y&&ep($,a))):[],x,N=S?.message??null;S?.kind==="done"?(x=k?"done":"blocked",k||(N=`Native child ${p} was merged before its dependencies`)):S?.kind==="active"?(x=k&&E.length===0?"active":"blocked",k?E.length>0&&(N=`Native child ${p} does not include merged dependencies: ${E.join(", ")}`):N=`Native child ${p} started before its dependencies merged`):S?.kind==="blocked"?x="blocked":(x=o&&k?"ready":"pending",o||(N="Parent Shape confirmation is required"));let _={name:p,summary:g.summary,dependsOn:[...g.depends_on],covers:[...g.covers],status:x,phase:S?.phase??null,projectRoot:S?.projectRoot??null,message:N};return h.set(p,_),_},m=i.contract.children.map(({name:p})=>v(p));return{schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:m,readyChildren:m.filter(({status:p})=>p==="ready").map(({name:p})=>p),allDone:m.every(({status:p})=>p==="done")}}function Qt(e,t,r){return e.language==="zh-CN"?r:t}function YS(e,t){let r=i=>({required:!1,message:null,suggestedReply:null,agentInstruction:i});return t&&e.phase==="shape"&&e.status==="active"?{required:!0,message:Qt(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:Qt(e,"Reply A or B","回复 A 或 B"),agentInstruction:Qt(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"?r(Qt(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"?r(Qt(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:i})=>i==="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."}:r(Qt(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 tl(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Ka(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function rp(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function XS(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function QS(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function ZS(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 Vi(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:tl({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Ka("summary","--summary"),rp(e.name,e.flag)]}}function el(e){return[Vi({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Vi({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function U(e,t){let r=QS(t)&&e.coordination_mode===void 0,i={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],userCommunication:YS(e,r)},n=a=>({kind:a,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...i,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:n("none")};if(e.status==="await-user")return e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...i,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Ka("summary","--summary")],commandAlternatives:[Vi({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...el({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"?{...i,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:tl({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"?{...i,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Ka("summary","--summary")],commandAlternatives:[Vi({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...el({change:e.name,stateVersion:e.state_version})],runnerAction:n("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...i,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Ka("summary","--summary")],commandAlternatives:el({change:e.name,stateVersion:e.state_version}),runnerAction:n("none")}:{...i,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{...i,disposition:"blocked",action:a?"retry-verifier":"none",commandArgs:a?tl({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{...i,disposition:r?"await-user":"continue",action:"confirm-shape",commandArgs:ZS({change:e.name,stateVersion:e.state_version,coordinationRequired:r}),requiredInputs:["summary",...r?["coordination-choice"]:[],"shared-understanding-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},...r?[XS("coordination-mode","--coordination-mode",ga)]:[],rp("confirmed","--confirmed")],runnerAction:n("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...i,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:n("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...i,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:n("none")};if(t.allDone)return{...i,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{...i,disposition:a&&!o?"blocked":"continue",action:"advance-children",commandArgs:null,requiredInputs:a&&!o?["resolve-child-blocker"]:["ready-children"],inputOptions:[],runnerAction:n("none")}}return{...i,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],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{...i,userCommunication:!a&&o?{...i.userCommunication,agentInstruction:`${i.userCommunication.agentInstruction} ${Qt(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:i.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?{...i,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],commandAlternatives:[Vi({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:n("none")}:{...i,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:n("none")}}import{randomUUID as KE}from"node:crypto";import{promises as Yi}from"node:fs";import YE from"node:path";import{randomUUID as wl}from"node:crypto";import{promises as Gi}from"node:fs";import Z from"node:path";import{createWriteStream as NE,promises as bE}from"node:fs";import be from"node:path";import{spawn as rl}from"node:child_process";import{existsSync as ip}from"node:fs";import Zt from"node:path";var eE=new Set([".bat",".cmd",".ps1"]),tE=new Set([".bat",".cmd"]),rE=/[&|<>()^%"!\r\n]/u,iE=["$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("; ");function il(e,t){let r=t.toLowerCase();return Object.entries(e).find(([i,n])=>i.toLowerCase()===r&&n!==void 0)?.[1]}function nE(e){let t=(il(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function aE(e,t,r){let n=Zt.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(il(t,"PATH")??"").split(Zt.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=Zt.win32.extname(e)?[e]:nE(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(c=>s?Zt.join(s,c):Zt.resolve(r,c)))}function oE(e,t,r){return aE(e,t,r).find(i=>ip(i))??e}function sE(e){let t=il(e,"SystemRoot");if(t){let r=Zt.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe");if(ip(r))return r}return"powershell.exe"}function cE(e){if(e.some(t=>rE.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}function lE(e,t,r){let i=Buffer.from(JSON.stringify({command:e,arguments:[...t]}),"utf8").toString("base64"),n=Buffer.from(iE,"utf16le").toString("base64");return rl(sE(r.env),["-NoLogo","-NoProfile","-NonInteractive","-InputFormat","None","-OutputFormat","Text","-ExecutionPolicy","Bypass","-EncodedCommand",n],{cwd:r.cwd,env:{...r.env,COMET_COMMAND_PAYLOAD:i},shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}function nl(e,t,r){let i=r.env??process.env;if(process.platform!=="win32")return rl(e,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});let n=oE(e,i,r.cwd),a=Zt.win32.extname(n).toLowerCase();return tE.has(a)&&cE(t),eE.has(a)?lE(n,t,{cwd:r.cwd,env:i}):rl(n,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}import{spawn as uE}from"node:child_process";import al from"node:path";var dE=1e3,fE=2;async function Ya(e){let t=e.pid;if(t===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let r=process.env.SystemRoot??process.env.WINDIR,i=r&&al.win32.isAbsolute(r)?al.win32.resolve(r):"C:\\Windows",n=al.win32.join(i,"System32","taskkill.exe"),a=()=>new Promise(o=>{let s=!1,c=null,l=null,f=(d,u=!1)=>{s||(s=!0,l&&clearTimeout(l),u&&c?.kill("SIGKILL"),o(d))};try{c=uE(n,["/pid",String(t),"/t","/f"],{stdio:"ignore",windowsHide:!0}),c.once("error",()=>f(!1)),c.once("close",d=>f(d===0)),l=setTimeout(()=>f(!1,!0),dE)}catch{f(!1)}});for(let o=0;o<fE;o+=1)if(await a()){e.kill("SIGKILL");return}e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy();return}try{process.kill(-t,"SIGKILL")}catch(r){if(r.code!=="ESRCH")throw r}e.kill("SIGKILL")}var hE=/\b(Bearer|Basic)\s+[^\s"']+/giu,pE=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,mE=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,vE=/\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,gE=/("(?:[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,wE=/(["'])((?:[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,yE=/\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\b(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)/giu;function $t(e){return e.replace(hE,"$1 [REDACTED]").replace(pE,"[REDACTED PRIVATE KEY]").replace(mE,"$1[REDACTED]@").replace(vE,"[REDACTED TOKEN]").replace(gE,'$1"[REDACTED]"').replace(wE,"$1$2$1$3$4[REDACTED]$4").replace(yE,"$1$2[REDACTED]")}function np(e,t){let r=be.relative(e,t);return r===""||!be.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${be.sep}`)}function ap(e,t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(e))throw new Error(`${t} is invalid`);return e}function Xa(e,t){if(t.length===0||t.includes("\\")||be.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||be.posix.normalize(t)!==t)throw new Error("Native check cwd must be a normalized project-relative ref");let r=be.resolve(e),i=be.resolve(r,...t.split("/"));if(!np(r,i))throw new Error("Native check cwd escaped the project root");return i}function Mi(e){return JSON.stringify([e.executable,e.argv,e.cwdRef.replaceAll("\\","/"),e.timeoutMs,e.repeatable])}var kE=/^(?:-p|-u|--(?:[a-z0-9]+[-_])*(?:api[-_]?key|access[-_]?token|auth[-_]?token|client[-_]?secret|secret(?:[-_]?access)?[-_]?key|private[-_]?key|token|password|passwd|secret|authorization|cookie|set[-_]?cookie|user))$/iu;function ol(e){let t=!1;return e.map(r=>{if(t)return t=!1,"[REDACTED]";let i=$t(r);return kE.test(r)&&(t=!0),i})}function Qa(e,t){if(ap(t.id,"Native check ID"),t.name.trim().length===0||t.executable.trim().length===0)throw new Error("Native check name and executable must be non-empty");if(!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<1)throw new Error("Native check timeout must be a positive integer");return Xa(e,t.cwdRef)}async function sl(e){let{plan:t}=e;ap(e.operationId,"Native check operation ID");let r=Qa(e.projectRoot,t),i=be.join(e.runtimeDir,"logs","checks"),n=be.join(i,`${e.operationId}-${t.id}.log`);if(!np(be.resolve(e.runtimeDir),be.resolve(n)))throw new Error("Native check log path escaped the Runtime root");await bE.mkdir(i,{recursive:!0});let a=(e.now??(()=>new Date))(),o=NE(n,{flags:"wx"});return new Promise((s,c)=>{let l;try{l=nl(t.executable,t.argv,{cwd:r,env:process.env})}catch(h){o.destroy(),c(h);return}let f=!1,d=null,u=setTimeout(()=>{f=!0,Ya(l).catch(()=>l.kill("SIGKILL"))},t.timeoutMs);u.unref?.(),l.stdout.pipe(o,{end:!1}),l.stderr.pipe(o,{end:!1}),l.once("error",h=>{d=h,o.write(`
182
- [comet] failed to start check: ${$t(h.message)}
183
- `)}),l.once("close",(h,v)=>{clearTimeout(u);let m=(e.now??(()=>new Date))();o.end(()=>{let p=f||d!==null||v!==null;s({id:t.id,name:t.name,argvDisplay:ol(t.argv),cwdRef:t.cwdRef,status:p?"interrupted":h===0?"passed":"failed",exitCode:h,signal:v,timedOut:f,durationMs:Math.max(0,m.getTime()-a.getTime()),startedAt:a.toISOString(),completedAt:m.toISOString(),repeatable:t.repeatable,logRef:be.relative(e.runtimeDir,n).split(be.sep).join("/")})})}),o.once("error",h=>{clearTimeout(u),Ya(l).catch(()=>l.kill("SIGKILL")),c(h)})})}import{randomUUID as PE}from"node:crypto";var op=Symbol("comet.native.trusted-execution-identity"),sp=Symbol("comet.native.trusted-verifier-envelope"),K="skill-coordinated";function cl(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} is invalid`);return e}function ll(){let e=new WeakSet;return Object.freeze({captureExecutionIdentity(t){cl(t.identityProvider,"Native identity provider");let r=Object.freeze({identityProvider:K,executionRef:cl(t.executionRef,"Native execution ref"),[op]:!0});return e.add(r),r},envelopeVerifierResponse(t){if(!e.has(t.identity))throw new Error("Native execution identity was not captured by this Runner channel");return Object.freeze({candidateId:cl(t.candidateId,"Native candidate ID"),identityProvider:t.identity.identityProvider,verifierExecutionRef:t.identity.executionRef,payload:t.payload,[sp]:!0})}})}function Za(e){return typeof e=="object"&&e!==null&&e[sp]===!0}function cp(e){return typeof e=="object"&&e!==null&&e[op]===!0}function eo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Fi(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function qi(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function er(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be non-empty text`);return e}function SE(e){if(!Array.isArray(e))throw new Error("Native Verifier acceptance must be an array");return e.map((t,r)=>{let i=eo(t,`Native Verifier acceptance ${r}`);Fi(i,["id","result","reason"],`Native Verifier acceptance ${r}`);let n=er(i.id,`Native Verifier acceptance ${r} ID`);if(!["passed","failed","blocked"].includes(String(i.result)))throw new Error(`Native Verifier acceptance ${n} result is invalid`);return{id:n,result:i.result,reason:er(i.reason,`Native Verifier acceptance ${n} reason`)}})}function EE(e){let t=eo(e,"Native Verifier final result");if(Fi(t,["iteration","attempt","verdict","acceptance","risks","summary"],"Native Verifier final result"),!["pass","fail","blocked"].includes(String(t.verdict)))throw new Error("Native Verifier verdict is invalid");if(!Array.isArray(t.risks)||!t.risks.every(r=>typeof r=="string"))throw new Error("Native Verifier risks must be text entries");return{iteration:qi(t.iteration,"Native Verifier iteration"),attempt:qi(t.attempt,"Native Verifier attempt"),verdict:t.verdict,acceptance:SE(t.acceptance),risks:t.risks,summary:er(t.summary,"Native Verifier summary")}}function xE(e,t){let r=eo(e,`Native Verifier check request ${t}`);if(Fi(r,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Verifier check request ${t}`),!Array.isArray(r.argv)||!r.argv.every(n=>typeof n=="string"))throw new Error(`Native Verifier check request ${t} argv is invalid`);if(typeof r.repeatable!="boolean")throw new Error(`Native Verifier check request ${t} repeatable is invalid`);let i=qi(r.timeoutMs,`Native Verifier check request ${t} timeout`);if(i<1)throw new Error("Native Verifier check timeout must be positive");return{id:er(r.id,`Native Verifier check request ${t} ID`),name:er(r.name,`Native Verifier check request ${t} name`),executable:er(r.executable,`Native Verifier check request ${t} executable`),argv:r.argv,cwdRef:er(r.cwdRef,`Native Verifier check request ${t} cwd`),timeoutMs:i,repeatable:r.repeatable}}function ul(e){let t=eo(e,"Native Verifier response");if(t.kind==="final-result")return Fi(t,["kind","result"],"Native Verifier response"),{kind:"final-result",result:EE(t.result)};if(t.kind==="request-checks"){if(Fi(t,["kind","iteration","attempt","checks"],"Native Verifier response"),!Array.isArray(t.checks)||t.checks.length===0)throw new Error("Native Verifier check request batch must be non-empty");return{kind:"request-checks",iteration:qi(t.iteration,"Native Verifier iteration"),attempt:qi(t.attempt,"Native Verifier attempt"),checks:t.checks.map(xE)}}throw new Error("Native Verifier response kind is invalid")}function lp(e){if(!Za(e.envelope))throw new Error("Native Verifier result must come from the trusted Runner channel");let{envelope:t,binding:r}=e;if(t.candidateId!==r.candidateId)throw new Error("Native Verifier result does not match the current candidate");if(t.identityProvider!==r.identityProvider)throw new Error("Native Verifier identity provider does not match the Builder provider");if(t.verifierExecutionRef===r.builderExecutionRef)throw new Error("Native Builder and Verifier must be different executions");let i=ul(t.payload),n=i.kind==="final-result"?i.result.iteration:i.iteration,a=i.kind==="final-result"?i.result.attempt:i.attempt;if(n!==r.iteration||a!==r.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");if(i.kind==="request-checks")return i;let o=[...r.acceptanceIds],s=i.result.acceptance.map(({id:u})=>u),c=s.filter((u,h)=>s.indexOf(u)!==h),l=s.filter(u=>!o.includes(u)),f=o.filter(u=>!s.includes(u));if(c.length>0||l.length>0||f.length>0)throw new Error(`Native Verifier acceptance coverage is invalid (duplicate: ${[...new Set(c)].join(", ")||"none"}; unknown: ${l.join(", ")||"none"}; missing: ${f.join(", ")||"none"})`);if(!r.requiredChecksPassed&&i.result.verdict==="pass")throw new Error("Native verification cannot pass before every required check succeeds");let d=i.result.acceptance.map(({result:u})=>u);if(i.result.verdict==="pass"&&d.some(u=>u!=="passed"))throw new Error("Native pass requires every acceptance criterion to pass");if(i.result.verdict==="fail"&&!d.includes("failed"))throw new Error("Native fail requires at least one failed acceptance criterion");if(i.result.verdict==="blocked"&&!d.includes("blocked"))throw new Error("Native blocked verdict requires at least one blocked acceptance criterion");return i}var Wi=3,dl=2;function ge(e){return e.state_version+1}function CE(e,t,r){let i=[...e];if(new Set(i).size!==i.length)throw new Error(`${r} contains duplicate IDs`);let n=new Set(t.map(({id:o})=>o)),a=i.filter(o=>!n.has(o));if(a.length>0)throw new Error(`${r} contains unknown IDs: ${a.join(", ")}`);return i}function fl(e){return e.map(t=>({...t,result:"pending",reason:null}))}function up(e){return e.acceptance.filter(({result:t})=>t==="pending").map(({id:t})=>t)}function RE(e){return(e??[]).map(t=>({name:O(t.name),result:t.result,note:t.note?O(t.note):null}))}function Ot(e){return{goal_cycle:e.state.loop.goal_cycle,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,outcome:e.outcome,unresolved_ids:e.unresolvedIds??[],summary:O(e.summary),completed_at:e.completedAt}}function dp(e){let t=C(e.state);if(t.phase!=="shape"||t.status!=="active")throw new Error("Native acceptance can only be confirmed from active Shape");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let r=e.acceptance.map(({id:i})=>i);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return C({...t,phase:"build",state_version:ge(t),loop:{...t.loop,stage:"building",iteration:1,attempt:0,next_action:"submit-builder-candidate"},acceptance:e.acceptance.map(i=>({...i,result:"pending",reason:null}))})}function fp(e){let t=C(e.state),{input:r}=e;if(t.phase!=="build"||t.status!=="active")throw new Error("Native candidate can only be submitted from active Build");if(!cp(r.identity))throw new Error("Native Builder identity must come from the trusted Runner channel");if(!r.review||r.review.status!=="passed")throw new Error("Native Builder candidate requires a passed read-only review");if(r.review.reviewerExecutionRef===r.identity.executionRef)throw new Error("Native reviewer execution ref must differ from the Builder execution ref");if(t.loop.stage==="repairing"&&t.builder_handoff?.review?.reviewer_execution_ref===r.review.reviewerExecutionRef)throw new Error("Native repaired candidate requires a fresh read-only review");let i=CE(r.addressedAcceptanceIds,t.acceptance,"Native Builder addressed acceptance"),n=new Set([...t.loop.previous_unresolved_ids,...i]),a=t.loop.stage==="repairing"&&t.loop.previous_unresolved_ids.length>0?t.acceptance.map(s=>n.has(s.id)?{...s,result:"pending",reason:null}:s):fl(t.acceptance),o=(r.now??new Date).toISOString();return C({...t,phase:"verify",state_version:ge(t),verification_result:"pending",verification_report:null,verification:null,blockers:[],acceptance:a,builder_handoff:{candidate_id:r.candidateId??PE(),identity_provider:r.identity.identityProvider,builder_execution_ref:r.identity.executionRef,iteration:t.loop.iteration,summary:O(r.summary),addressed_acceptance_ids:i,checks:RE(r.checks),checks_truncated:!1,known_limits:(r.knownLimits??[]).map(s=>O(s)),known_limits_truncated:!1,review:{status:"passed",summary:O(r.review.summary),reviewer_execution_ref:r.review.reviewerExecutionRef},submitted_at:o},loop:{...t.loop,stage:"verify-ready",attempt:0,execution_failure_count:0,next_action:"run-required-checks-and-dispatch-verifier"}})}function hp(e){let t=C(e);if(t.phase!=="verify"||t.status!=="active"||t.loop.stage!=="verify-ready"||t.builder_handoff===null||t.builder_handoff.review===null)throw new Error("Native Verifier attempt requires a reviewed Builder candidate");return C({...t,state_version:ge(t),verification:null,loop:{...t.loop,attempt:t.loop.attempt+1,next_action:"await-verifier-result"}})}function AE(e,t){let r=e.loop.previous_unresolved_ids;if(r.length===0)return 0;let i=new Set(r),n=new Set(t);return n.size<i.size&&[...n].every(o=>i.has(o))?0:e.loop.no_progress_count+1}function _E(e){return{candidate_id:e.envelope.candidateId,identity_provider:e.envelope.identityProvider,verifier_execution_ref:e.envelope.verifierExecutionRef,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,assurance:e.envelope.identityProvider===K?"skill-coordinated":"host-attested",verdict:e.response.result.verdict,checks:e.checks,summary:O(e.response.result.summary),risks:e.response.result.risks.map(t=>O(t)),risks_truncated:!1,completed_at:e.completedAt}}function pp(e){let t=C(e.state);if(t.phase!=="verify"||t.builder_handoff===null||t.loop.attempt<1)throw new Error("Native change is not awaiting a Verifier result");let r=up(t);if(r.length===0)throw new Error("Native Verifier attempt has no pending acceptance scenarios");let i=lp({envelope:e.envelope,binding:{candidateId:t.builder_handoff.candidate_id,identityProvider:t.builder_handoff.identity_provider,builderExecutionRef:t.builder_handoff.builder_execution_ref,iteration:t.loop.iteration,attempt:t.loop.attempt,acceptanceIds:r,requiredChecksPassed:e.checks.every(({status:m})=>m==="passed")}});if(i.kind==="request-checks")return{state:t,response:i};if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let n=(e.now??new Date).toISOString(),a=new Map(i.result.acceptance.map(m=>[m.id,m])),o=t.acceptance.map(m=>{let p=a.get(m.id);return p?{...m,result:p.result,reason:O(p.reason)}:m}),s=o.filter(({result:m})=>m==="failed"||m==="blocked").map(({id:m})=>m),c=_E({state:t,envelope:e.envelope,response:i,checks:e.checks,completedAt:n});if(i.result.verdict==="pass"){if(t.loop.previous_unresolved_ids.length>0){let y=Ne({...t,acceptance:o,verification:c},Ot({state:t,outcome:"recovery",summary:`Repair verification passed for ${r.join(", ")}; final full verification is required.`,completedAt:n}));return{response:i,state:C({...y,state_version:ge(t),status:"active",verification_result:"pending",verification_report:null,blockers:[],acceptance:fl(o),loop:{...t.loop,stage:"verify-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:"run-final-full-verification"}})}}let m=Ne({...t,acceptance:o,verification:c},Ot({state:t,outcome:"pass",summary:i.result.summary,completedAt:n})),p=t.builder_handoff.identity_provider===K;return{response:i,state:C({...m,phase:p?"verify":"archive",status:p?"await-user":"active",state_version:ge(t),verification_result:"pass",verification_report:"verification.md",blockers:p?[{owner:"user",reason:O("The generic Skill bridge cannot prove an independent Verifier execution; user confirmation is required before Archive."),acceptance_ids:[],resolution_action:"await-user"}]:[],loop:{...t.loop,stage:p?"await-user":"archive-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:p?"confirm-skill-coordinated-pass":"archive"}})}}if(i.result.verdict==="blocked"){let m=Ne({...t,acceptance:o,verification:c},Ot({state:t,outcome:"blocked",unresolvedIds:s,summary:i.result.summary,completedAt:n}));return{response:i,state:C({...m,status:"await-user",state_version:ge(t),verification_result:"blocked",verification_report:"verification.md",blockers:[{owner:"user",reason:O(i.result.summary),acceptance_ids:s,resolution_action:"resolve-verifier-blocker"}],loop:{...t.loop,stage:"await-user",execution_failure_count:0,previous_unresolved_ids:s,next_action:"resolve-verifier-blocker"}})}}let l=t.loop.failed_iteration_count+1,f=AE(t,s),d=l>=e.maxVerifyFailures,u=f>=3,h=d||u,v=Ne({...t,acceptance:o,verification:c},Ot({state:t,outcome:"fail",unresolvedIds:s,summary:i.result.summary,completedAt:n}));return{response:i,state:C({...v,phase:h?"verify":"build",status:h?"await-user":"active",state_version:ge(t),verification_result:"fail",verification_report:"verification.md",builder_handoff:t.builder_handoff,blockers:h?[{owner:"user",reason:O(d?"Native verification reached the configured failed iteration limit.":"Native verification did not strictly reduce the unresolved acceptance set three times."),acceptance_ids:s,resolution_action:"await-user"}]:f>=2?[{owner:"builder",reason:O("Native verification has not made reliable progress twice; use a different repair hypothesis before resubmitting."),acceptance_ids:s,resolution_action:"return-build"}]:[],loop:{...t.loop,stage:h?"await-user":"repairing",iteration:h?t.loop.iteration:t.loop.iteration+1,attempt:h?t.loop.attempt:0,failed_iteration_count:l,no_progress_count:f,execution_failure_count:0,previous_unresolved_ids:s,next_action:h?"await-user":"repair-failed-acceptance"}})}}function mp(e){let t=C(e);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="pass"||t.verification===null||t.builder_handoff?.identity_provider!==K||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-skill-coordinated-pass")throw new Error("Native change is not awaiting Skill-coordinated pass confirmation");return C({...t,phase:"archive",status:"active",state_version:ge(t),blockers:[],loop:{...t.loop,stage:"archive-ready",next_action:"archive"}})}function vp(e){let t=C(e.state);if(t.phase!=="verify"||t.status!=="active"||t.builder_handoff?.identity_provider!==K||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native semantic verification unavailability requires an active Skill attempt");if(e.checks.some(({status:a})=>a!=="passed"))throw new Error("Native semantic verification unavailability requires every resolved Runtime check to pass");let r=(e.now??new Date).toISOString(),i=up(t),n=Ne(t,Ot({state:t,outcome:"blocked",unresolvedIds:i,summary:e.summary,completedAt:r}));return C({...n,status:"await-user",state_version:ge(t),verification_result:"blocked",verification_report:"verification.md",verification:{candidate_id:t.builder_handoff.candidate_id,identity_provider:t.builder_handoff.identity_provider,verifier_execution_ref:e.verifierExecutionRef,iteration:t.loop.iteration,attempt:t.loop.attempt,assurance:"semantic-verification-unavailable",verdict:"blocked",checks:e.checks,summary:O(e.summary),risks:[O("No independent semantic Verifier execution was available; Runtime checks alone do not cover acceptance semantics.")],risks_truncated:!1,completed_at:r},blockers:[{owner:"user",reason:O("Independent semantic verification is unavailable on this platform; only completed Runtime checks are available, so explicit user confirmation is required before Archive."),acceptance_ids:i,resolution_action:"confirm-verifier-unavailable"}],loop:{...t.loop,stage:"await-user",previous_unresolved_ids:i,execution_failure_count:0,next_action:"confirm-verifier-unavailable"}})}function gp(e){let t=C(e.state);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.verification?.assurance!=="semantic-verification-unavailable"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-verifier-unavailable")throw new Error("Native change is not awaiting degraded verification confirmation");let r=(e.now??new Date).toISOString(),i=O(e.summary),n=Ne(t,Ot({state:t,outcome:"pass",summary:e.summary,completedAt:r}));return C({...n,phase:"archive",status:"active",state_version:ge(t),verification_result:"pass",verification:{...t.verification,assurance:"user-confirmed-degraded",verdict:"pass",summary:i,completed_at:r},acceptance:t.acceptance.map(a=>({...a,result:"passed",reason:O(`User confirmed degraded completion without independent semantic verification: ${e.summary}`)})),blockers:[],loop:{...t.loop,stage:"archive-ready",previous_unresolved_ids:[],next_action:"archive"}})}function wp(e){let t=C(e);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.verification?.verdict!=="blocked"||t.verification.assurance==="semantic-verification-unavailable"||t.loop.stage!=="await-user"||t.loop.next_action!=="resolve-verifier-blocker"||!t.blockers.some(({resolution_action:r})=>r==="resolve-verifier-blocker"))throw new Error("Native change is not awaiting resolution of a semantic Verifier blocker");return C({...t,status:"active",state_version:ge(t),verification_result:"pending",verification_report:null,verification:null,acceptance:t.acceptance.map(r=>r.result==="failed"||r.result==="blocked"?{...r,result:"pending",reason:null}:r),blockers:[],loop:{...t.loop,stage:"verify-ready",retry_epoch:t.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function yp(e){let t=C(e.state);if(t.phase!=="verify"||t.status!=="active"||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier execution error requires an active Verify attempt");let r=(e.now??new Date).toISOString(),i=t.loop.execution_failure_count+1,n=i>=Wi,a=Ne(t,Ot({state:t,outcome:"execution-error",summary:e.summary,completedAt:r}));return C({...a,status:n?"blocked":"active",state_version:ge(t),blockers:n?[{owner:"runtime",reason:O(e.summary),acceptance_ids:[],resolution_action:"retry-verifier"}]:[],loop:{...t.loop,stage:n?"blocked":"verify-ready",execution_failure_count:i,next_action:n?"retry-verifier":"dispatch-new-verifier"}})}function Np(e){let t=C(e);if(t.phase!=="verify"||t.status!=="blocked"||!t.blockers.some(({resolution_action:r})=>r==="retry-verifier"))throw new Error("Native change is not blocked on Verifier infrastructure");return C({...t,status:"active",state_version:ge(t),blockers:[],loop:{...t.loop,stage:"verify-ready",retry_epoch:t.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function zi(e){let t=C(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let r=(e.now??new Date).toISOString(),i=Ne(t,Ot({state:t,outcome:"recovery",summary:e.reason,completedAt:r})),n=new Set(t.loop.previous_unresolved_ids),a=n.size===0?fl(t.acceptance):t.acceptance.map(o=>n.has(o.id)?{...o,result:"pending",reason:null}:o);return C({...i,phase:"build",status:"active",state_version:ge(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:t.builder_handoff,blockers:[],acceptance:a,loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,next_action:"submit-builder-candidate"}})}import{promises as kp}from"node:fs";import Ji from"node:path";function to(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ro(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function et(e,t,r=!1){if(typeof e!="string"||!r&&e.length===0)throw new Error(`${t} must be ${r?"a string":"a non-empty string"}`);return e}function bp(e,t){return e===null?null:et(e,t)}function no(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function IE(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 TE(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function io(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function hl(e,t){if(e===null)return null;let r=et(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function pl(e,t){let r=et(e,t);if(!Ji.isAbsolute(r))throw new Error(`${t} must be absolute`);return Ji.resolve(r)}function jE(e,t){let r=`Native local checks[${t}]`,i=to(e,r);if(ro(i,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),r),!Array.isArray(i.argv)||i.argv.length===0)throw new Error(`${r}.argv must be a non-empty array`);let n=i.argv.map((l,f)=>et(l,`${r}.argv[${f}]`,!0)),a=io(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=hl(i.startedAt,`${r}.startedAt`),s=hl(i.completedAt,`${r}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${r} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${r} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${r} completed check requires startedAt and completedAt`);let c=no(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);return{id:et(i.id,`${r}.id`),name:et(i.name,`${r}.name`),operationId:et(i.operationId,`${r}.operationId`),status:a,repeatable:TE(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:no(i.executionCount,`${r}.executionCount`),argv:n,cwd:pl(i.cwd,`${r}.cwd`),exitCode:IE(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:et(i.log,`${r}.log`)}}function ml(e){let t="Native local execution state",r=to(e,t);if(ro(r,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),r.schema!==Pi)throw new Error(`Native local execution schema must be ${Pi}`);let i=to(r.workspace,"Native local workspace");ro(i,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(r.execution!==null){let o=to(r.execution,"Native local execution");ro(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=hl(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:et(o.operationId,"Native local execution.operationId"),stage:io(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:io(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:bp(o.executionId,"Native local execution.executionId"),status:io(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:no(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(jE);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:Pi,change:et(r.change,"Native local change"),basedOnStateVersion:no(r.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:pl(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:pl(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:bp(i.branch,"Native local workspace.branch")},execution:n,checks:a}}function oe(e){return ml({schema:Pi,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:Ji.resolve(e.projectRoot),worktreeRoot:Ji.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function tt(e){let t;try{t=await kp.readFile(e,"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}let r;try{r=JSON.parse(t)}catch(i){throw new Error(`Native local execution state is invalid JSON: ${i.message}`,{cause:i})}return ml(r)}async function L(e,t,r={}){let i=ml(t);await kp.mkdir(Ji.dirname(e),{recursive:!0}),await me(e,i,r)}async function vl(e){let t=null,r=null;try{t=await tt(e.file),t===null&&(r="missing")}catch(n){if(n.code)throw n;r="invalid"}if(t&&(t.change!==e.portableState.name||t.basedOnStateVersion!==e.portableState.state_version)&&(r="version-mismatch"),t&&r===null)return{state:t,rebuilt:!1,reason:null};let i=oe(e);return await L(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{}}),{state:i,rebuilt:!0,reason:r??"missing"}}import{promises as $E}from"node:fs";function Ht(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
184
- `).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function dt(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function OE(e){return e.archived?Be(e.language,"Archived","已归档"):e.phase==="verify"&&e.loop.next_action==="confirm-skill-coordinated-pass"?Be(e.language,"Verification passed; your confirmation is required","验收通过,需要你确认"):e.phase==="archive"&&e.loop.next_action==="archive"?Be(e.language,"Verification passed; ready to archive","验收通过,可归档"):Be(e.language,"Verification passed","验收通过")}function HE(e){let t=e.language;return e.verification?.assurance==="semantic-verification-unavailable"?Be(t,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查"):e.verification_result==="pass"?OE(e):e.verification_result==="blocked"?Be(t,"Blocked","已阻塞"):e.verification_result==="fail"?Be(t,"Failed","未通过"):Be(t,"Pending","待处理")}function DE(e){let t=e.verification?.assurance??(e.builder_handoff?.identity_provider===K?K:"host-attested"),r=t===K&&(e.archived||e.phase==="archive"&&e.loop.next_action==="archive");return(e.language==="en"?{"host-attested":"Host independently verified","skill-coordinated":r?"Checks completed; result confirmed":"Checks completed, but your confirmation is required","semantic-verification-unavailable":"Full verification was unavailable; only automatic checks completed","user-confirmed-degraded":"You accepted the incomplete verification result"}:{"host-attested":"已完成独立验证","skill-coordinated":r?"已完成检查,验证结果已确认":"已完成检查,但需要你确认验证结果","semantic-verification-unavailable":"无法完成完整验证,只完成了自动检查","user-confirmed-degraded":"你已确认接受不完整验证结果"})[t]??t}function BE(e,t){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let r=e.language,i=d=>Pc(r,d),n=(d,u)=>Be(r,d,u),a=e.acceptance.map(d=>`| ${dt(d.id)} | ${dt(d.result)} | ${dt(d.source)} | ${dt(d.text)} | ${dt(Ht(d.reason))} |`).join(`
185
- `),o=e.verification.checks.length===0?`_${n("No Runtime checks were recorded.","没有记录 Runtime 检查。")}_`:[`| ${n("Check","检查")} | ${n("Command","命令")} | ${n("Working directory","工作目录")} | ${n("Status","状态")} | ${n("Exit","退出码")} | ${n("Duration","耗时")} |`,"| --- | --- | --- | --- | ---: | ---: |",...e.verification.checks.map(d=>{let u=d.argv_display.map(Ht).join(" ");return`| ${dt(Ht(d.name))} | ${dt(u||"—")} | ${dt(d.cwd_ref)} | ${d.status} | ${d.exit_code??"—"} | ${d.duration_ms} ms |`})].join(`
186
- `),s=e.blockers.length===0?`_${n("None.","无。")}_`:e.blockers.map(d=>`- **${d.owner}**: ${Ht(d.reason)}${d.acceptance_ids.length>0?` (acceptance: ${d.acceptance_ids.join(", ")})`:""} — next: \`${d.resolution_action}\``).join(`
187
- `),c=e.verification.risks.length===0?`_${n("None reported.","未报告风险。")}_`:e.verification.risks.map(d=>`- ${Ht(d)}`).join(`
188
- `),l=e.history.length===0?`_${n("No previous iterations.","没有之前的迭代。")}_`:[`| ${n("Goal cycle","目标周期")} | ${n("Iteration","迭代")} | ${n("Attempt","尝试")} | ${n("Outcome","结果")} | ${n("Unresolved","未解决项")} | ${n("Summary","摘要")} | ${n("Completed","完成时间")} |`,"| ---: | ---: | ---: | --- | --- | --- | --- |",...e.history.map(d=>`| ${d.goal_cycle} | ${d.iteration} | ${d.attempt} | ${d.outcome} | ${d.unresolved_ids.join(", ")||"—"} | ${dt(Ht(d.summary))} | ${d.completed_at} |`)].join(`
180
+ `;return await Wi.appendFile(o,`${c}${i}
181
+ `,"utf8"),!0}function GS(e,t,r){let i=se.resolve(e,r??se.join(".worktrees",t)),n=se.resolve(e,_(e,["rev-parse","--git-common-dir"]));if(Yp(n,i))throw new Error("Native worktree path cannot be inside the Git common directory");if(Kt(e).some(a=>Zc(a,i)))throw new Error(`Native worktree path is already registered: ${i}`);return i}async function US(e){try{throw await Wi.lstat(e),new Error(`Native worktree path already exists: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t}}async function Kp(e){try{return await Wi.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function el(e){let t=se.resolve(e.projectRoot);if(e.isolation==="current"){if(e.changeBranch||e.targetBranch||e.worktreePath)throw new Error("Native current isolation does not accept --change-branch, --target-branch, or --worktree-path");let i=W(t);if(i.isGitWorktree&&i.currentBranch===null)throw new Error("Native workspace binding requires a branch; detached HEAD is not supported");return{projectRoot:t,binding:{isolation:"current",changeBranch:i.currentBranch,targetBranch:i.currentBranch},preparation:{isolation:"current",projectRoot:t,changeBranch:i.currentBranch,targetBranch:i.currentBranch,worktreePath:null,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1}}}let r=await Ot(t,e.sourceConfig?.native.artifact_root??"docs");return cp([{runtimeDir:r.runtimeDir,locksDir:r.locksDir}],`prepare Native ${e.isolation} workspace`,async()=>{let i=W(t);if(!i.isGitWorktree||i.currentBranch===null||i.primaryWorktreeRoot===null||i.currentWorktreeRoot===null)throw new Error("Native branch and worktree isolation require an attached Git branch");let n=e.changeBranch??`comet/${e.name}`;lc(t,n);let a=i.currentBranch===n,o=e.targetBranch??(a?void 0:i.currentBranch);if(!o)throw new Error("Native isolated workspace already on its change branch requires --target-branch");if(lc(t,o),!br(t,o))throw new Error(`Native target branch is not a verified local branch: ${o}`);if(e.isolation==="branch"){if(e.worktreePath)throw new Error("--worktree-path is only valid with --isolation worktree");let p=!1;if(!a){if(!ut(t))throw new Error("Native branch isolation requires a clean current working directory");if(br(t,n))throw new Error(`Native change branch already exists: ${n}`);_(t,["switch","-c",n,o]),p=!0}let v;try{v=await eo(t,e.sourceConfig)}catch(m){throw new Dt(`Native branch preparation is incomplete: ${m.message}`,{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:p,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:m})}return{projectRoot:t,binding:{isolation:"branch",changeBranch:n,targetBranch:o},preparation:{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:p,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}if(a){if(!i.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree");let p=e.worktreePath?se.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(p&&!Zc(p,i.currentWorktreeRoot))throw new Error(`Native worktree path ${p} does not match the current worktree ${i.currentWorktreeRoot}`);let v;try{v=await eo(t,e.sourceConfig)}catch(m){throw new Dt(`Native worktree preparation is incomplete: ${m.message}`,{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:m})}return{projectRoot:t,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}let s=ua(i.primaryWorktreeRoot),c=s.find(p=>p.branch===n);if(c&&await Kp(c.root)){let p=e.worktreePath?se.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(p&&!Zc(p,c.root))throw new Error(`Native worktree branch ${n} is already checked out at ${c.root}`);let v;try{v=await eo(c.root,e.sourceConfig)}catch(m){throw new Dt(`Native worktree preparation is incomplete: ${m.message}`,{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:m})}return{projectRoot:c.root,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}c&&!await Kp(c.root)&&(_(i.primaryWorktreeRoot,["worktree","prune"]),s=ua(i.primaryWorktreeRoot));let l=br(t,n);if(s.some(p=>p.branch===n))throw new Error(`Native change branch ${n} is already registered to a worktree`);let f=GS(i.primaryWorktreeRoot,e.name,e.worktreePath);await US(f);let u=await JS(i.primaryWorktreeRoot,f),d={isolation:"worktree",projectRoot:f,changeBranch:n,targetBranch:o,worktreePath:f,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:u,configInitialized:!1};try{_(i.primaryWorktreeRoot,l?["worktree","add",f,n]:["worktree","add","-b",n,f,o]),d.createdBranch=!l,d.createdWorktree=!0,d.configInitialized=await eo(f,e.sourceConfig)}catch(p){throw new Dt(`Native worktree preparation is incomplete: ${p.message}`,d,{cause:p})}return{projectRoot:f,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:d}})}var tl="comet.native.supervisor.v2",YS=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function Qp(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`}async function Zp(e){let t=rr.join(".worktrees",`${e.parent}-integration`);return el({projectRoot:e.projectRoot,name:`${e.parent}-integration`,isolation:"worktree",changeBranch:Qp(e.parent),targetBranch:e.targetBranch,worktreePath:t,sourceConfig:e.sourceConfig})}async function XS(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.parent)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.child))throw new Error("Native Supervisor parent and child names are invalid");return el({projectRoot:e.projectRoot,name:`${e.parent}-${e.child}`,isolation:"worktree",changeBranch:`comet/supervisor/${e.parent}/${e.child}`,targetBranch:e.targetBranch,worktreePath:rr.join(".worktrees",`${e.parent}-${e.child}`),sourceConfig:e.sourceConfig})}function QS(e,t){return rr.join(Ve(e,t),"supervisor")}function to(e,t){return rr.join(QS(e,t),"state.json")}function eh(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!==tl)throw new Error(`Native Supervisor state schema must be ${tl}`);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(Bt(t.integration.targetCommit,"Native Supervisor target commit"),Bt(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 r=new Set,i=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(r.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(r.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&&Bt(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(Bt(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),i.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(i.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 U(e,t){try{let r=await Xp.readFile(to(e,t),"utf8"),i=JSON.parse(r);return eh(i),i}catch(r){if(r.code==="ENOENT")return null;throw r}}async function ie(e,t){eh(t),await Xp.mkdir(e.changesRuntimeDir,{recursive:!0}),await ge(to(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function Bt(e,t){if(!YS.test(e))throw new Error(`${t} must be a Git commit`)}function ze(e){return structuredClone(e)}function it(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function ZS(e,t){for(let r of t.dependsOn){let i=e.children.find(({name:n})=>n===r);if(!i||i.status!=="integrated")throw new Error(`Native Supervisor child ${t.name} dependency ${r} is not integrated`)}}function eE(e){let t=new Set(e.children.map(({name:i})=>i)),r=[];for(;t.size>0;){let i=e.children.find(n=>t.has(n.name)&&n.dependsOn.every(a=>!t.has(a)));if(!i)throw new Error("Native Supervisor Child dependencies contain a cycle");r.push(i),t.delete(i.name)}return r}function rl(e){Bt(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:i})=>i)),r=e.contract.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.depends_on],status:i.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 i of r)for(let n of i.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${i.name} depends on unknown child ${n}`);return{schema:tl,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:r,history:[],finalVerification:{status:"pending",summary:null}}}async function ro(e){let t=Qp(e.parent),r=kr(e.paths.projectRoot,t);if(!r)return null;let i=kr(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=Kt(e.paths.projectRoot).map(o=>rr.resolve(o)).find(o=>W(o).currentBranch===t);if(!n)return null;let a=rl({parent:e.parent,targetBranch:e.targetBranch,targetCommit:i,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(r!==i){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=r}return it(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function th(e){let t=ze(e.state),r=new Map(e.contract.children.map(n=>[n.name,n])),i=new Map(t.children.map(n=>[n.name,n]));for(let n of t.children){let a=r.get(n.name);if(!a){if(n.status!=="archived")throw new Error(`Native Supervisor child ${n.name} cannot be removed before Archive`);continue}if((n.status==="integrated"||n.status==="archived")&&(a.summary!==n.summary||a.depends_on.join("\0")!==n.dependsOn.join("\0")))throw new Error(`Native Supervisor integrated child ${n.name} history is immutable`);n.summary=a.summary,n.dependsOn=[...a.depends_on]}for(let n of e.contract.children)i.has(n.name)||t.children.push({name:n.name,summary:n.summary,dependsOn:[...n.depends_on],status:n.depends_on.every(a=>t.children.some(({name:o,status:s})=>o===a&&s==="integrated"))?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null});return t.stateVersion+=1,t}function il(e,t){if(!t.projectRoot.trim()||!t.runId.trim())throw new Error("Native Supervisor task projectRoot and runId are required");let r=ze(e),i=r.children.find(({name:o})=>o===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(i.task)throw new Error(`Native Supervisor child ${t.child} already has an active task`);let n;if(t.role==="builder"){if(i.status!=="ready")throw new Error(`Native Supervisor child ${t.child} is not ready for a Builder task`);ZS(r,i),n=r.integration.headCommit,i.status="active"}else{if(i.status!=="active"&&i.status!=="needs-reverify"||!i.candidateCommit)throw new Error(`Native Supervisor child ${t.child} is not ready for a Verifier task`);n=i.candidateCommit}let a={...t,baseCommit:n};return i.projectRoot=t.projectRoot,i.task=a,i.blocker=null,it(r,{kind:"task-dispatched",child:i.name,runId:a.runId,summary:`${a.role} task dispatched`}),r.stateVersion+=1,{state:r,task:a}}function tE(e,t){let r=e.children.find(({name:i})=>i===t.child);if(!r?.task||r.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return structuredClone(r.task)}function rh(e,t){let r=tE(e,t),i=ze(e);return it(i,{kind:"task-reconnected",child:t.child,runId:t.runId,summary:"existing task reconnected"}),i.stateVersion+=1,{state:i,task:r}}function rE(e,t,r){let i=W(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor child worktree identity is not ${t}`);if(!ut(e))throw new Error(`Native Supervisor child worktree is not clean: ${e}`);let n=_(e,["rev-parse","HEAD"]);if(n===r)return;if(!(()=>{try{return _(e,["merge-base","--is-ancestor",n,r]),!0}catch{return!1}})())throw new Error(`Native Supervisor child worktree ${e} cannot be refreshed from integration HEAD`);if((()=>{try{return _(e,["merge-base","--is-ancestor",r,n]),!0}catch{return!1}})())throw new Error(`Native Supervisor child worktree ${e} contains unintegrated commits`);if(_(e,["merge","--ff-only",r]),_(e,["rev-parse","HEAD"])!==r)throw new Error("Native Supervisor child worktree did not reach integration HEAD")}function nl(e){if(!ut(e.integration.worktree))throw new Error("Native Supervisor integration worktree must be clean");let t=_(e.integration.worktree,["rev-parse","--show-toplevel"]);if(rr.resolve(t)!==rr.resolve(e.integration.worktree))throw new Error("Native Supervisor integration worktree identity is invalid");let r=_(e.integration.worktree,["branch","--show-current"]);if(r!==e.integration.branch)throw new Error(`Native Supervisor integration branch mismatch: expected ${e.integration.branch}, got ${r||"(detached)"}`);return _(e.integration.worktree,["rev-parse","HEAD"])}function iE(e,t,r){let i=W(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor Verifier worktree identity is not ${t}`);if(!ut(e))throw new Error(`Native Supervisor Verifier worktree is not clean: ${e}`);if(_(e,["rev-parse","HEAD"])!==r)throw new Error("Native Supervisor Verifier worktree is not at its candidate commit")}function al(e,t){if(t.reason.trim().length===0)throw new Error("Native Supervisor cancellation reason is required");let r=ze(e),i=r.children.find(({name:n})=>n===t.child);if(!i?.task||i.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return i.task.role==="builder"?(i.status="ready",i.candidateCommit=null):i.status="needs-reverify",i.task=null,i.blocker=t.reason,it(r,{kind:"task-cancelled",child:t.child,runId:t.runId,summary:t.reason}),r.stateVersion+=1,r}function io(e,t){if(t.reason.trim().length===0)throw new Error("Native Supervisor blocker reason is required");let r=ze(e),i=r.children.find(({name:n})=>n===t.child);if(!i?.task||i.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return i.blocker=t.reason,it(r,{kind:"task-blocked",child:t.child,runId:t.runId,summary:t.reason}),r.stateVersion+=1,r}async function ih(e){return x(e.paths,`dispatch Native Supervisor children ${e.parent}`,async()=>{let t=await U(e.paths,e.parent);if(!t)throw new Error(`Native Supervisor state is missing for ${e.parent}`);let r=e.maxParallel??2;if(!Number.isSafeInteger(r)||r<1)throw new Error("Native Supervisor maxParallel must be a positive integer");let i=t.children.filter(({task:l})=>l!==null).length,n=Math.max(0,r-i);if(n===0)return{state:t,tasks:[]};let a=await we(e.paths.projectRoot),o=t,s=[],c=!1;for(let l of t.children){if(s.length>=n)break;if(l.task!==null)continue;let f=l.status==="needs-reverify"&&l.candidateCommit!==null;if(l.status!=="ready"&&!f)continue;let u;try{u=await XS({projectRoot:e.paths.projectRoot,parent:t.parent,child:l.name,targetBranch:t.integration.branch,sourceConfig:a}),f?iE(u.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,l.candidateCommit):rE(u.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,t.integration.headCommit)}catch(p){let v=ze(o),m=v.children.find(({name:h})=>h===l.name);m&&(m.blocker=p.message,it(v,{kind:"task-blocked",child:l.name,runId:null,summary:m.blocker}),v.stateVersion+=1,o=v,c=!0);continue}let d=il(o,{role:f?"verifier":"builder",child:l.name,projectRoot:u.projectRoot,runId:KS()});o=d.state,s.push(d.task)}return(s.length>0||c)&&await ie(e.paths,o),{state:o,tasks:s}})}function nh(e,t){Bt(t.candidateCommit,"Native Supervisor candidate commit");let r=ze(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(!i.task||i.task.role!=="builder"||i.task.runId!==t.runId)throw new Error(`Native Supervisor Builder result runId is not current for ${t.child}`);if(i.status!=="active")throw new Error(`Native Supervisor child ${t.child} is not active for Builder result`);return i.candidateCommit=t.candidateCommit,i.task=null,i.blocker=null,it(r,{kind:"builder-result",child:i.name,runId:t.runId,summary:"Builder candidate recorded"}),r.stateVersion+=1,r}function ah(e,t){if(t.evidence.summary.trim().length===0)throw new Error("Native Supervisor verification summary must not be empty");if(t.verdict==="pass"&&t.evidence.checks.length===0)throw new Error("Native Supervisor verification pass requires at least one check");let r=ze(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(!i.task||i.task.role!=="verifier"||i.task.runId!==t.runId)throw new Error(`Native Supervisor Verifier result runId is not current for ${t.child}`);if(i.status!=="active"&&i.status!=="needs-reverify"||!i.candidateCommit)throw new Error(`Native Supervisor child ${t.child} is not ready for Verifier result`);return i.verification={summary:t.evidence.summary,checks:[...t.evidence.checks]},i.task=null,t.verdict==="pass"?(i.status="verified",i.verifiedCommit=i.candidateCommit,i.blocker=null):(i.status="needs-reverify",i.blocker=t.evidence.summary),it(r,{kind:"verifier-result",child:i.name,runId:t.runId,summary:t.evidence.summary}),r.stateVersion+=1,r}function nE(e,t){Bt(t.integrationCommit,"Native Supervisor integration commit");let r=ze(e),i=r.children.find(({name:n})=>n===t.name);if(!i)throw new Error(`Native Supervisor child ${t.name} does not exist`);if(i.status!=="verified"||!i.verifiedCommit)throw new Error(`Native Supervisor child ${t.name} must be verified before integration`);if(t.checks.length===0||t.checks.some(({status:n})=>n!=="passed"))throw new Error(`Native Supervisor child ${t.name} integration checks are incomplete`);i.status="integrated",i.integrationCommit=t.integrationCommit,i.checks=structuredClone(t.checks),i.blocker=null,r.integration.headCommit=t.integrationCommit,it(r,{kind:"child-integrated",child:i.name,runId:null,summary:"Child integrated into the Supervisor branch"});for(let n of r.children)n.status==="pending"&&n.dependsOn.every(a=>r.children.some(({name:o,status:s})=>o===a&&s==="integrated"))&&(n.status="ready");return r.stateVersion+=1,r}async function oh(e){return x(e.paths,`integrate Native Supervisor child ${e.name}`,async()=>{let r=await U(e.paths,e.state.parent)??e.state;if(r.stateVersion!==e.state.stateVersion)throw new Error("Native Supervisor state changed before integration; reload status first");let i=r.children.find(({name:c})=>c===e.name);if(!i)throw new Error(`Native Supervisor child ${e.name} does not exist`);let n=eE(r).find(({status:c})=>c!=="integrated"&&c!=="archived");if(n&&n.name!==e.name)throw new Error(`Native Supervisor integration order requires ${n.name} before ${e.name}`);if(i.status!=="verified"||!i.verifiedCommit)throw new Error(`Native Supervisor child ${e.name} must be verified before integration`);let a=nl(r);if(a!==r.integration.headCommit){let c=(()=>{try{return _(r.integration.worktree,["merge-base","--is-ancestor",r.integration.headCommit,a]),!0}catch{return!1}})(),l=(()=>{try{return _(r.integration.worktree,["merge-base","--is-ancestor",i.verifiedCommit,a]),!0}catch{return!1}})();if(!c||!l)throw new Error(`Native Supervisor integration head drifted: expected ${r.integration.headCommit}, got ${a}`)}try{_(r.integration.worktree,["cat-file","-e",`${i.verifiedCommit}^{commit}`])}catch(c){throw new Error(`Native Supervisor verified commit is unavailable: ${i.verifiedCommit}`,{cause:c})}if(a===r.integration.headCommit){try{_(r.integration.worktree,["merge","--no-ff","--no-edit",i.verifiedCommit])}catch(c){throw new Error(`Native Supervisor integration conflict preserved in ${r.integration.worktree}`,{cause:c})}a=_(r.integration.worktree,["rev-parse","HEAD"])}let o=a,s=nE(r,{name:e.name,integrationCommit:o,checks:e.checks});return await ie(e.paths,s),s})}function aE(e,t){if(Bt(t.headCommit,"Native Supervisor final verification head commit"),t.summary.trim().length===0)throw new Error("Native Supervisor final verification summary must not be empty");let r=ze(e);if(t.headCommit!==r.integration.headCommit)throw new Error("Native Supervisor final verification head is stale");if(t.status==="passed"){if(r.children.some(({status:i})=>i!=="integrated"))throw new Error("Native Supervisor cannot pass final verification before all children integrate");if(t.layers.parentChecks.length===0)throw new Error("Native Supervisor parent verification requires executed parent checks");if(t.layers.childVerification!=="complete"||t.layers.parentIntegration!=="complete"||t.layers.incomplete.length>0)throw new Error("Native Supervisor final verification evidence is incomplete")}return r.finalVerification={status:t.status,summary:t.summary,layers:{childVerification:t.layers.childVerification,parentIntegration:t.layers.parentIntegration,parentChecks:[...t.layers.parentChecks],notRerun:[...t.layers.notRerun],incomplete:[...t.layers.incomplete]}},r.stateVersion+=1,r}function zi(e){let t=nl(e);if(t===e.integration.headCommit)return e;try{_(e.integration.worktree,["merge-base","--is-ancestor",e.integration.headCommit,t])}catch{throw new Error("Native Supervisor integration head is not a descendant of the recorded integration head")}let r=ze(e);return r.integration.headCommit=t,it(r,{kind:"integration-head-reconciled",child:null,runId:null,summary:"Parent-level commits were included in final verification"}),r.stateVersion+=1,r}function Ji(e,t){let r=t.verification;if(r===null||t.verification_result==="pending")throw new Error("Native Supervisor final verification has no persisted Portable result");let i=nl(e),n=e.children.every(({status:o,verification:s})=>(o==="integrated"||o==="archived")&&s!==null),a=r.checks.length>0&&r.checks.every(({status:o})=>o==="passed");return aE(e,{status:t.verification_result==="pass"?"passed":t.verification_result==="blocked"?"incomplete":"failed",summary:r.summary.text,headCommit:i,layers:{childVerification:n?"complete":"incomplete",parentIntegration:a?"complete":"incomplete",parentChecks:r.checks.map(({name:o})=>o.text),notRerun:e.children.flatMap(({verification:o})=>o?.checks??[]),incomplete:r.checks.filter(({status:o})=>o!=="passed").map(({name:o})=>o.text)}})}function sh(e){let t=e.children.map(r=>({name:r.name,summary:r.summary,dependsOn:[...r.dependsOn],covers:[],status:r.status,phase:null,projectRoot:r.projectRoot??r.task?.projectRoot??null,message:r.blocker}));return{contractHash:null,confirmed:!0,parentBranch:e.integration.branch,children:t,readyChildren:t.filter(({status:r})=>r==="ready").map(({name:r})=>r),allDone:t.every(({status:r})=>r==="integrated"||r==="archived")}}var ch="children.yaml",Gi="comet.native.children.v1",Dr="comet.native.children.v2",vh=Dr,oE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,lh=new Set(["schema","children"]),sE=new Set(["schema","acceptance_index","children"]),cE=new Set(["name","depends_on","covers"]),lE=new Set(["name","summary","depends_on"]),uE=new Set(["name","depends_on","covers"]);function ao(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function no(e,t,r){let i=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(i.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...i.length>0?[`unexpected ${i.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${r} fields are invalid: ${a.join("; ")}`)}}function uh(e,t){if(!Array.isArray(e)||!e.every(r=>typeof r=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((r,i)=>r.localeCompare(i,"en"))}function ol(e,t){let r=Ie.normalize(Ie.resolve(e)),i=Ie.normalize(Ie.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function dE(e){let t=new Map(e.map(a=>[a.name,a])),r=new Set,i=new Set,n=a=>{if(!i.has(a)){if(r.has(a))throw new Error(`Native children dependency cycle includes ${a}`);r.add(a);for(let o of t.get(a).depends_on)n(o);r.delete(a),i.add(a)}};for(let a of e)n(a.name)}function dh(e,t,r=t){let i=new Set(t);for(let o of e){let s=o.covers.filter(c=>!i.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=r.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function fE(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===vh&&e.acceptance_index){let n=r.requiredAcceptanceIds??t??[],a=r.allowedAcceptanceIds??n,o=Object.keys(e.acceptance_index);i.missing=n.filter(l=>!(l in e.acceptance_index)),i.extra=o.filter(l=>!a.includes(l));let s=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of o){let f=s.get(l),u=e.acceptance_index[l];f&&u&&(u.source!==f.source||u.text!==f.text)&&i.mismatched.push(l)}let c=new Set(o);for(let l of e.children)i.unknownCovers.push(...l.covers.filter(f=>!c.has(f)));return i.uncovered=o.filter(l=>!fh(e.children,l)),ph(i)?i:null}if(e.schema===Gi&&t){let n=new Set(t);for(let a of e.children)i.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return i.uncovered=t.filter(a=>!fh(e.children,a)),ph(i)?i:null}return null}function fh(e,t){return e.some(r=>r.covers.includes(t))}function ph(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function Ui(e){let t=new Set(e.acceptance.map(({id:n})=>n)),r=new Set(e.acceptance.filter(({source:n})=>n===e.brief).map(({id:n})=>n)),i=new Set(r);for(let n of e.history.filter(({outcome:a})=>a==="fail"))for(let a of n.unresolved_ids)t.has(a)&&i.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??[])r.add(a)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...r],allowedAcceptanceIds:[...i]}}function pE(e){let t=ao(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),r={};for(let[i,n]of Object.entries(t)){let a=ao(n,`Native children acceptance_index.${i}`);if(no(a,new Set(["source","text"]),`Native children acceptance_index.${i}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${i}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${i}.text must be a non-empty string`);r[i]={source:a.source,text:a.text}}return r}function hE(e,t,r){let i=r.requiredAcceptanceIds??t??[],n=r.allowedAcceptanceIds??i,a=Object.keys(e),o=i.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((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of a){let f=c.get(l);if(!f)continue;let u=e[l];if(u.source!==f.source||u.text!==f.text){let d=["source","text"].filter(p=>u[p]!==f[p]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${d.join(", ")} exactly from the current acceptance catalog`)}}}function mE(e,t,r={}){let i=(0,sl.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=ao(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==Gi&&a!==Dr)throw no(n,lh,"Native children contract"),new Error(`Native children schema must be ${Gi} or ${Dr}`);let o=a===Gi?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(no(n,o==="indexed-v2"?sE:lh,"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,p)=>{let v=ao(d,`Native child ${p}`);if(no(v,o==="indexed-v2"?uE:o==="summary-v2"?lE:cE,`Native ${s} child fields (child ${p})`),typeof v.name!="string"||!oE.test(v.name))throw new Error(`Native child ${p} name is invalid`);let m=o==="summary-v2";if(m){if(typeof v.summary!="string"||v.summary.trim().length===0)throw new Error(`Native child ${v.name} summary must be a non-empty string`);if(v.summary.length>2e3)throw new Error(`Native child ${v.name} summary exceeds 2000 characters`)}return{name:v.name,summary:m?v.summary:null,depends_on:uh(v.depends_on,`Native child ${v.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?uh(v.covers,`Native child ${v.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 f=new Set(l);for(let d of c){let p=d.depends_on.filter(v=>!f.has(v));if(p.length>0)throw new Error(`Native child ${d.name} depends on unknown child: ${p.join(", ")}`)}dE(c);let u=r.policy==="advisory";if(a===vh){if(o==="indexed-v2"){let d=pE(n.acceptance_index);u||hE(d,t,r);let p=Object.keys(d);return u||dh(c,p,p),{schema:Dr,acceptance_index:d,children:c}}return{schema:Dr,children:c}}return t&&!u&&dh(c,t),{schema:Gi,children:c}}async function Ki(e){let t=Ie.join(e.changeDir,ch);try{await mh.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await Y({root:e.changeDir,ref:ch}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=mE(r.text,e.acceptanceIds,n);return{contract:a,size:r.size,drift:i?fE(a,e.acceptanceIds,e.validation??{}):null}}function vE(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let r=e.slice(t.index+t[0].length);return r.split(/^#\s+/mu,1)[0]??r}function gE(e){let t=vE(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let r=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),i=t.match(/\bChild\s+\d+\b/giu);return Math.max(r?.length??0,i?.length??0)>=2}async function cl(e){try{let t=await Y({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return gE(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function oo(e){return ve("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:r,text:i})=>({id:t,source:r,text:i})),children:e.children})}async function wE(e){let t=Kt(e.projectRoot);t.some(i=>ol(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>Ie.resolve(n)))]){let n=await we(i);n&&r.push({projectRoot:i,paths:await Ot(i,n.native.artifact_root),parent:ol(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function yE(e,t){let r=Ie.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Me(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function NE(e,t){let r;try{r=await mh.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=Ie.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await Me(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function bE(e,t,r){let i=Ie.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${Ie.sep}`))return null;let n=i.split(Ie.sep).join("/");try{let a=(0,sl.parseDocument)(_(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:P(a.toJS({mapAsMap:!1}))}catch{return null}}function kE(e,t,r){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==r||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 ${r??"(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 hh(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function nt(e){let t=Ie.join(e.paths.changesDir,e.state.name),r=await cl(t),i=await Ki({changeDir:t,validation:Ui(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:h})=>h)}:{},policy:"advisory"});if(!i)return e.state.children_contract_hash?{...r?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:r?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null;let n=oo({acceptance:e.state.acceptance,children:i.contract}),a=e.state.workspace.change_branch,o=e.state.phase!=="shape"&&e.state.children_contract_hash===n&&!i.drift;if(i.contract.schema===Dr){let h=await U(e.paths,e.state.name);if(!h){let y=e.state.workspace.target_branch??e.state.workspace.change_branch;if(y){let S=await ro({paths:e.paths,parent:e.state.name,targetBranch:y,contract:i.contract});S&&(h=S,await ie(e.paths,S))}}if(h){let y=sh(h);return e.state.children_contract_hash!==n||i.drift?{...y,schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:!1,readyChildren:[],allDone:!1,children:y.children.map(S=>({...S,message:i.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...y,schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o}}let g=new Map(i.contract.children.map(y=>[y.name,y])),w=i.contract.children.map(y=>({name:y.name,summary:y.summary,dependsOn:[...y.depends_on],covers:[],status:o&&y.depends_on.every(S=>i.contract.children.filter(({name:N})=>N!==y.name).every(({name:N})=>N!==S))?"ready":"pending",phase:null,projectRoot:null,message:o?null:"Parent Shape confirmation is required"}));for(let y of w){if(y.status!=="ready")continue;g.get(y.name).depends_on.length>0&&(y.status="pending")}return{schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:w,readyChildren:w.filter(({status:y})=>y==="ready").map(({name:y})=>y),allDone:!1}}let s=await wE(e.paths),c=new Set(i.contract.children.map(({name:h})=>h)),l=new Map,f=new Map;for(let h of s){let g=h.parent&&a?`refs/heads/${a}`:"HEAD";for(let w of await NE(h,c)){let y={...w,source:h,committedState:bE(h,w.file,g)};l.set(w.state.name,[...l.get(w.state.name)??[],y])}for(let w of c){let y=await yE(h,w);y&&f.set(w,[...f.get(w)??[],{source:h,state:y}])}}let u=new Map;for(let h of i.contract.children){let g=(l.get(h.name)??[]).find(({source:S,committedState:N})=>S.parent&&N?.name===h.name&&hh(N,a));if(g){u.set(h.name,{kind:"done",phase:g.state.phase,projectRoot:g.source.projectRoot,message:null});continue}let w=l.get(h.name)?.[0];if(w){u.set(h.name,{kind:"blocked",phase:w.state.phase,projectRoot:w.source.projectRoot,message:`Native child ${h.name} is archived but not merged into parent branch ${a??"(missing)"}`});continue}let y=f.get(h.name)??[];y.length>1?u.set(h.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${h.name} has multiple active workspace owners`}):y[0]&&u.set(h.name,kE(y[0].state,y[0].source,a))}let d=new Map(i.contract.children.map(h=>[h.name,h])),p=new Map,v=h=>{let g=p.get(h);if(g)return g;let w=d.get(h),S=w.depends_on.map(v).every(({status:F})=>F==="done"),N=u.get(h),E=N?.kind==="active"&&S?w.depends_on.filter(F=>!(l.get(F)??[]).some(({source:Z,committedState:j})=>ol(Z.projectRoot,N.projectRoot)&&j?.name===F&&hh(j,a))):[],C,b=N?.message??null;N?.kind==="done"?(C=S?"done":"blocked",S||(b=`Native child ${h} was merged before its dependencies`)):N?.kind==="active"?(C=S&&E.length===0?"active":"blocked",S?E.length>0&&(b=`Native child ${h} does not include merged dependencies: ${E.join(", ")}`):b=`Native child ${h} started before its dependencies merged`):N?.kind==="blocked"?C="blocked":(C=o&&S?"ready":"pending",o||(b="Parent Shape confirmation is required"));let T={name:h,summary:w.summary,dependsOn:[...w.depends_on],covers:[...w.covers],status:C,phase:N?.phase??null,projectRoot:N?.projectRoot??null,message:b};return p.set(h,T),T},m=i.contract.children.map(({name:h})=>v(h));return{schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:m,readyChildren:m.filter(({status:h})=>h==="ready").map(({name:h})=>h),allDone:m.every(({status:h})=>h==="done")}}function ir(e,t,r){return e.language==="zh-CN"?r:t}function SE(e,t){let r=i=>({required:!1,message:null,suggestedReply:null,agentInstruction:i});if(t&&e.phase==="shape"&&e.status==="active")return{required:!0,message:ir(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:ir(e,"Reply A or B","回复 A 或 B"),agentInstruction:ir(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 r(ir(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 r(ir(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:i})=>i==="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 r(ir(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 gh(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Yi(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function wh(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function EE(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function xE(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function CE(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 nr(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:gh({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Yi("summary","--summary"),wh(e.name,e.flag)]}}function ll(e){return[nr({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),nr({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function X(e,t){let r=xE(t)&&e.coordination_mode===void 0,i={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],userCommunication:SE(e,r)},n=a=>({kind:a,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...i,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:n("none")};if(e.status==="await-user")return e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...i,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Yi("summary","--summary")],commandAlternatives:[nr({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...ll({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"?{...i,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Yi("summary","--summary")],commandAlternatives:[nr({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),nr({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"?{...i,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Yi("summary","--summary")],commandAlternatives:[nr({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...ll({change:e.name,stateVersion:e.state_version})],runnerAction:n("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...i,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Yi("summary","--summary")],commandAlternatives:ll({change:e.name,stateVersion:e.state_version}),runnerAction:n("none")}:{...i,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{...i,disposition:"blocked",action:a?"retry-verifier":"none",commandArgs:a?gh({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{...i,disposition:r?"await-user":"continue",action:"confirm-shape",commandArgs:CE({change:e.name,stateVersion:e.state_version,coordinationRequired:r}),requiredInputs:["summary",...r?["coordination-choice"]:[],"shared-understanding-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},...r?[EE("coordination-mode","--coordination-mode",Ra)]:[],wh("confirmed","--confirmed")],runnerAction:n("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...i,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:n("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...i,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:n("none")};if(t.allDone)return{...i,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{...i,disposition:a&&!o?"blocked":"continue",action:"advance-children",commandArgs:null,requiredInputs:a&&!o?["resolve-child-blocker"]:["ready-children"],inputOptions:[],runnerAction:n("none")}}return{...i,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],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{...i,userCommunication:!a&&o?{...i.userCommunication,agentInstruction:`${i.userCommunication.agentInstruction} ${ir(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:i.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?{...i,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],commandAlternatives:[nr({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:n("none")}:{...i,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:n("none")}}import{randomUUID as Sx}from"node:crypto";import{promises as on}from"node:fs";import Ex from"node:path";import{randomUUID as Pl}from"node:crypto";import{promises as sr}from"node:fs";import ne from"node:path";import{createWriteStream as GE,promises as UE}from"node:fs";import Se from"node:path";import{spawn as ul}from"node:child_process";import{existsSync as yh}from"node:fs";import ar from"node:path";var PE=new Set([".bat",".cmd",".ps1"]),RE=new Set([".bat",".cmd"]),AE=/[&|<>()^%"!\r\n]/u,_E=["$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("; ");function dl(e,t){let r=t.toLowerCase();return Object.entries(e).find(([i,n])=>i.toLowerCase()===r&&n!==void 0)?.[1]}function IE(e){let t=(dl(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function TE(e,t,r){let n=ar.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(dl(t,"PATH")??"").split(ar.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=ar.win32.extname(e)?[e]:IE(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(c=>s?ar.join(s,c):ar.resolve(r,c)))}function jE(e,t,r){return TE(e,t,r).find(i=>yh(i))??e}function $E(e){let t=dl(e,"SystemRoot");if(t){let r=ar.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe");if(yh(r))return r}return"powershell.exe"}function OE(e){if(e.some(t=>AE.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}function HE(e,t,r){let i=Buffer.from(JSON.stringify({command:e,arguments:[...t]}),"utf8").toString("base64"),n=Buffer.from(_E,"utf16le").toString("base64");return ul($E(r.env),["-NoLogo","-NoProfile","-NonInteractive","-InputFormat","None","-OutputFormat","Text","-ExecutionPolicy","Bypass","-EncodedCommand",n],{cwd:r.cwd,env:{...r.env,COMET_COMMAND_PAYLOAD:i},shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}function fl(e,t,r){let i=r.env??process.env;if(process.platform!=="win32")return ul(e,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});let n=jE(e,i,r.cwd),a=ar.win32.extname(n).toLowerCase();return RE.has(a)&&OE(t),PE.has(a)?HE(n,t,{cwd:r.cwd,env:i}):ul(n,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}import{spawn as DE}from"node:child_process";import pl from"node:path";var BE=1e3,LE=2;async function so(e){let t=e.pid;if(t===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let r=process.env.SystemRoot??process.env.WINDIR,i=r&&pl.win32.isAbsolute(r)?pl.win32.resolve(r):"C:\\Windows",n=pl.win32.join(i,"System32","taskkill.exe"),a=()=>new Promise(o=>{let s=!1,c=null,l=null,f=(u,d=!1)=>{s||(s=!0,l&&clearTimeout(l),d&&c?.kill("SIGKILL"),o(u))};try{c=DE(n,["/pid",String(t),"/t","/f"],{stdio:"ignore",windowsHide:!0}),c.once("error",()=>f(!1)),c.once("close",u=>f(u===0)),l=setTimeout(()=>f(!1,!0),BE)}catch{f(!1)}});for(let o=0;o<LE;o+=1)if(await a()){e.kill("SIGKILL");return}e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy();return}try{process.kill(-t,"SIGKILL")}catch(r){if(r.code!=="ESRCH")throw r}e.kill("SIGKILL")}var VE=/\b(Bearer|Basic)\s+[^\s"']+/giu,ME=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,FE=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,qE=/\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,WE=/("(?:[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,zE=/(["'])((?:[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,JE=/\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 Lt(e){return e.replace(VE,"$1 [REDACTED]").replace(ME,"[REDACTED PRIVATE KEY]").replace(FE,"$1[REDACTED]@").replace(qE,"[REDACTED TOKEN]").replace(WE,'$1"[REDACTED]"').replace(zE,"$1$2$1$3$4[REDACTED]$4").replace(JE,"$1$2[REDACTED]")}function Nh(e,t){let r=Se.relative(e,t);return r===""||!Se.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Se.sep}`)}function bh(e,t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(e))throw new Error(`${t} is invalid`);return e}function co(e,t){if(t.length===0||t.includes("\\")||Se.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||Se.posix.normalize(t)!==t)throw new Error("Native check cwd must be a normalized project-relative ref");let r=Se.resolve(e),i=Se.resolve(r,...t.split("/"));if(!Nh(r,i))throw new Error("Native check cwd escaped the project root");return i}function Xi(e){return JSON.stringify([e.executable,e.argv,e.cwdRef.replaceAll("\\","/"),e.timeoutMs,e.repeatable])}var KE=/^(?:-p|-u|--(?:[a-z0-9]+[-_])*(?:api[-_]?key|access[-_]?token|auth[-_]?token|client[-_]?secret|secret(?:[-_]?access)?[-_]?key|private[-_]?key|token|password|passwd|secret|authorization|cookie|set[-_]?cookie|user))$/iu;function hl(e){let t=!1;return e.map(r=>{if(t)return t=!1,"[REDACTED]";let i=Lt(r);return KE.test(r)&&(t=!0),i})}function lo(e,t){if(bh(t.id,"Native check ID"),t.name.trim().length===0||t.executable.trim().length===0)throw new Error("Native check name and executable must be non-empty");if(!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<1)throw new Error("Native check timeout must be a positive integer");return co(e,t.cwdRef)}async function ml(e){let{plan:t}=e;bh(e.operationId,"Native check operation ID");let r=lo(e.projectRoot,t),i=Se.join(e.runtimeDir,"logs","checks"),n=Se.join(i,`${e.operationId}-${t.id}.log`);if(!Nh(Se.resolve(e.runtimeDir),Se.resolve(n)))throw new Error("Native check log path escaped the Runtime root");await UE.mkdir(i,{recursive:!0});let a=(e.now??(()=>new Date))(),o=GE(n,{flags:"wx"});return new Promise((s,c)=>{let l;try{l=fl(t.executable,t.argv,{cwd:r,env:process.env})}catch(p){o.destroy(),c(p);return}let f=!1,u=null,d=setTimeout(()=>{f=!0,so(l).catch(()=>l.kill("SIGKILL"))},t.timeoutMs);d.unref?.(),l.stdout.pipe(o,{end:!1}),l.stderr.pipe(o,{end:!1}),l.once("error",p=>{u=p,o.write(`
182
+ [comet] failed to start check: ${Lt(p.message)}
183
+ `)}),l.once("close",(p,v)=>{clearTimeout(d);let m=(e.now??(()=>new Date))();o.end(()=>{let h=f||u!==null||v!==null;s({id:t.id,name:t.name,argvDisplay:hl(t.argv),cwdRef:t.cwdRef,status:h?"interrupted":p===0?"passed":"failed",exitCode:p,signal:v,timedOut:f,durationMs:Math.max(0,m.getTime()-a.getTime()),startedAt:a.toISOString(),completedAt:m.toISOString(),repeatable:t.repeatable,logRef:Se.relative(e.runtimeDir,n).split(Se.sep).join("/")})})}),o.once("error",p=>{clearTimeout(d),so(l).catch(()=>l.kill("SIGKILL")),c(p)})})}import{randomUUID as ZE}from"node:crypto";var kh=Symbol("comet.native.trusted-execution-identity"),Sh=Symbol("comet.native.trusted-verifier-envelope"),Q="skill-coordinated";function vl(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} is invalid`);return e}function gl(){let e=new WeakSet;return Object.freeze({captureExecutionIdentity(t){vl(t.identityProvider,"Native identity provider");let r=Object.freeze({identityProvider:Q,executionRef:vl(t.executionRef,"Native execution ref"),[kh]:!0});return e.add(r),r},envelopeVerifierResponse(t){if(!e.has(t.identity))throw new Error("Native execution identity was not captured by this Runner channel");return Object.freeze({candidateId:vl(t.candidateId,"Native candidate ID"),identityProvider:t.identity.identityProvider,verifierExecutionRef:t.identity.executionRef,payload:t.payload,[Sh]:!0})}})}function uo(e){return typeof e=="object"&&e!==null&&e[Sh]===!0}function Eh(e){return typeof e=="object"&&e!==null&&e[kh]===!0}function fo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Qi(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function Zi(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function or(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be non-empty text`);return e}function YE(e){if(!Array.isArray(e))throw new Error("Native Verifier acceptance must be an array");return e.map((t,r)=>{let i=fo(t,`Native Verifier acceptance ${r}`);Qi(i,["id","result","reason"],`Native Verifier acceptance ${r}`);let n=or(i.id,`Native Verifier acceptance ${r} ID`);if(!["passed","failed","blocked"].includes(String(i.result)))throw new Error(`Native Verifier acceptance ${n} result is invalid`);return{id:n,result:i.result,reason:or(i.reason,`Native Verifier acceptance ${n} reason`)}})}function XE(e){let t=fo(e,"Native Verifier final result");if(Qi(t,["iteration","attempt","verdict","acceptance","risks","summary"],"Native Verifier final result"),!["pass","fail","blocked"].includes(String(t.verdict)))throw new Error("Native Verifier verdict is invalid");if(!Array.isArray(t.risks)||!t.risks.every(r=>typeof r=="string"))throw new Error("Native Verifier risks must be text entries");return{iteration:Zi(t.iteration,"Native Verifier iteration"),attempt:Zi(t.attempt,"Native Verifier attempt"),verdict:t.verdict,acceptance:YE(t.acceptance),risks:t.risks,summary:or(t.summary,"Native Verifier summary")}}function QE(e,t){let r=fo(e,`Native Verifier check request ${t}`);if(Qi(r,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Verifier check request ${t}`),!Array.isArray(r.argv)||!r.argv.every(n=>typeof n=="string"))throw new Error(`Native Verifier check request ${t} argv is invalid`);if(typeof r.repeatable!="boolean")throw new Error(`Native Verifier check request ${t} repeatable is invalid`);let i=Zi(r.timeoutMs,`Native Verifier check request ${t} timeout`);if(i<1)throw new Error("Native Verifier check timeout must be positive");return{id:or(r.id,`Native Verifier check request ${t} ID`),name:or(r.name,`Native Verifier check request ${t} name`),executable:or(r.executable,`Native Verifier check request ${t} executable`),argv:r.argv,cwdRef:or(r.cwdRef,`Native Verifier check request ${t} cwd`),timeoutMs:i,repeatable:r.repeatable}}function wl(e){let t=fo(e,"Native Verifier response");if(t.kind==="final-result")return Qi(t,["kind","result"],"Native Verifier response"),{kind:"final-result",result:XE(t.result)};if(t.kind==="request-checks"){if(Qi(t,["kind","iteration","attempt","checks"],"Native Verifier response"),!Array.isArray(t.checks)||t.checks.length===0)throw new Error("Native Verifier check request batch must be non-empty");return{kind:"request-checks",iteration:Zi(t.iteration,"Native Verifier iteration"),attempt:Zi(t.attempt,"Native Verifier attempt"),checks:t.checks.map(QE)}}throw new Error("Native Verifier response kind is invalid")}function xh(e){if(!uo(e.envelope))throw new Error("Native Verifier result must come from the trusted Runner channel");let{envelope:t,binding:r}=e;if(t.candidateId!==r.candidateId)throw new Error("Native Verifier result does not match the current candidate");if(t.identityProvider!==r.identityProvider)throw new Error("Native Verifier identity provider does not match the Builder provider");if(t.verifierExecutionRef===r.builderExecutionRef)throw new Error("Native Builder and Verifier must be different executions");let i=wl(t.payload),n=i.kind==="final-result"?i.result.iteration:i.iteration,a=i.kind==="final-result"?i.result.attempt:i.attempt;if(n!==r.iteration||a!==r.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");if(i.kind==="request-checks")return i;let o=[...r.acceptanceIds],s=i.result.acceptance.map(({id:d})=>d),c=s.filter((d,p)=>s.indexOf(d)!==p),l=s.filter(d=>!o.includes(d)),f=o.filter(d=>!s.includes(d));if(c.length>0||l.length>0||f.length>0)throw new Error(`Native Verifier acceptance coverage is invalid (duplicate: ${[...new Set(c)].join(", ")||"none"}; unknown: ${l.join(", ")||"none"}; missing: ${f.join(", ")||"none"})`);if(!r.requiredChecksPassed&&i.result.verdict==="pass")throw new Error("Native verification cannot pass before every required check succeeds");let u=i.result.acceptance.map(({result:d})=>d);if(i.result.verdict==="pass"&&u.some(d=>d!=="passed"))throw new Error("Native pass requires every acceptance criterion to pass");if(i.result.verdict==="fail"&&!u.includes("failed"))throw new Error("Native fail requires at least one failed acceptance criterion");if(i.result.verdict==="blocked"&&!u.includes("blocked"))throw new Error("Native blocked verdict requires at least one blocked acceptance criterion");return i}var en=3,yl=2;function ye(e){return e.state_version+1}function ex(e,t,r){let i=[...e];if(new Set(i).size!==i.length)throw new Error(`${r} contains duplicate IDs`);let n=new Set(t.map(({id:o})=>o)),a=i.filter(o=>!n.has(o));if(a.length>0)throw new Error(`${r} contains unknown IDs: ${a.join(", ")}`);return i}function Nl(e){return e.map(t=>({...t,result:"pending",reason:null}))}function bl(e){return e.acceptance.filter(({result:t})=>t==="pending").map(({id:t})=>t)}function tx(e){return(e??[]).map(t=>({name:H(t.name),result:t.result,note:t.note?H(t.note):null}))}function ht(e){return{goal_cycle:e.state.loop.goal_cycle,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,outcome:e.outcome,unresolved_ids:e.unresolvedIds??[],summary:H(e.summary),completed_at:e.completedAt}}function Ch(e){let t=P(e.state);if(t.phase!=="shape"||t.status!=="active")throw new Error("Native acceptance can only be confirmed from active Shape");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let r=e.acceptance.map(({id:i})=>i);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return P({...t,phase:"build",state_version:ye(t),loop:{...t.loop,stage:"building",iteration:1,attempt:0,next_action:"submit-builder-candidate"},acceptance:e.acceptance.map(i=>({...i,result:"pending",reason:null}))})}function Ph(e){let t=P(e.state),{input:r}=e;if(t.phase!=="build"||t.status!=="active")throw new Error("Native candidate can only be submitted from active Build");if(!Eh(r.identity))throw new Error("Native Builder identity must come from the trusted Runner channel");if(!r.review||r.review.status!=="passed")throw new Error("Native Builder candidate requires a passed read-only review");if(r.review.reviewerExecutionRef===r.identity.executionRef)throw new Error("Native reviewer execution ref must differ from the Builder execution ref");if(t.loop.stage==="repairing"&&t.builder_handoff?.review?.reviewer_execution_ref===r.review.reviewerExecutionRef)throw new Error("Native repaired candidate requires a fresh read-only review");let i=ex(r.addressedAcceptanceIds,t.acceptance,"Native Builder addressed acceptance"),n=new Set([...t.loop.previous_unresolved_ids,...i]),a=t.loop.stage==="repairing"&&t.loop.previous_unresolved_ids.length>0?t.acceptance.map(s=>n.has(s.id)?{...s,result:"pending",reason:null}:s):Nl(t.acceptance),o=(r.now??new Date).toISOString();return P({...t,phase:"verify",state_version:ye(t),verification_result:"pending",verification_report:null,verification:null,blockers:[],acceptance:a,builder_handoff:{candidate_id:r.candidateId??ZE(),identity_provider:r.identity.identityProvider,builder_execution_ref:r.identity.executionRef,iteration:t.loop.iteration,summary:H(r.summary),addressed_acceptance_ids:i,checks:tx(r.checks),checks_truncated:!1,known_limits:(r.knownLimits??[]).map(s=>H(s)),known_limits_truncated:!1,review:{status:"passed",summary:H(r.review.summary),reviewer_execution_ref:r.review.reviewerExecutionRef},submitted_at:o},loop:{...t.loop,stage:"verify-ready",attempt:0,execution_failure_count:0,next_action:"run-required-checks-and-dispatch-verifier"}})}function Rh(e){let t=P(e);if(t.phase!=="verify"||t.status!=="active"||t.loop.stage!=="verify-ready"||t.builder_handoff===null||t.builder_handoff.review===null)throw new Error("Native Verifier attempt requires a reviewed Builder candidate");return P({...t,state_version:ye(t),verification:null,loop:{...t.loop,attempt:t.loop.attempt+1,next_action:"await-verifier-result"}})}function rx(e,t){let r=e.loop.previous_unresolved_ids;if(r.length===0)return 0;let i=new Set(r),n=new Set(t);return n.size<i.size&&[...n].every(o=>i.has(o))?0:e.loop.no_progress_count+1}function ix(e){return{candidate_id:e.envelope.candidateId,identity_provider:e.envelope.identityProvider,verifier_execution_ref:e.envelope.verifierExecutionRef,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,assurance:e.envelope.identityProvider===Q?"skill-coordinated":"host-attested",verdict:e.response.result.verdict,checks:e.checks,summary:H(e.response.result.summary),risks:e.response.result.risks.map(t=>H(t)),risks_truncated:!1,completed_at:e.completedAt}}function Ah(e){let t=P(e.state);if(t.phase!=="verify"||t.builder_handoff===null||t.loop.attempt<1)throw new Error("Native change is not awaiting a Verifier result");let r=bl(t);if(r.length===0)throw new Error("Native Verifier attempt has no pending acceptance scenarios");let i=xh({envelope:e.envelope,binding:{candidateId:t.builder_handoff.candidate_id,identityProvider:t.builder_handoff.identity_provider,builderExecutionRef:t.builder_handoff.builder_execution_ref,iteration:t.loop.iteration,attempt:t.loop.attempt,acceptanceIds:r,requiredChecksPassed:e.checks.every(({status:h})=>h==="passed")}});if(i.kind==="request-checks")return{state:t,response:i};if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let n=(e.now??new Date).toISOString(),a=new Map(i.result.acceptance.map(h=>[h.id,h])),o=t.acceptance.map(h=>{let g=a.get(h.id);return g?{...h,result:g.result,reason:H(g.reason)}:h}),s=o.filter(({result:h})=>h==="failed"||h==="blocked").map(({id:h})=>h),c=ix({state:t,envelope:e.envelope,response:i,checks:e.checks,completedAt:n});if(i.result.verdict==="pass"){if(t.loop.previous_unresolved_ids.length>0){let w=de({...t,acceptance:o,verification:c},ht({state:t,outcome:"recovery",summary:`Repair verification passed for ${r.join(", ")}; final full verification is required.`,completedAt:n}));return{response:i,state:P({...w,state_version:ye(t),status:"active",verification_result:"pending",verification_report:null,blockers:[],acceptance:Nl(o),loop:{...t.loop,stage:"verify-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:"run-final-full-verification"}})}}let h=de({...t,acceptance:o,verification:c},ht({state:t,outcome:"pass",summary:i.result.summary,completedAt:n})),g=t.builder_handoff.identity_provider===Q;return{response:i,state:P({...h,phase:g?"verify":"archive",status:g?"await-user":"active",state_version:ye(t),verification_result:"pass",verification_report:"verification.md",blockers:g?[{owner:"user",reason:H("The generic Skill bridge cannot prove an independent Verifier execution; user confirmation is required before Archive."),acceptance_ids:[],resolution_action:"await-user"}]:[],loop:{...t.loop,stage:g?"await-user":"archive-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:g?"confirm-skill-coordinated-pass":"archive"}})}}if(i.result.verdict==="blocked"){let h=de({...t,acceptance:o,verification:c},ht({state:t,outcome:"blocked",unresolvedIds:s,summary:i.result.summary,completedAt:n}));return{response:i,state:P({...h,status:"await-user",state_version:ye(t),verification_result:"blocked",verification_report:"verification.md",blockers:[{owner:"user",reason:H(i.result.summary),acceptance_ids:s,resolution_action:"resolve-verifier-blocker"}],loop:{...t.loop,stage:"await-user",execution_failure_count:0,previous_unresolved_ids:s,next_action:"resolve-verifier-blocker"}})}}let l=t.loop.failed_iteration_count+1,f=rx(t,s),u=l>=e.maxVerifyFailures,d=f>=3,p=u||d,v=d?"stalled":u?"budget":void 0,m=de({...t,acceptance:o,verification:c},ht({state:t,outcome:"fail",unresolvedIds:s,summary:i.result.summary,completedAt:n}));return{response:i,state:P({...m,phase:p?"verify":"build",status:p?"await-user":"active",state_version:ye(t),verification_result:"fail",verification_report:"verification.md",builder_handoff:t.builder_handoff,blockers:p?[{owner:"user",reason:H(v==="budget"?"Native verification reached the configured failed iteration limit.":"Native verification did not strictly reduce the unresolved acceptance set three times."),acceptance_ids:s,resolution_action:"await-user"}]:f>=2?[{owner:"builder",reason:H("Native verification has not made reliable progress twice; use a different repair hypothesis before resubmitting."),acceptance_ids:s,resolution_action:"return-build"}]:[],loop:{...t.loop,stage:p?"await-user":"repairing",iteration:p?t.loop.iteration:t.loop.iteration+1,attempt:p?t.loop.attempt:0,failed_iteration_count:l,no_progress_count:f,...v===void 0?{}:{stop_reason:v},execution_failure_count:0,previous_unresolved_ids:s,next_action:p?"await-user":"repair-failed-acceptance"}})}}function _h(e){let t=P(e);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="pass"||t.verification===null||t.builder_handoff?.identity_provider!==Q||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-skill-coordinated-pass")throw new Error("Native change is not awaiting Skill-coordinated pass confirmation");return P({...t,phase:"archive",status:"active",state_version:ye(t),blockers:[],loop:{...t.loop,stage:"archive-ready",next_action:"archive"}})}function Ih(e){let t=P(e.state);if(t.phase!=="verify"||t.status!=="active"||t.builder_handoff?.identity_provider!==Q||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native semantic verification unavailability requires an active Skill attempt");if(e.checks.some(({status:a})=>a!=="passed"))throw new Error("Native semantic verification unavailability requires every resolved Runtime check to pass");let r=(e.now??new Date).toISOString(),i=bl(t),n=de(t,ht({state:t,outcome:"blocked",unresolvedIds:i,summary:e.summary,completedAt:r}));return P({...n,status:"await-user",state_version:ye(t),verification_result:"blocked",verification_report:"verification.md",verification:{candidate_id:t.builder_handoff.candidate_id,identity_provider:t.builder_handoff.identity_provider,verifier_execution_ref:e.verifierExecutionRef,iteration:t.loop.iteration,attempt:t.loop.attempt,assurance:"semantic-verification-unavailable",verdict:"blocked",checks:e.checks,summary:H(e.summary),risks:[H("No independent semantic Verifier execution was available; Runtime checks alone do not cover acceptance semantics.")],risks_truncated:!1,completed_at:r},blockers:[{owner:"user",reason:H("Independent semantic verification is unavailable on this platform; only completed Runtime checks are available, so explicit user confirmation is required before Archive."),acceptance_ids:i,resolution_action:"confirm-verifier-unavailable"}],loop:{...t.loop,stage:"await-user",previous_unresolved_ids:i,execution_failure_count:0,next_action:"confirm-verifier-unavailable"}})}function Th(e){let t=P(e.state);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.verification?.assurance!=="semantic-verification-unavailable"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-verifier-unavailable")throw new Error("Native change is not awaiting degraded verification confirmation");let r=(e.now??new Date).toISOString(),i=H(e.summary),n=de(t,ht({state:t,outcome:"pass",summary:e.summary,completedAt:r}));return P({...n,phase:"archive",status:"active",state_version:ye(t),verification_result:"pass",verification:{...t.verification,assurance:"user-confirmed-degraded",verdict:"pass",summary:i,completed_at:r},acceptance:t.acceptance.map(a=>({...a,result:"passed",reason:H(`User confirmed degraded completion without independent semantic verification: ${e.summary}`)})),blockers:[],loop:{...t.loop,stage:"archive-ready",previous_unresolved_ids:[],next_action:"archive"}})}function jh(e,t){let r=P(e);if(r.phase!=="verify"||r.status!=="await-user"||r.verification_result!=="blocked"||r.verification?.verdict!=="blocked"||r.verification.assurance==="semantic-verification-unavailable"||r.loop.stage!=="await-user"||r.loop.next_action!=="resolve-verifier-blocker"||!r.blockers.some(({resolution_action:n})=>n==="resolve-verifier-blocker"))throw new Error("Native change is not awaiting resolution of a semantic Verifier blocker");let i=de(r,ht({state:r,outcome:"recovery",summary:t?.reason??"Resolved the semantic Verifier blocker and resumed verification.",completedAt:(t?.now??new Date).toISOString()}));return P({...i,status:"active",state_version:ye(r),verification_result:"pending",verification_report:null,verification:null,acceptance:r.acceptance.map(n=>n.result==="failed"||n.result==="blocked"?{...n,result:"pending",reason:null}:n),blockers:[],loop:{...r.loop,stage:"verify-ready",retry_epoch:r.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function $h(e){let t=P(e.state);if(t.phase!=="verify"||t.status!=="active"||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier execution error requires an active Verify attempt");let r=(e.now??new Date).toISOString(),i=t.loop.execution_failure_count+1,n=i>=en,a=de(t,ht({state:t,outcome:"execution-error",summary:e.summary,completedAt:r}));return P({...a,status:n?"blocked":"active",state_version:ye(t),blockers:n?[{owner:"runtime",reason:H(e.summary),acceptance_ids:[],resolution_action:"retry-verifier"}]:[],loop:{...t.loop,stage:n?"blocked":"verify-ready",execution_failure_count:i,next_action:n?"retry-verifier":"dispatch-new-verifier"}})}function Oh(e){let t=P(e),r=t.status==="blocked"&&t.blockers.some(({resolution_action:o})=>o==="retry-verifier"),i=t.status==="await-user"&&t.verification_result==="blocked"&&t.verification?.assurance==="semantic-verification-unavailable"&&t.loop.stage==="await-user"&&t.loop.next_action==="confirm-verifier-unavailable"&&t.blockers.some(({resolution_action:o})=>o==="confirm-verifier-unavailable");if(t.phase!=="verify"||!r&&!i)throw new Error("Native change is not blocked on Verifier infrastructure");let n=bl(t),a=t.acceptance.some(({result:o})=>o==="passed");return P({...t,status:"active",state_version:ye(t),...i?{verification_result:"pending",verification_report:null,verification:null}:{},blockers:[],loop:{...t.loop,stage:"verify-ready",retry_epoch:t.loop.retry_epoch+1,execution_failure_count:0,...i?{previous_unresolved_ids:a?n:[]}:{},next_action:"dispatch-new-verifier"}})}function tn(e){let t=P(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let r=(e.now??new Date).toISOString(),i=de(t,ht({state:t,outcome:"recovery",summary:e.reason,completedAt:r})),n=new Set(t.loop.previous_unresolved_ids),a=n.size===0?Nl(t.acceptance):t.acceptance.map(o=>n.has(o.id)?{...o,result:"pending",reason:null}:o);return P({...i,phase:"build",status:"active",state_version:ye(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:t.builder_handoff,blockers:[],acceptance:a,loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,stop_reason:void 0,next_action:"submit-builder-candidate"}})}import{promises as Dh}from"node:fs";import rn from"node:path";function po(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ho(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function at(e,t,r=!1){if(typeof e!="string"||!r&&e.length===0)throw new Error(`${t} must be ${r?"a string":"a non-empty string"}`);return e}function Hh(e,t){return e===null?null:at(e,t)}function vo(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function nx(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 ax(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function mo(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function kl(e,t){if(e===null)return null;let r=at(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function Sl(e,t){let r=at(e,t);if(!rn.isAbsolute(r))throw new Error(`${t} must be absolute`);return rn.resolve(r)}function ox(e,t){let r=`Native local checks[${t}]`,i=po(e,r);if(ho(i,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),r),!Array.isArray(i.argv)||i.argv.length===0)throw new Error(`${r}.argv must be a non-empty array`);let n=i.argv.map((l,f)=>at(l,`${r}.argv[${f}]`,!0)),a=mo(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=kl(i.startedAt,`${r}.startedAt`),s=kl(i.completedAt,`${r}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${r} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${r} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${r} completed check requires startedAt and completedAt`);let c=vo(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);return{id:at(i.id,`${r}.id`),name:at(i.name,`${r}.name`),operationId:at(i.operationId,`${r}.operationId`),status:a,repeatable:ax(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:vo(i.executionCount,`${r}.executionCount`),argv:n,cwd:Sl(i.cwd,`${r}.cwd`),exitCode:nx(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:at(i.log,`${r}.log`)}}function El(e){let t="Native local execution state",r=po(e,t);if(ho(r,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),r.schema!==ji)throw new Error(`Native local execution schema must be ${ji}`);let i=po(r.workspace,"Native local workspace");ho(i,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(r.execution!==null){let o=po(r.execution,"Native local execution");ho(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=kl(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:at(o.operationId,"Native local execution.operationId"),stage:mo(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:mo(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Hh(o.executionId,"Native local execution.executionId"),status:mo(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:vo(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(ox);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:ji,change:at(r.change,"Native local change"),basedOnStateVersion:vo(r.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:Sl(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Sl(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Hh(i.branch,"Native local workspace.branch")},execution:n,checks:a}}function oe(e){return El({schema:ji,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:rn.resolve(e.projectRoot),worktreeRoot:rn.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function ot(e){let t;try{t=await Dh.readFile(e,"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}let r;try{r=JSON.parse(t)}catch(i){throw new Error(`Native local execution state is invalid JSON: ${i.message}`,{cause:i})}return El(r)}async function L(e,t,r={}){let i=El(t);await Dh.mkdir(rn.dirname(e),{recursive:!0}),await ge(e,i,r)}async function xl(e){let t=null,r=null;try{t=await ot(e.file),t===null&&(r="missing")}catch(n){if(n.code)throw n;r="invalid"}if(t&&(t.change!==e.portableState.name||t.basedOnStateVersion!==e.portableState.state_version)&&(r="version-mismatch"),t&&r===null)return{state:t,rebuilt:!1,reason:null};let i=oe(e);return await L(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{}}),{state:i,rebuilt:!0,reason:r??"missing"}}import{promises as sx}from"node:fs";function Vt(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
184
+ `).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function mt(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function cx(e){return e.archived?Fe(e.language,"Archived","已归档"):e.phase==="verify"&&e.loop.next_action==="confirm-skill-coordinated-pass"?Fe(e.language,"Verification passed; your confirmation is required","验收通过,需要你确认"):e.phase==="archive"&&e.loop.next_action==="archive"?Fe(e.language,"Verification passed; ready to archive","验收通过,可归档"):Fe(e.language,"Verification passed","验收通过")}function lx(e){let t=e.language;return e.verification?.assurance==="semantic-verification-unavailable"?Fe(t,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查"):e.verification_result==="pass"?cx(e):e.verification_result==="blocked"?Fe(t,"Blocked","已阻塞"):e.verification_result==="fail"?Fe(t,"Failed","未通过"):Fe(t,"Pending","待处理")}function ux(e){let t=e.verification?.assurance??(e.builder_handoff?.identity_provider===Q?Q:"host-attested"),r=t===Q&&(e.archived||e.phase==="archive"&&e.loop.next_action==="archive");return(e.language==="en"?{"host-attested":"Host independently verified","skill-coordinated":r?"Checks completed; result confirmed":"Checks completed, but your confirmation is required","semantic-verification-unavailable":"Full verification was unavailable; only automatic checks completed","user-confirmed-degraded":"You accepted the incomplete verification result"}:{"host-attested":"已完成独立验证","skill-coordinated":r?"已完成检查,验证结果已确认":"已完成检查,但需要你确认验证结果","semantic-verification-unavailable":"无法完成完整验证,只完成了自动检查","user-confirmed-degraded":"你已确认接受不完整验证结果"})[t]??t}function dx(e,t){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let r=e.language,i=u=>$c(r,u),n=(u,d)=>Fe(r,u,d),a=e.acceptance.map(u=>`| ${mt(u.id)} | ${mt(u.result)} | ${mt(u.source)} | ${mt(u.text)} | ${mt(Vt(u.reason))} |`).join(`
185
+ `),o=e.verification.checks.length===0?`_${n("No Runtime checks were recorded.","没有记录 Runtime 检查。")}_`:[`| ${n("Check","检查")} | ${n("Command","命令")} | ${n("Working directory","工作目录")} | ${n("Status","状态")} | ${n("Exit","退出码")} | ${n("Duration","耗时")} |`,"| --- | --- | --- | --- | ---: | ---: |",...e.verification.checks.map(u=>{let d=u.argv_display.map(Vt).join(" ");return`| ${mt(Vt(u.name))} | ${mt(d||"—")} | ${mt(u.cwd_ref)} | ${u.status} | ${u.exit_code??"—"} | ${u.duration_ms} ms |`})].join(`
186
+ `),s=e.blockers.length===0?`_${n("None.","无。")}_`:e.blockers.map(u=>`- **${u.owner}**: ${Vt(u.reason)}${u.acceptance_ids.length>0?` (acceptance: ${u.acceptance_ids.join(", ")})`:""} — next: \`${u.resolution_action}\``).join(`
187
+ `),c=e.verification.risks.length===0?`_${n("None reported.","未报告风险。")}_`:e.verification.risks.map(u=>`- ${Vt(u)}`).join(`
188
+ `),l=e.history.length===0?`_${n("No previous iterations.","没有之前的迭代。")}_`:[`| ${n("Goal cycle","目标周期")} | ${n("Iteration","迭代")} | ${n("Attempt","尝试")} | ${n("Outcome","结果")} | ${n("Unresolved","未解决项")} | ${n("Summary","摘要")} | ${n("Completed","完成时间")} |`,"| ---: | ---: | ---: | --- | --- | --- | --- |",...e.history.map(u=>`| ${u.goal_cycle} | ${u.iteration} | ${u.attempt} | ${u.outcome} | ${u.unresolved_ids.join(", ")||"—"} | ${mt(Vt(u.summary))} | ${u.completed_at} |`)].join(`
189
189
  `),f=t?.finalVerification.layers?`
190
190
  ## ${n("Supervisor evidence layers","Supervisor 分层证据")}
191
191
 
@@ -202,13 +202,13 @@ generated_from_state_version: ${e.state_version}
202
202
 
203
203
  ## ${i("currentResult")}
204
204
 
205
- - ${n("Result","结果")}: **${HE(e)}**
206
- - ${n("Verification status","验证情况")}: **${DE(e)}**
205
+ - ${n("Result","结果")}: **${lx(e)}**
206
+ - ${n("Verification status","验证情况")}: **${ux(e)}**
207
207
  - ${n("Goal cycle","目标周期")}: ${e.loop.goal_cycle}
208
208
  - ${n("Iteration","迭代")}: ${e.verification.iteration}
209
209
  - ${n("Verifier attempt","验证器尝试次数")}: ${e.verification.attempt}
210
210
  - ${n("Completed","完成时间")}: ${e.verification.completed_at}
211
- - ${n("Summary","摘要")}: ${Ht(e.verification.summary)}
211
+ - ${n("Summary","摘要")}: ${Vt(e.verification.summary)}
212
212
 
213
213
  ## ${i("acceptance")}
214
214
 
@@ -238,17 +238,23 @@ ${e.history_overflow.dropped_entries>0?`${n("Earlier history entries folded into
238
238
 
239
239
  `:""}## ${i("conclusion")}
240
240
 
241
- ${Ht(e.verification.summary)}
242
- `}function LE(e){let t=/^---\r?\ngenerated_from_state_version: ([1-9]\d*)\r?\n---(?:\r?\n|$)/u.exec(e);if(!t)return null;let r=Number(t[1]);return Number.isSafeInteger(r)?r:null}async function Sp(e){let t;try{t=await $E.readFile(e.file,"utf8")}catch(i){if(i.code==="ENOENT")return"missing";throw i}let r=LE(t);return r===null?"invalid":r===e.stateVersion?"aligned":"stale"}async function _r(e){await xe(e.file,BE(e.state,e.supervisor))}var xp=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,VE="comet-state.yaml",ME="state.json",r$=Pa("en");function tr(e){let t=e.expected;if(t){if(e.state.state_version!==t.stateVersion)throw new Error(`Native continuation is stale for state version ${t.stateVersion}; current state version is ${e.state.state_version}`);if(t.action!==e.action)throw new Error(`Native continuation expected ${t.action} cannot be used for ${e.action}`)}}function ue(e,t){if(!xp.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=Z.join(e.changesDir,t);if(!se(e.changesDir,r))throw new Error("Native change path escaped");return r}function Fe(e,t){return Z.join(ue(e,t),VE)}function D(e,t){return Z.join(He(e,t),ME)}async function Ui(e,t){try{let r=await Gi.readFile(Fe(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function Me(e){return F(e).currentBranch}async function j(e,t){return De(Fe(e,t))}async function ke(e){let t=await Ci({file:Fe(e.paths,e.previous.name),expectedStateVersion:e.previous.state_version,next:e.next,containedRoot:e.paths.nativeRoot});if(t.verification===null&&t.verification_report===null){let r=Z.join(ue(e.paths,t.name),"verification.md");await q(e.paths.nativeRoot,r),await Gi.rm(r,{force:!0})}return t}async function Pp(e){let t=ue(e.paths,e.state.name),r=Z.join(t,"specs"),i=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await Gi.readdir(r,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,c)=>s.name.localeCompare(c.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!xp.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(i.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,c=Z.join(t,...s.split("/")),l=await Gi.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let f=Z.join(e.paths.specsDir,o.name,"spec.md"),d="create";try{let u=await Gi.lstat(f);if(!u.isFile()||u.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);d="modify"}catch(u){if(u.code!=="ENOENT")throw u}a.push({capability:o.name,operation:d,source:s})}return a.push(...i.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function Cp(e){let t=ue(e.paths,e.state.name),r=await J({root:t,ref:"brief.md",maxBytes:null,includeHash:!1}),i=[];for(let n of e.specChanges){if(n.source===null)continue;let a=await J({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}return $a({briefMarkdown:r.text,specs:i})}async function Rp(e){return P(e.paths,`confirm portable shape ${e.name}`,async()=>{let t=await j(e.paths,e.name);tr({state:t,expected:e.expectedContinuation,action:"confirm-shape"});let r=await Pp({paths:e.paths,state:t}),i=await Cp({paths:e.paths,state:t,specChanges:r}),n=await Li({changeDir:ue(e.paths,t.name),acceptanceIds:i.map(({id:h})=>h),validation:Bi({...t,acceptance:i})});if(n&&t.workspace.change_branch===null)throw new Error("Native parent changes require a Git integration branch");let a=await Zc(ue(e.paths,t.name))||n?.contract.schema==="comet.native.children.v2"&&n.contract.children.length>=2,o=e.coordinationMode??t.coordination_mode;if(a&&!n)throw new Error("Native Supervisor Shape requires children.yaml before confirmation");if(a&&o===void 0)throw new Error("Native Supervisor Shape requires --coordination-mode multi-session or single-session");if(!a&&e.coordinationMode!==void 0)throw new Error("--coordination-mode is only valid for a multi-child Native Supervisor Shape");let s=dp({state:{...t,spec_changes:r},acceptance:i.map(h=>({...h}))});if(delete s.children_contract_hash,delete s.coordination_mode,n){s.children_contract_hash=Ua({acceptance:s.acceptance,children:n.contract}),a&&(s.coordination_mode=o);let h=[...t.history].reverse().find(({outcome:v})=>v==="pass"||v==="fail");if(h?.outcome==="fail"&&h.unresolved_ids.length>0){let v=await Ze({paths:e.paths,state:s}),m=new Set((v?.children??[]).filter(({status:y})=>y!=="done").flatMap(({covers:y})=>y)),p=h.unresolved_ids.filter(y=>!m.has(y));if(p.length>0)throw new Error(`Native parent repair plan requires an unfinished child covering: ${p.join(", ")}`)}}let c=null,l=n?.contract.schema==="comet.native.children.v2"?await re(e.paths,t.name):null,f=null,d=null;if(n?.contract.schema==="comet.native.children.v2"){if(f=t.workspace.target_branch??t.workspace.change_branch,!f)throw new Error("Native Supervisor v2 requires a target branch");if(d=mr(e.paths.projectRoot,f),!d)throw new Error(`Native Supervisor target branch has no commit: ${f}`);l||(l=await qa({paths:e.paths,parent:t.name,targetBranch:f,contract:n.contract})),l||(c=await Vh({projectRoot:e.paths.projectRoot,parent:t.name,targetBranch:f,sourceConfig:await ve(e.paths.projectRoot)}))}let u=await ke({paths:e.paths,previous:t,next:s});if(await L(D(e.paths,t.name),oe({portableState:u,projectRoot:e.paths.projectRoot,branch:Me(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n?.contract.schema==="comet.native.children.v2"&&f&&d){let h=l?Fh({state:l,contract:n.contract}):c?Uc({parent:u.name,targetBranch:f,targetCommit:d,integrationBranch:c.binding.changeBranch,integrationWorktree:c.projectRoot,contract:n.contract}):null;if(!h)throw new Error("Native Supervisor integration state is unavailable");await ae(e.paths,h)}return u})}async function co(e){let t=await Pp(e),r=e.ignoreSpecOperationFor??(e.state.children_contract_hash?new Set(e.state.spec_changes.map(({capability:c})=>c)):void 0);if(!(t.length===e.state.spec_changes.length&&t.every((c,l)=>{let f=e.state.spec_changes[l];return f!==void 0&&c.capability===f.capability&&c.source===f.source&&(c.operation===f.operation||r?.has(c.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n=await Cp({...e,specChanges:t}),a=e.state.acceptance.map(({source:c,text:l})=>({source:c,text:l}));if(!yh(a,n))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let o;try{o=await Li({changeDir:ue(e.paths,e.state.name),acceptanceIds:n.map(({id:c})=>c),validation:Bi({...e.state,acceptance:n})})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return(o?Ua({acceptance:n,children:o.contract}):null)===(e.state.children_contract_hash??null)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native child declarations changed"}}async function Dt(e){let t=await co(e);if(!t.drifted)return;let r=t.reason??"Native confirmed requirements changed";throw await Fp({paths:e.paths,state:e.state,reason:r}),new Error(`${r}; Native change returned to Shape and requires confirmation`)}async function Ap(e){return P(e.paths,`submit portable candidate ${e.name}`,async()=>{let t=await j(e.paths,e.name);if(await Dt({paths:e.paths,state:t}),await Li({changeDir:ue(e.paths,t.name),acceptanceIds:t.acceptance.map(({id:a})=>a),validation:Bi(t)})||t.children_contract_hash){let a=await Ze({paths:e.paths,state:t});if(!a?.confirmed||!a.allDone)throw new Error("Native parent Build advances child changes before parent review");if(t.loop.stage==="repairing"&&t.verification_result==="fail")throw new Error("Native parent verification failed; complete the repair child first")}let i=fp({state:t,input:e.input}),n=await ke({paths:e.paths,previous:t,next:i});return await L(D(e.paths,t.name),oe({portableState:n,projectRoot:e.paths.projectRoot,branch:Me(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function lo(e){let t=await j(e.paths,e.name),r={trigger:e.trigger,parent:e.name,advanced:!1,message:null,blocker:null};if(t.phase!=="build"||t.status!=="active")return{state:t,parentAdvance:r};let i=await Ze({paths:e.paths,state:t});if(!i||!i.confirmed||!i.allDone)return{state:t,parentAdvance:{...r,blocker:i&&!i.confirmed?"Supervisor child declarations require Shape confirmation":null}};if(t.loop.stage==="repairing"&&t.verification_result==="fail")return{state:t,parentAdvance:{...r,blocker:"Native parent verification failed; add and confirm a repair child"}};let n=t.language==="zh-CN"?"全部 Child 已完成;Supervisor 父级候选需要独立代码审查后再进入验证":"All Children are complete; the Supervisor parent candidate needs an independent code review before verification.";return{state:t,parentAdvance:{...r,message:n}}}function yl(e,t,r){return{id:e.id,name:e.name,operationId:t,status:"planned",repeatable:e.repeatable,timeoutMs:e.timeoutMs,executionCount:0,argv:[e.executable,...e.argv],cwd:Xa(r,e.cwdRef),exitCode:null,startedAt:null,completedAt:null,log:`logs/checks/${t}-${e.id}.log`}}function _p(e,t,r,i){if(!e.repeatable)throw new Error(`Native check ${e.id} was interrupted and is not repeatable; user resolution is required`);return{...yl(t,r,i),executionCount:e.executionCount}}function Ip(e,t){let r=Z.relative(Z.resolve(e),Z.resolve(t));if(Z.isAbsolute(r)||r===".."||r.startsWith(`..${Z.sep}`))throw new Error("Native local check cwd escaped the project root");let i=r.length===0?".":r.split(Z.sep).join("/");return Xa(e,i),i}function gl(e,t){let[r,...i]=e.argv;if(!r)throw new Error(`Native local check ${e.id} has no executable`);return Mi({id:e.id,name:e.id,executable:r,argv:i,cwdRef:Ip(t,e.cwd),timeoutMs:e.timeoutMs,repeatable:e.repeatable})}function FE(e){return e.startedAt===null||e.completedAt===null?0:Math.max(0,Date.parse(e.completedAt)-Date.parse(e.startedAt))}function Ir(e){let t=new Map;for(let r of e.supplied){if(t.has(r.id))throw new Error(`Native Runtime check summaries contain duplicate ID ${r.id}`);t.set(r.id,r)}return e.local.checks.map(r=>{if(r.status==="planned"||r.status==="running")throw new Error(`Native Runtime check ${r.id} has not completed`);let i=e.requestedNames?.get(r.id)??r.name;return{id:r.id,name:O(i),argv_display:ol(r.argv.slice(1)).map(n=>O(n)),argv_truncated:!1,cwd_ref:Ip(e.projectRoot,r.cwd),status:r.status,exit_code:r.exitCode,duration_ms:FE(r)}})}function qE(e){return{id:e.id,name:e.name,executable:e.executable,argv:[...e.argv],cwdRef:e.cwdRef,timeoutMs:e.timeoutMs,repeatable:e.repeatable}}function Ki(e){if(e.local===null||e.local.change!==e.state.name)return oe({portableState:e.state,projectRoot:e.projectRoot,branch:Me(e.projectRoot)});let t=e.local.execution?.operationId??wl();return{...e.local,basedOnStateVersion:e.state.state_version,execution:{operationId:t,stage:"checking",actor:"runtime",executionId:null,status:"completed",startedAt:e.local.execution?.startedAt??new Date().toISOString(),requestCheckRounds:0},checks:e.local.checks.map(r=>r.status==="running"||r.status==="planned"?{...r,operationId:t,status:"interrupted"}:{...r,operationId:t})}}async function Tr(e){try{let t=await tt(D(e.paths,e.state.name));return t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version?null:t}catch{return null}}function Tp(e){let{state:t,local:r,expected:i}=e;if(t.state_version!==i.stateVersion||t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.loop.iteration!==i.iteration||t.loop.attempt!==i.attempt||t.builder_handoff===null||r===null||r.basedOnStateVersion!==t.state_version||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running"||r.execution.executionId!==i.verifierExecutionRef)throw new Error("Native Verifier execution message is stale for the current attempt");return r}function WE(e){let{state:t,local:r,envelope:i}=e;if(!Za(i))throw new Error("Native Verifier result must come from the trusted Runner channel");if(t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.builder_handoff===null)throw new Error("Native Verifier result is stale for the current workflow state");if(i.candidateId!==t.builder_handoff.candidate_id||i.identityProvider!==t.builder_handoff.identity_provider||i.verifierExecutionRef===t.builder_handoff.builder_execution_ref)throw new Error("Native Verifier result is stale for the current candidate or identity");if(r===null||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running"||r.execution.executionId!==null&&r.execution.executionId!==i.verifierExecutionRef)throw new Error("Native Verifier result is stale for the active execution");return i}function zE(e){return e.kind==="final-result"?{iteration:e.result.iteration,attempt:e.result.attempt}:{iteration:e.iteration,attempt:e.attempt}}async function so(e){let t=await Tr({paths:e.paths,state:e.state}),r=yp({state:e.state,summary:e.summary}),i=await ke({paths:e.paths,previous:e.state,next:r});return await L(D(e.paths,e.state.name),Ki({local:t,state:i,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),i}function Ep(e,t,r){return e.checks.length!==t.length?!1:e.checks.every((i,n)=>gl(i,r)===Mi(t[n]))}async function JE(e){return P(e.paths,`reserve portable checks ${e.name}`,async()=>{let t=await j(e.paths,e.name);if(await Dt({paths:e.paths,state:t}),t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native checks require Verify ready state");let r=D(e.paths,t.name),i=(await vl({file:r,portableState:t,projectRoot:e.projectRoot,branch:Me(e.projectRoot),containedRoot:e.paths.runtimeDir})).state;if(i.execution?.stage==="checking"&&i.execution.actor==="runtime"&&Ep(i,e.plans,e.projectRoot)){let o=i.execution;if(o.status==="running")throw new Error("Native check plan is already in progress");let s=i.checks.filter(c=>c.status==="interrupted");if(s.length===0&&o.status==="completed"){let c=new Map(e.plans.map(({id:l,name:f})=>[l,f]));return{kind:"reuse",state:t,checks:Ir({local:i,projectRoot:e.projectRoot,supplied:[],requestedNames:c})}}if(s.length>0&&s.some(c=>!c.repeatable)){let c=zi({state:t,reason:`A non-repeatable Runtime check was interrupted (${s.filter(f=>!f.repeatable).map(({id:f})=>f).join(", ")}); a new Builder candidate is required before it can run again.`}),l=await ke({paths:e.paths,previous:t,next:c});throw await L(D(e.paths,t.name),oe({portableState:l,projectRoot:e.paths.projectRoot,branch:Me(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),new Error(`Native check ${s.find(f=>!f.repeatable).id} was interrupted and is not repeatable; the change returned to Build for a new candidate`)}}if(i.execution!==null&&i.checks.length>0){if(!(i.execution.stage==="checking"&&i.execution.actor==="runtime"&&i.checks.some(s=>s.status==="interrupted")&&Ep(i,e.plans,e.projectRoot)))throw new Error("Native check plan was already resolved with a different plan")}else if(i.execution!==null||i.checks.length>0)throw new Error("Native check plan was already resolved with a different plan");let n=wl(),a={...i,execution:{operationId:n,stage:"checking",actor:"runtime",executionId:null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:e.plans.map(o=>{let s=i.checks.find(c=>c.id===o.id);return s?.status==="interrupted"?_p(s,o,n,e.projectRoot):s?{...s,operationId:n}:yl(o,n,e.projectRoot)})};return await L(r,a,{containedRoot:e.paths.runtimeDir}),{kind:"execute",state:t,local:a,plans:e.plans.filter(o=>{let s=i.checks.find(c=>c.id===o.id);return s===void 0||s.status==="interrupted"})}})}async function ao(e){return P(e.paths,`update portable checks ${e.state.name}`,async()=>{let t=await j(e.paths,e.state.name);if(t.state_version!==e.state.state_version||t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native check plan state changed during execution");let r=D(e.paths,t.name),i=await tt(r);if(i===null||i.basedOnStateVersion!==t.state_version||i.execution?.operationId!==e.operationId||i.execution.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="running")throw new Error("Native check plan reservation changed during execution");let n=e.update(i);return await L(r,n,{containedRoot:e.paths.runtimeDir}),n})}async function jp(e){let t=e.projectRoot??e.paths.projectRoot;if(new Set(e.plans.map(({id:c})=>c)).size!==e.plans.length)throw new Error("Native check plan contains duplicate IDs");let r=[],i=new Set;for(let c of e.plans){Qa(t,c);let l=Mi(c);i.has(l)||(i.add(l),r.push(c))}let n=await JE({...e,plans:r,projectRoot:t});if(n.kind==="reuse")return n;let a=n.local.execution.operationId,o=He(e.paths,n.state.name);try{for(let c of n.plans){let l=new Date().toISOString();await ao({paths:e.paths,state:n.state,operationId:a,update:d=>({...d,checks:d.checks.map(u=>u.id===c.id?{...u,status:"running",executionCount:u.executionCount+1,startedAt:l}:u)})});let f=await sl({projectRoot:t,runtimeDir:o,operationId:a,plan:c});await ao({paths:e.paths,state:n.state,operationId:a,update:d=>({...d,checks:d.checks.map(u=>u.id===c.id?{...u,status:f.status,exitCode:f.exitCode,startedAt:f.startedAt,completedAt:f.completedAt,log:f.logRef}:u)})})}await ao({paths:e.paths,state:n.state,operationId:a,update:c=>({...c,execution:{...c.execution,status:"completed"}})})}catch(c){try{await ao({paths:e.paths,state:n.state,operationId:a,update:l=>({...l,execution:{...l.execution,status:"interrupted"},checks:l.checks.map(f=>f.status==="planned"||f.status==="running"?{...f,status:"interrupted"}:f)})})}catch{}throw c}let s=await tt(D(e.paths,n.state.name));if(s===null)throw new Error("Native Runtime check state disappeared after execution");return{state:n.state,checks:Ir({local:s,projectRoot:t,supplied:[]})}}async function GE(e){let t=D(e.paths,e.state.name),r=e.local;if(r===null||r.change!==e.state.name||r.basedOnStateVersion!==e.state.state_version||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running")throw new Error("Native Verifier request-checks has no active local execution");if(r.execution.executionId!==null&&r.execution.executionId!==e.envelope.verifierExecutionRef)throw new Error("Native Verifier request-checks changed execution within the same attempt");if(r.execution.requestCheckRounds>=dl)throw new Error(`Native Verifier request-checks exceeded ${dl} rounds for this attempt`);let i=new Map,n=new Map,a=new Map;for(let h of r.checks){let v=gl(h,e.projectRoot);n.set(v,h),h.status!=="interrupted"&&i.set(v,h),a.set(h.id,v)}let o=new Map,s=new Map;for(let h of e.response.checks){let v=qE(h);Qa(e.projectRoot,v);let m=Mi(v),p=s.get(v.id);if(p!==void 0&&p!==m)throw new Error(`Native Verifier check ID ${v.id} refers to conflicting commands`);let y=a.get(v.id);if(y!==void 0&&y!==m)throw new Error(`Native Verifier check ID ${v.id} conflicts with a Runtime check`);s.set(v.id,m);let g=n.get(m);if(g?.status==="interrupted"&&!g.repeatable)throw new Error(`Native check ${g.id} was interrupted and is not repeatable; user resolution is required`);o.has(m)||o.set(m,v)}let c=[...o.entries()],l=c.filter(([h])=>!i.has(h));if(r.execution.requestCheckRounds>0&&l.length===0)throw new Error("Native Verifier repeatedly requested only equivalent checks");let f=r.execution.requestCheckRounds+1,d=new Map(c.map(([,h])=>[h.id,h.name])),u={...r,execution:{...r.execution,stage:"checking",actor:"runtime",executionId:e.envelope.verifierExecutionRef,requestCheckRounds:f},checks:[...r.checks.map(h=>{let v=gl(h,e.projectRoot),m=o.get(v);return m&&h.status==="interrupted"?_p(h,m,r.execution.operationId,e.projectRoot):h}),...l.filter(([h])=>!n.has(h)).map(([,h])=>yl(h,r.execution.operationId,e.projectRoot))]};return await L(t,u,{containedRoot:e.paths.runtimeDir}),{state:e.state,local:u,verifierExecutionRef:e.envelope.verifierExecutionRef,round:f,novelPlans:l.map(([,h])=>h),requestedNames:d,reusedCheckIds:c.filter(([h])=>i.has(h)).map(([,h])=>h.id),suppliedChecks:e.suppliedChecks}}async function oo(e){return P(e.paths,`update Verifier-requested checks ${e.reservation.state.name}`,async()=>{let t=await j(e.paths,e.reservation.state.name);if(t.state_version!==e.reservation.state.state_version||t.phase!=="verify"||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier request-checks state changed during execution");let r=D(e.paths,t.name),i=await tt(r),n=i?.execution;if(i===null||i.basedOnStateVersion!==t.state_version||n===null||n===void 0||n.operationId!==e.reservation.local.execution?.operationId||n.stage!=="checking"||n.actor!=="runtime"||n.status!=="running"||n.executionId!==e.reservation.verifierExecutionRef||n.requestCheckRounds!==e.reservation.round)throw new Error("Native Verifier request-checks reservation changed during execution");let a=e.update(i);return await L(r,a,{containedRoot:e.paths.runtimeDir}),a})}async function UE(e){let t;try{for(let r of e.reservation.novelPlans){let i=new Date().toISOString();t=await oo({paths:e.paths,reservation:e.reservation,update:a=>({...a,checks:a.checks.map(o=>o.id===r.id?{...o,status:"running",executionCount:o.executionCount+1,startedAt:i}:o)})});let n=await sl({projectRoot:e.projectRoot,runtimeDir:He(e.paths,e.reservation.state.name),operationId:e.reservation.local.execution.operationId,plan:r});t=await oo({paths:e.paths,reservation:e.reservation,update:a=>({...a,checks:a.checks.map(o=>o.id===r.id?{...o,status:n.status,exitCode:n.exitCode,startedAt:n.startedAt,completedAt:n.completedAt,log:n.logRef}:o)})})}t=await oo({paths:e.paths,reservation:e.reservation,update:r=>({...r,execution:{...r.execution,stage:"verifying",actor:"verifier",executionId:e.reservation.verifierExecutionRef}})})}catch(r){try{await oo({paths:e.paths,reservation:e.reservation,update:i=>({...i,execution:{...i.execution,status:"interrupted"},checks:i.checks.map(n=>n.status==="planned"||n.status==="running"?{...n,status:"interrupted"}:n)})})}catch{}throw r}return{checks:Ir({local:t,projectRoot:e.projectRoot,supplied:e.reservation.suppliedChecks,requestedNames:e.reservation.requestedNames}),requestChecks:{round:e.reservation.round,reusedCheckIds:e.reservation.reusedCheckIds,executedCheckIds:e.reservation.novelPlans.map(({id:r})=>r)}}}async function $p(e){return P(e.paths,`dispatch portable verifier ${e.name}`,async()=>{let t=await j(e.paths,e.name),r=e.projectRoot??e.paths.projectRoot;await Dt({paths:e.paths,state:t});let i=(await vl({file:D(e.paths,t.name),portableState:t,projectRoot:r,branch:Me(r),containedRoot:e.paths.runtimeDir})).state;if(i.execution?.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="completed")throw new Error("Native check plan must be explicitly resolved before Verifier dispatch");Ir({local:i,projectRoot:r,supplied:e.checks});let n=hp(t),a=await ke({paths:e.paths,previous:t,next:n}),o=D(e.paths,t.name),s=wl();return await L(o,{...i,basedOnStateVersion:a.state_version,execution:{operationId:s,stage:"verifying",actor:"verifier",executionId:e.verifierExecutionId??null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:i.checks.map(c=>({...c,operationId:s}))},{containedRoot:e.paths.runtimeDir}),a})}async function Op(e){if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let t=await P(e.paths,`apply portable verifier ${e.name}`,async()=>{let r=await j(e.paths,e.name),i=e.projectRoot??e.paths.projectRoot;await Dt({paths:e.paths,state:r});let n=await Tr({paths:e.paths,state:r}),a=WE({state:r,local:n,envelope:e.envelope}),o;try{o=ul(a.payload)}catch(d){let u=`Native Verifier response was invalid: ${d.message}`,h=await so({paths:e.paths,state:r,summary:u});throw new Error(`${u}; execution error ${h.loop.execution_failure_count}/${Wi} was recorded`,{cause:d})}let s=zE(o);if(s.iteration!==r.loop.iteration||s.attempt!==r.loop.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");let c=[],l;try{n!==null&&(c=Ir({local:n,projectRoot:i,supplied:e.checks}));let d=pp({state:r,envelope:a,checks:c,maxVerifyFailures:e.maxVerifyFailures});if(d.response.kind==="request-checks"){if(n===null)throw new Error("Native Verifier request-checks has no active local execution");let u=await GE({paths:e.paths,projectRoot:i,state:r,local:n,envelope:a,response:d.response,suppliedChecks:c});return{kind:"request-checks",state:r,response:d.response,reservation:u}}if(n===null||n.execution===null||n.execution.stage!=="verifying"||n.execution.actor!=="verifier"||n.execution.status!=="running")throw new Error("Native Verifier final result has no active local execution");if(n.execution.executionId!==null&&n.execution.executionId!==a.verifierExecutionRef)throw new Error("Native Verifier final result changed execution within the same attempt");l=d}catch(d){let u=`Native Verifier response was invalid: ${d.message}`,h=await so({paths:e.paths,state:r,summary:u});throw new Error(`${u}; execution error ${h.loop.execution_failure_count}/${Wi} was recorded`,{cause:d})}let f=await ke({paths:e.paths,previous:r,next:l.state});return await L(D(e.paths,r.name),f.loop.next_action==="resolve-verifier-blocker"||f.loop.next_action==="run-final-full-verification"?Ki({local:n,state:f,projectRoot:i}):oe({portableState:f,projectRoot:i,branch:Me(i)}),{containedRoot:e.paths.runtimeDir}),f.verification!==null&&await _r({file:Z.join(ue(e.paths,r.name),"verification.md"),state:f}),{kind:"final-result",result:{state:f,response:l.response,checks:c,requestChecks:null}}});if(t.kind==="final-result")return t.result;try{let r=await UE({paths:e.paths,projectRoot:e.projectRoot??e.paths.projectRoot,reservation:t.reservation});return{state:t.state,response:t.response,checks:r.checks,requestChecks:r.requestChecks}}catch(r){let i=`Native Verifier response was invalid: ${r.message}`,n=await P(e.paths,`record Verifier-requested check failure ${e.name}`,async()=>{let a=await j(e.paths,e.name);return a.state_version!==t.state.state_version?null:so({paths:e.paths,state:a,summary:i})});throw new Error(n?`${i}; execution error ${n.loop.execution_failure_count}/${Wi} was recorded`:`${i}; the portable state changed before the execution error could be recorded`,{cause:r})}}async function Hp(e){return P(e.paths,`record portable verifier failure ${e.name}`,async()=>{let t=await j(e.paths,e.name),r=await Tr({paths:e.paths,state:t});if(Tp({state:t,local:r,expected:e.expected}),e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");return so({paths:e.paths,state:t,summary:e.summary})})}async function Dp(e){return P(e.paths,`record unavailable portable verifier ${e.name}`,async()=>{let t=await j(e.paths,e.name);await Dt({paths:e.paths,state:t});let r=await Tr({paths:e.paths,state:t}),i=Tp({state:t,local:r,expected:e.expected});if(e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");let n=Ir({local:i,projectRoot:e.paths.projectRoot,supplied:[]}),a=vp({state:t,checks:n,verifierExecutionRef:i.execution.executionId,summary:e.summary}),o=await ke({paths:e.paths,previous:t,next:a});return await L(D(e.paths,t.name),Ki({local:i,state:o,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),await _r({file:Z.join(ue(e.paths,t.name),"verification.md"),state:o}),o})}async function Bp(e){return P(e.paths,`confirm portable Skill-coordinated pass ${e.name}`,async()=>{let t=await j(e.paths,e.name);tr({state:t,expected:e.expectedContinuation,action:"accept-result"}),await Dt({paths:e.paths,state:t});let r=mp(t),i=await ke({paths:e.paths,previous:t,next:r});return await L(D(e.paths,t.name),oe({portableState:i,projectRoot:e.paths.projectRoot,branch:Me(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await _r({file:Z.join(ue(e.paths,t.name),"verification.md"),state:i}),i})}async function Lp(e){return P(e.paths,`confirm unavailable portable verifier ${e.name}`,async()=>{let t=await j(e.paths,e.name);tr({state:t,expected:e.expectedContinuation,action:"confirm-verifier-unavailable"}),await Dt({paths:e.paths,state:t});let r=gp({state:t,summary:e.summary}),i=await ke({paths:e.paths,previous:t,next:r});return await L(D(e.paths,t.name),oe({portableState:i,projectRoot:e.paths.projectRoot,branch:Me(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await _r({file:Z.join(ue(e.paths,t.name),"verification.md"),state:i}),i})}async function Vp(e){return P(e.paths,`resolve portable verifier blocker ${e.name}`,async()=>{let t=await j(e.paths,e.name);tr({state:t,expected:e.expectedContinuation,action:"resolve-verifier-blocker"}),await Dt({paths:e.paths,state:t});let r=await Tr({paths:e.paths,state:t}),i=wp(t),n=await ke({paths:e.paths,previous:t,next:i});return await L(D(e.paths,t.name),Ki({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function Mp(e){return P(e.paths,`retry portable verifier ${e.name}`,async()=>{let t=await j(e.paths,e.name);tr({state:t,expected:e.expectedContinuation,action:"retry-verifier"});let r=await Tr({paths:e.paths,state:t}),i=Np(t),n=await ke({paths:e.paths,previous:t,next:i});return await L(D(e.paths,t.name),Ki({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function uo(e){return P(e.paths,`return portable change ${e.name} to Build`,async()=>{let t=await j(e.paths,e.name);if(tr({state:t,expected:e.expectedContinuation,action:"revise-implementation"}),t.phase==="build")return t;let r=zi({state:t,reason:e.reason}),i=await ke({paths:e.paths,previous:t,next:r});return await L(D(e.paths,t.name),oe({portableState:i,projectRoot:e.paths.projectRoot,branch:Me(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),i})}async function fo(e){return P(e.paths,`return portable change ${e.name} to Shape`,async()=>{let t=await j(e.paths,e.name);if(tr({state:t,expected:e.expectedContinuation,action:"revise-requirements"}),e.allowedPhases&&!e.allowedPhases.includes(t.phase))throw new Error("--revise-requirements is only valid from Verify or Archive");return t.phase==="shape"?t:Fp({paths:e.paths,state:t,reason:e.reason})})}async function Fp(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let i={...Ne(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:O(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"confirm-shape"}};delete i.children_contract_hash;let n=await ke({paths:e.paths,previous:t,next:i});return await L(D(e.paths,t.name),oe({portableState:n,projectRoot:e.paths.projectRoot,branch:Me(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function ho(e){if(e.state.verification===null)return"not-applicable";let t=Z.join(ue(e.paths,e.state.name),"verification.md");return await Sp({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await _r({file:t,state:e.state}),"rebuilt")}var qp=["evidence.md","repair.md","archive.md","checkpoint.md"],XE="verification.md";async function QE(e,t){let r=await Ch(e,{kind:"migration",change:t});return r?.kind==="migration"?r.journal:null}async function Wp(e,t){await Yi.mkdir(e.transactionsDir,{recursive:!0}),await me(Da(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function zp(e,t,r={}){let i=r.removeVerificationReport===!1?qp:[...qp,XE];await Promise.all([Yi.rm(He(e,t),{recursive:!0,force:!0}),Yi.rm(vc(e,t),{recursive:!0,force:!0}),...i.map(n=>Yi.rm(YE.join(Xe(e,t),n),{force:!0}))])}async function Jp(e,t){await L(D(e,t.name),oe({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function Gp(e,t){try{let r=await Ai(e,t);if(r?.schema==="comet.native.workspace.v3")return{isolation:r.isolation,change_branch:r.changeBranch,target_branch:r.targetBranch,finish:r.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function Up(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let r=F(e.projectRoot);if(!r.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(r.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${r.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!r.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function ZE(e){let t=Xe(e.paths,e.state.name),r=await J({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),i=[];for(let n of e.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await J({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return $a({briefMarkdown:r.text,specs:i})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function Kp(e,t){let r=await uh(e,t);if(!r.state)throw new Error(`Native legacy change ${t} is unreadable`);return r.state}async function Yp(e){return P(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await QE(e.paths,e.name),r=await Ui(e.paths,e.name)?await De(Fe(e.paths,e.name)):null;if(!t&&r)return await zp(e.paths,e.name,{removeVerificationReport:!1}),await Jp(e.paths,r),r;let i=null,n=null;for(t||(i=await Kp(e.paths,e.name),n=await Gp(e.paths,e.name),Up(e.paths,n),t={schema:Oa,id:KE(),change:i.name,fromSchema:i.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await Wp(e.paths,t));;){let a=bh(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?r||(i??=await Kp(e.paths,e.name),n??=await Gp(e.paths,e.name),Up(e.paths,n),r=Nh({state:i,acceptance:await ZE({paths:e.paths,state:i}),workspace:n,migratedAt:e.now}),await ka(Fe(e.paths,e.name),r,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await zp(e.paths,e.name):a.action==="commit-transaction"&&(r??=await De(Fe(e.paths,e.name)),await Jp(e.paths,r)),t={...t,status:a.nextStatus},await Wp(e.paths,t)}return await Yi.rm(Da(e.paths,{kind:"migration",change:e.name}),{force:!0}),r??De(Fe(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as Xp}from"node:fs";import Qp from"node:path";function ex(e,t){let r=F(e.projectRoot);if(t.workspace.change_branch!==null){if(!r.isGitWorktree)return"The portable change requires a Git branch/worktree";if(r.currentBranch!==t.workspace.change_branch)return`Expected Native change branch ${t.workspace.change_branch}, current branch is ${r.currentBranch??"(detached)"}`}return t.workspace.isolation==="current"?null:r.isGitWorktree?t.workspace.isolation==="worktree"&&!r.isSecondaryWorktree?"The portable change requires its linked worktree":null:"The portable change requires a Git branch/worktree"}function tx(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function rx(e,t,r){let i=new Date().toISOString(),n=e.verification===null?e:Ne(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:O(t),completed_at:i});return C({...n,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:r?tx(e):e.acceptance,verification:null,verification_result:"pending",verification_report:null,blockers:[],loop:{...e.loop,stage:"verify-ready",next_action:"run-required-checks-and-dispatch-verifier"}})}async function ix(e){try{let t=await tt(e);return t===null?{local:null,reason:"missing"}:{local:t,reason:"available"}}catch(t){if(t.code&&t.code!=="ENOENT")throw t;return{local:null,reason:"invalid"}}}async function Nl(e){return P(e.paths,`recover portable change ${e.name}`,async()=>{let t=await j(e.paths,e.name);if(t.status==="done")return await ho({paths:e.paths,state:t}),{state:t,local:null,action:"done",reason:"done",message:"Archived Native changes do not require a local execution overlay."};let r=ex(e.paths,t);if(r)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:r};let i=D(e.paths,e.name),n=await ix(i),a=n.reason==="available"&&(n.local?.change!==t.name||n.local?.basedOnStateVersion!==t.state_version)?"stale":n.reason;if(a==="available"&&!e.preserveRunningExecution&&n.local?.execution!==null&&n.local?.execution?.status!=="completed"&&n.local&&(a="interrupted",n.local.execution?.status==="running"&&(n.local={...n.local,execution:{...n.local.execution,status:"interrupted"},checks:n.local.checks.map(u=>u.status==="planned"||u.status==="running"?{...u,status:"interrupted"}:u)},await L(i,n.local,{containedRoot:e.paths.runtimeDir}))),a==="available")return await ho({paths:e.paths,state:t}),{state:t,local:n.local,action:"resume-stable-boundary",reason:a,message:"Native local execution overlay matches the portable state."};let s=a==="interrupted"?n.local?.checks.find(u=>u.status==="interrupted"&&!u.repeatable):void 0;if(s){let u=zi({state:t,reason:`Check ${s.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await Ci({file:Fe(e.paths,t.name),expectedStateVersion:t.state_version,next:u,containedRoot:e.paths.nativeRoot}),await Xp.rm(Qp.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let h=oe({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await L(i,h,{containedRoot:e.paths.runtimeDir}),{state:t,local:h,action:"resume-stable-boundary",reason:a,message:`Native check ${s.id} was not repeatable; the change returned to Build for a new candidate.`}}let c=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",l=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",f=c||l;if(f){let u=rx(t,l?"Local Runtime was unavailable at Archive ready; the synchronized implementation must be verified again.":"The previous Verifier execution was unavailable; dispatch a new attempt from the stable Verify boundary.",l);t=await Ci({file:Fe(e.paths,t.name),expectedStateVersion:t.state_version,next:u,containedRoot:e.paths.nativeRoot})}let d=oe({portableState:t,projectRoot:e.paths.projectRoot,branch:F(e.paths.projectRoot).currentBranch});return await Xp.mkdir(Qp.dirname(D(e.paths,t.name)),{recursive:!0}),await L(i,d,{containedRoot:e.paths.runtimeDir}),await ho({paths:e.paths,state:t}),{state:t,local:d,action:f?"reverify":"resume-stable-boundary",reason:a,message:f?"Rebuilt local execution from the portable boundary; previous pass/execution was not reused.":`Rebuilt local execution from the portable ${t.phase}/${t.loop.stage} boundary.`}})}function nx(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function rt(e){let t=e.acceptance.reduce((r,i)=>({...r,[i.result]:r[i.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:r})=>r==="failed"||r==="blocked").map(({id:r})=>r),verification_result:e.verification_result,blockers:e.blockers.slice(0,8).map(r=>({owner:r.owner,reason:nx(r.reason.text),acceptance_ids:r.acceptance_ids,resolution_action:r.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}}import{randomUUID as nm}from"node:crypto";import{promises as Zp}from"node:fs";import Qi from"node:path";function jr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function de(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function H(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} must be non-empty text`);return e}function kl(e,t){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,i)=>H(r,`${t}[${i}]`))}function ax(e){if(!Array.isArray(e))throw new Error("Native Builder checks must be an array");return e.map((t,r)=>{let i=jr(t,`Native Builder check ${r}`);if(de(i,["name","result","note"],`Native Builder check ${r}`),!["passed","failed","not-run"].includes(String(i.result)))throw new Error(`Native Builder check ${r} result is invalid`);if(i.note!==null&&typeof i.note!="string")throw new Error(`Native Builder check ${r} note is invalid`);return{name:H(i.name,`Native Builder check ${r} name`),result:i.result,note:i.note}})}function ox(e){if(!Array.isArray(e))throw new Error("Native Runtime checks must be an array");return e.map((t,r)=>{let i=jr(t,`Native Runtime check ${r}`);if(de(i,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Runtime check ${r}`),!Array.isArray(i.argv)||!i.argv.every(n=>typeof n=="string"))throw new Error(`Native Runtime check ${r} argv is invalid`);if(!Number.isSafeInteger(i.timeoutMs)||i.timeoutMs<1)throw new Error(`Native Runtime check ${r} timeoutMs is invalid`);if(typeof i.repeatable!="boolean")throw new Error(`Native Runtime check ${r} repeatable is invalid`);return{id:H(i.id,`Native Runtime check ${r} id`),name:H(i.name,`Native Runtime check ${r} name`),executable:H(i.executable,`Native Runtime check ${r} executable`),argv:[...i.argv],cwdRef:H(i.cwdRef,`Native Runtime check ${r} cwdRef`),timeoutMs:i.timeoutMs,repeatable:i.repeatable}})}function em(e,t){let r=e.stateVersion,i=e.iteration,n=e.attempt;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${t} stateVersion is invalid`);if(!Number.isSafeInteger(i)||i<1)throw new Error(`${t} iteration is invalid`);if(!Number.isSafeInteger(n)||n<1)throw new Error(`${t} attempt is invalid`);return{stateVersion:r,iteration:i,attempt:n,verifierExecutionRef:H(e.verifierExecutionRef,`${t} verifierExecutionRef`)}}function sx(e){let t=jr(e,"Native Supervisor evidence");return de(t,["summary","checks"],"Native Supervisor evidence"),{summary:H(t.summary,"Native Supervisor evidence summary"),checks:kl(t.checks,"Native Supervisor evidence checks")}}function cx(e){if(!Array.isArray(e))throw new Error("Native Supervisor integration checks must be an array");return e.map((t,r)=>{let i=jr(t,`Native Supervisor integration check ${r}`),n=new Set(["name","status","reason"]);if(Object.keys(i).some(a=>!n.has(a)))throw new Error(`Native Supervisor integration check ${r} fields are invalid`);if(!Object.hasOwn(i,"name")||!Object.hasOwn(i,"status"))throw new Error(`Native Supervisor integration check ${r} fields are invalid`);if(!["passed","failed","incomplete"].includes(String(i.status)))throw new Error(`Native Supervisor integration check ${r} status is invalid`);if(i.reason!==void 0&&i.reason!==null&&typeof i.reason!="string")throw new Error(`Native Supervisor integration check ${r} reason is invalid`);return{name:H(i.name,`Native Supervisor integration check ${r} name`),status:i.status,reason:i.reason??null}})}function lx(e){let t=jr(e,"Native Runner input");if(t.kind==="builder-handoff"){de(t,["kind","summary","addressed_acceptance_ids","checks","known_limits","review"],"Native Runner Builder input");let r=jr(t.review,"Native Builder review");if(de(r,["status","summary","reviewer_execution_ref"],"Native Builder review"),r.status!=="passed")throw new Error("Native Builder review status must be passed");return{kind:"builder-handoff",summary:H(t.summary,"Native Builder summary"),addressed_acceptance_ids:kl(t.addressed_acceptance_ids,"Native Builder addressed acceptance IDs"),checks:ax(t.checks),known_limits:kl(t.known_limits,"Native Builder known limits"),review:{status:"passed",summary:H(r.summary,"Native Builder review summary"),reviewer_execution_ref:H(r.reviewer_execution_ref,"Native Builder reviewer execution ref")}}}if(t.kind==="dispatch-verifier")return de(t,["kind","checks"],"Native Runner dispatch input"),{kind:"dispatch-verifier",checks:ox(t.checks)};if(t.kind==="verifier-response")return de(t,["kind","response"],"Native Runner Verifier input"),{kind:"verifier-response",response:t.response};if(t.kind==="verifier-execution-error")return de(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner execution error input"),{kind:"verifier-execution-error",summary:H(t.summary,"Native Verifier execution error summary"),...em(t,"Native Runner execution error input")};if(t.kind==="verifier-unavailable")return de(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner unavailable Verifier input"),{kind:"verifier-unavailable",summary:H(t.summary,"Native unavailable Verifier summary"),...em(t,"Native Runner unavailable Verifier input")};if(t.kind==="supervisor-builder-result")return de(t,["kind","child","runId","candidateCommit"],"Native Supervisor Builder input"),{kind:"supervisor-builder-result",child:H(t.child,"Native Supervisor child"),runId:H(t.runId,"Native Supervisor runId"),candidateCommit:H(t.candidateCommit,"Native Supervisor candidate commit")};if(t.kind==="supervisor-builder-failure")return de(t,["kind","child","runId","reason"],"Native Supervisor Builder failure input"),{kind:"supervisor-builder-failure",child:H(t.child,"Native Supervisor child"),runId:H(t.runId,"Native Supervisor runId"),reason:H(t.reason,"Native Supervisor Builder failure reason")};if(t.kind==="supervisor-reconnect")return de(t,["kind","child","runId"],"Native Supervisor reconnect input"),{kind:"supervisor-reconnect",child:H(t.child,"Native Supervisor child"),runId:H(t.runId,"Native Supervisor runId")};if(t.kind==="supervisor-cancel")return de(t,["kind","child","runId","reason"],"Native Supervisor cancel input"),{kind:"supervisor-cancel",child:H(t.child,"Native Supervisor child"),runId:H(t.runId,"Native Supervisor runId"),reason:H(t.reason,"Native Supervisor cancellation reason")};if(t.kind==="supervisor-verifier-result"){if(de(t,["kind","child","runId","verdict","evidence"],"Native Supervisor Verifier input"),!["pass","fail","incomplete"].includes(String(t.verdict)))throw new Error("Native Supervisor Verifier verdict is invalid");return{kind:"supervisor-verifier-result",child:H(t.child,"Native Supervisor child"),runId:H(t.runId,"Native Supervisor runId"),verdict:t.verdict,evidence:sx(t.evidence)}}if(t.kind==="supervisor-integrate")return de(t,["kind","child","checks"],"Native Supervisor integration input"),{kind:"supervisor-integrate",child:H(t.child,"Native Supervisor child"),checks:cx(t.checks)};throw new Error("Native Runner input kind is invalid")}async function am(e,t){let r=Qi.resolve(t,e),i=await Zp.lstat(r);if(!i.isFile()||i.isSymbolicLink())throw new Error("Native Runner input must be a regular non-symlink file");let n;try{n=JSON.parse(await Zp.readFile(r,"utf8"))}catch(a){throw new Error("Native Runner input must be valid JSON",{cause:a})}return lx(n)}function tm(e){return`${K}:${e}:${nm()}`}function rm(e,t,r,i){if(Qi.resolve(A(e.projectRoot,["rev-parse","--show-toplevel"]))!==Qi.resolve(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree identity is invalid`);if(A(e.projectRoot,["branch","--show-current"])!==i)throw new Error(`Native Supervisor ${r} result came from the wrong Child worktree branch`);if(!at(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree must be clean before returning a commit`);if(A(e.projectRoot,["rev-parse","HEAD"])!==t)throw new Error(`Native Supervisor ${r} result is not bound to the worktree HEAD`);try{A(e.projectRoot,["merge-base","--is-ancestor",e.baseCommit,t])}catch(s){throw new Error(`Native Supervisor ${r} result is not based on its task base commit`,{cause:s})}}function ux(e,t){let r=F(e.projectRoot),i=Qi.resolve(r.currentWorktreeRoot??"");if(!r.isGitWorktree||i!==Qi.resolve(e.projectRoot))throw new Error("Native Supervisor task worktree identity is invalid");if(r.currentBranch!==t)throw new Error("Native Supervisor task is attached to the wrong Child branch");let n=A(e.projectRoot,["rev-parse","HEAD"]);if(e.role==="verifier"){if(!at(e.projectRoot)||n!==e.baseCommit)throw new Error("Native Supervisor Verifier task worktree is not at its candidate commit");return}try{A(e.projectRoot,["merge-base","--is-ancestor",e.baseCommit,n])}catch(a){throw new Error("Native Supervisor Builder task base commit is not an ancestor of its HEAD",{cause:a})}}function Xi(e){if(e.builder_handoff===null)throw new Error("Native Skill coordination has no current Builder candidate");if(e.builder_handoff.identity_provider!==K)throw new Error("Native candidate is owned by a host identity adapter and cannot use the generic Skill coordination bridge");if(!e.builder_handoff.review)throw new Error("Native Skill coordination requires a passed read-only review");return e.builder_handoff}function im(e){let{paths:t,state:r,checks:i,verifierExecutionRef:n,supervisor:a}=e,o=Xi(r);if(!o.review)throw new Error("Native Skill coordination requires a passed read-only review");let s=r.acceptance.filter(({result:c})=>c==="pending").map(({id:c})=>c);return{coordination:K,change:r.name,candidateId:o.candidate_id,stateVersion:r.state_version,iteration:r.loop.iteration,attempt:r.loop.attempt,verifierExecutionRef:n,projectRoot:t.projectRoot,verificationRoot:a?.integration.worktree??t.projectRoot,changeDir:ue(t,r.name),supervisorStateRef:a?Fa(t,r.name):null,briefRef:r.brief,specRefs:r.spec_changes.map(({capability:c,operation:l,source:f})=>({capability:c,operation:l,ref:f})),acceptanceCount:r.acceptance.length,scopeIds:s,detailsPageArgs:["comet","native","status",r.name,"--details","--json","--project-root",t.projectRoot],builderReview:{status:o.review.status,summary:o.review.summary},runtimeChecks:i.map(c=>({...c}))}}async function bl(e){Xi(e.state);let t=await tt(D(e.paths,e.state.name));if(t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version||t.execution===null||t.execution.stage!=="verifying"||t.execution.actor!=="verifier"||t.execution.status!=="running"||t.execution.executionId===null)throw new Error("Native Skill coordination has no active Verifier attempt");return t.execution.executionId}async function om(e){let t=await re(e.paths,e.name),r=e.input,i=t?await j(e.paths,e.name):null,n=t!==null&&i?.phase==="verify"&&t.children.every(({status:u})=>u==="integrated"||u==="archived"),a=t!==null&&i?.phase==="build"&&t.children.every(({status:u})=>u==="integrated"||u==="archived");if(t&&r.kind==="supervisor-builder-result")return P(e.paths,`apply Native Supervisor Builder result ${r.child}`,async()=>{let u=await re(e.paths,e.name);if(!u)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=u.children.find(({name:g})=>g===r.child);if(!h?.task||h.task.role!=="builder")throw new Error(`Native Supervisor Builder task is not active for ${r.child}`);try{rm(h.task,r.candidateCommit,"builder",`comet/supervisor/${u.parent}/${r.child}`)}catch(g){throw await ae(e.paths,Wa(u,{child:r.child,runId:r.runId,reason:g.message})),g}let v=h.task.projectRoot,m=zh(u,r),p=Kc(m,{role:"verifier",child:r.child,projectRoot:v,runId:nm()});await ae(e.paths,p.state);let y=await j(e.paths,e.name);return{state:y,supervisorTask:p.task,checks:[],requestChecks:null,verifierDispatch:null,continuation:U(y)}});if(t&&r.kind==="supervisor-builder-failure")return P(e.paths,`cancel Native Supervisor Builder task ${r.child}`,async()=>{let u=await re(e.paths,e.name);if(!u)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=u.children.find(({name:p})=>p===r.child);if(!h?.task||h.task.role!=="builder")throw new Error(`Native Supervisor Builder failure is not valid for ${r.child}`);let v=Yc(u,{child:r.child,runId:r.runId,reason:r.reason});await ae(e.paths,v);let m=await j(e.paths,e.name);return{state:m,supervisorState:v,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:U(m)}});if(t&&r.kind==="supervisor-reconnect")return P(e.paths,`reconnect Native Supervisor task ${r.child}`,async()=>{let u=await re(e.paths,e.name);if(!u)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=u.children.find(({name:p})=>p===r.child)?.task;if(!h||h.runId!==r.runId)throw new Error(`Native Supervisor task runId is not current for ${r.child}`);try{ux(h,`comet/supervisor/${u.parent}/${r.child}`)}catch(p){throw await ae(e.paths,Wa(u,{child:r.child,runId:r.runId,reason:p.message})),p}let v=qh(u,{child:r.child,runId:r.runId});await ae(e.paths,v.state);let m=await j(e.paths,e.name);return{state:m,supervisorState:v.state,supervisorTask:v.task,checks:[],requestChecks:null,verifierDispatch:null,continuation:U(m)}});if(t&&r.kind==="supervisor-cancel")return P(e.paths,`cancel Native Supervisor task ${r.child}`,async()=>{let u=await re(e.paths,e.name);if(!u)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=Yc(u,{child:r.child,runId:r.runId,reason:r.reason});await ae(e.paths,h);let v=await j(e.paths,e.name);return{state:v,supervisorState:h,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:U(v)}});if(t&&r.kind==="supervisor-verifier-result")return P(e.paths,`apply Native Supervisor Verifier result ${r.child}`,async()=>{let u=await re(e.paths,e.name);if(!u)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=u.children.find(({name:p})=>p===r.child);if(!h?.task||h.task.role!=="verifier"||!h.candidateCommit)throw new Error(`Native Supervisor Verifier task is not active for ${r.child}`);try{rm(h.task,h.candidateCommit,"verifier",`comet/supervisor/${u.parent}/${r.child}`)}catch(p){throw await ae(e.paths,Wa(u,{child:r.child,runId:r.runId,reason:p.message})),p}let v=Jh(u,r);await ae(e.paths,v);let m=await j(e.paths,e.name);return{state:m,supervisorState:v,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:U(m)}});if(t&&r.kind==="supervisor-integrate"){let u=await Gh({paths:e.paths,state:t,name:r.child,checks:r.checks}),h=await lo({paths:e.paths,name:e.name,trigger:"v2-integrate"}),v=h.state;return{state:v,supervisorState:u,supervisorTask:null,checks:r.checks,requestChecks:null,verifierDispatch:null,parentAdvance:h.parentAdvance,continuation:U(v)}}if(t&&(r.kind==="builder-handoff"||r.kind==="dispatch-verifier"||r.kind==="verifier-response"||r.kind==="verifier-execution-error"||r.kind==="verifier-unavailable"||r.kind==="supervisor-builder-result"||r.kind==="supervisor-builder-failure"||r.kind==="supervisor-reconnect"||r.kind==="supervisor-cancel"||r.kind==="supervisor-verifier-result")&&!n&&!(r.kind==="builder-handoff"&&a))throw new Error("Native Supervisor accepts only Supervisor task result inputs until every Child is integrated");if(r.kind==="builder-handoff"){let h=ll().captureExecutionIdentity({identityProvider:K,executionRef:tm("builder")}),v=await Ap({paths:e.paths,name:e.name,input:{identity:h,summary:r.summary,addressedAcceptanceIds:r.addressed_acceptance_ids,checks:r.checks,knownLimits:r.known_limits,review:{status:r.review.status,summary:r.review.summary,reviewerExecutionRef:r.review.reviewer_execution_ref}}});return{state:v,checks:[],requestChecks:null,verifierDispatch:null,continuation:U(v)}}if(r.kind==="dispatch-verifier"){if(n&&r.checks.length===0)throw new Error("Native Supervisor parent verification requires at least one check");let u=await j(e.paths,e.name);if(u.builder_handoff!==null&&u.builder_handoff.identity_provider!==K){let y=await uo({paths:e.paths,name:e.name,reason:"The previous Builder identity provider is unavailable to the generic Skill bridge; submit a new Builder candidate before dispatching a Verifier."});return{state:y,checks:[],requestChecks:null,verifierDispatch:null,continuation:U(y)}}Xi(u);let v=(u.loop.next_action==="run-final-full-verification"&&u.verification?.verdict==="pass"&&u.verification.checks.every(({status:y})=>y==="passed")?u.verification.checks:null)??(await jp({paths:e.paths,name:e.name,plans:r.checks,...n&&t?{projectRoot:t.integration.worktree}:{}})).checks,m=tm("verifier"),p=await $p({paths:e.paths,name:e.name,checks:v,verifierExecutionId:m,...n&&t?{projectRoot:t.integration.worktree}:{}});return{state:p,checks:v,requestChecks:null,verifierDispatch:im({paths:e.paths,state:p,checks:v,verifierExecutionRef:m,supervisor:n?t:null}),continuation:U(p)}}if(r.kind==="verifier-execution-error"){let u=await j(e.paths,e.name);Xi(u),await bl({paths:e.paths,state:u});let h=await Hp({paths:e.paths,name:e.name,summary:r.summary,expected:r,requireSkillCoordination:!0});return{state:h,checks:[],requestChecks:null,verifierDispatch:null,continuation:U(h)}}if(r.kind==="verifier-unavailable"){let u=await Dp({paths:e.paths,name:e.name,summary:r.summary,expected:r,requireSkillCoordination:!0});return{state:u,checks:u.verification?.checks??[],requestChecks:null,verifierDispatch:null,continuation:U(u)}}if(r.kind!=="verifier-response")throw new Error("Native Runner input kind is invalid for the portable verifier bridge");let o=await j(e.paths,e.name),s=Xi(o),c=await bl({paths:e.paths,state:o}),l=ll(),f=l.captureExecutionIdentity({identityProvider:K,executionRef:c}),d=await Op({paths:e.paths,name:e.name,envelope:l.envelopeVerifierResponse({candidateId:s.candidate_id,identity:f,payload:r.response}),checks:[],maxVerifyFailures:e.maxVerifyFailures,...n&&t?{projectRoot:t.integration.worktree}:{}});if(n&&d.response.kind==="final-result"){if(d.state.verification_result==="pass"&&(d.checks.length===0||d.checks.some(({status:g})=>g!=="passed")))throw new Error("Native Supervisor parent verification cannot pass without completed integration checks");let u=await re(e.paths,e.name);if(!u)throw new Error("Native Supervisor state disappeared during verification");let h=A(u.integration.worktree,["rev-parse","HEAD"]),v=d.response.result.summary,m=u.children.every(({status:g,verification:w})=>(g==="integrated"||g==="archived")&&w!==null),p=d.checks.length>0&&d.checks.every(({status:g})=>g==="passed"),y=Uh(u,{status:d.state.verification_result==="pass"?"passed":d.state.verification_result==="blocked"?"incomplete":"failed",summary:v,headCommit:h,layers:{childVerification:m?"complete":"incomplete",parentIntegration:p?"complete":"incomplete",parentChecks:d.checks.map(({name:g})=>g.text),notRerun:u.children.flatMap(({verification:g})=>g?.checks??[]),incomplete:d.checks.filter(({status:g})=>g!=="passed").map(({name:g})=>g.text)}});return await ae(e.paths,y),{...d,supervisorState:y,verifierDispatch:null,continuation:U(d.state)}}return{...d,verifierDispatch:d.requestChecks===null?null:im({paths:e.paths,state:d.state,checks:d.checks,verifierExecutionRef:await bl({paths:e.paths,state:d.state}),supervisor:n?t:null}),continuation:U(d.state)}}import en from"path";import{realpathSync as Kx}from"fs";var fx=["outcome","scope","nonGoals","acceptanceExamples"],oO=[...fx,"constraints","decisions","openQuestions","verificationExpectations"];var hx=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});var sm=1024*1024;var lm="scoped-text-safety",px=1,mx=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var vx="comet.native.checker-policy.v1";var kO=pe(vx,{policy:lm,version:px,limits:mx,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var gx=["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"],SO=new Set(gx);var Nx=sm,VO=3*Nx;var um={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:[]},kx=Re("comet-native-runtime:v3:scope-reopen"),h0=[{skillVersion:"3",skillHash:Re("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:Re("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:Re("comet-native-runtime:v1")}];var fm=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],G0=new Set(fm),Ax=new Set([...fm,"minimum_runtime_version","revision"]),U0=new Set([...Ax,"operation"]),K0=512*1024,_x=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),Y0=new Set([..._x,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);var tH={maxAcceptanceCriteria:ja.maxCriteria};var oH={maxSpecs:64,maxFileBytes:ia,maxTotalBytes:4*1024*1024};import{execFile as Lx}from"node:child_process";import{promisify as Vx}from"node:util";var vH={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};var DH=512*1024;var Zi=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};var oD=64*1024;var sD=3600*1e3;var cD=Vx(Lx);var po=class extends Error{details;constructor(t){let r=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(i=>`${i.ref}${i.acceptanceId?`[${i.acceptanceId}]`:""} -> ${i.mismatches.join("; ")}`).join(" | ")}`;super(r),this.name="NativeVerificationReceiptBindingError",this.details=t}};var GD={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var iB=16*1024*1024,nB=256*1024,aB=16*1024;var dB=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var pB=16*1024;var PB=16*1024;var vL=16*1024*1024,mo=class extends Error{constructor(r,i,n,a){super(`Canonical spec conflict for ${r}: expected ${i??"(missing)"}, actual ${n??"(missing)"}`);this.capability=r;this.expectedHash=i;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},vo=class extends Error{constructor(r,i=r.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${r.findingCodes.join(", ")}`){super(i);this.preflight=r;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};var mm=["--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."],El=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:mm,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>]
243
- 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]
244
- 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 Sl(e,t){return`${e}:
241
+ ${Vt(e.verification.summary)}
242
+ `}function fx(e){let t=/^---\r?\ngenerated_from_state_version: ([1-9]\d*)\r?\n---(?:\r?\n|$)/u.exec(e);if(!t)return null;let r=Number(t[1]);return Number.isSafeInteger(r)?r:null}async function Bh(e){let t;try{t=await sx.readFile(e.file,"utf8")}catch(i){if(i.code==="ENOENT")return"missing";throw i}let r=fx(t);return r===null?"invalid":r===e.stateVersion?"aligned":"stale"}async function Br(e){await Pe(e.file,dx(e.state,e.supervisor))}var Vh=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,px="comet-state.yaml",hx="state.json",W$=Ba("en");function cr(e){let t=e.expected;if(t){if(e.state.state_version!==t.stateVersion)throw new Error(`Native continuation is stale for state version ${t.stateVersion}; current state version is ${e.state.state_version}`);if(t.action!==e.action)throw new Error(`Native continuation expected ${t.action} cannot be used for ${e.action}`)}}function fe(e,t){if(!Vh.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=ne.join(e.changesDir,t);if(!ce(e.changesDir,r))throw new Error("Native change path escaped");return r}function Je(e,t){return ne.join(fe(e,t),px)}function D(e,t){return ne.join(Ve(e,t),hx)}async function nn(e,t){try{let r=await sr.readFile(Je(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function Te(e){return W(e).currentBranch}async function I(e,t){return Me(Je(e,t))}async function Ne(e){let t=await $i({file:Je(e.paths,e.previous.name),expectedStateVersion:e.previous.state_version,next:e.next,containedRoot:e.paths.nativeRoot});if(t.verification===null&&t.verification_report===null){let r=ne.join(fe(e.paths,t.name),"verification.md");await z(e.paths.nativeRoot,r),await sr.rm(r,{force:!0})}return t}async function Mh(e){let t=fe(e.paths,e.state.name),r=ne.join(t,"specs"),i=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await sr.readdir(r,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,c)=>s.name.localeCompare(c.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!Vh.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(i.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,c=ne.join(t,...s.split("/")),l=await sr.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let f=ne.join(e.paths.specsDir,o.name,"spec.md"),u="create";try{let d=await sr.lstat(f);if(!d.isFile()||d.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);u="modify"}catch(d){if(d.code!=="ENOENT")throw d}a.push({capability:o.name,operation:u,source:s})}return a.push(...i.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function Fh(e){let t=fe(e.paths,e.state.name),r=await Y({root:t,ref:"brief.md",maxBytes:null,includeHash:!1}),i=[];for(let n of e.specChanges){if(n.source===null)continue;let a=await Y({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}return Ja({briefMarkdown:r.text,specs:i})}async function qh(e){return x(e.paths,`confirm portable shape ${e.name}`,async()=>{let t=await I(e.paths,e.name);cr({state:t,expected:e.expectedContinuation,action:"confirm-shape"});let r=await Mh({paths:e.paths,state:t}),i=await Fh({paths:e.paths,state:t,specChanges:r}),n=await Ki({changeDir:fe(e.paths,t.name),acceptanceIds:i.map(({id:p})=>p),validation:Ui({...t,acceptance:i})});if(n&&t.workspace.change_branch===null)throw new Error("Native parent changes require a Git integration branch");let a=await cl(fe(e.paths,t.name))||n?.contract.schema==="comet.native.children.v2"&&n.contract.children.length>=2,o=e.coordinationMode??t.coordination_mode;if(a&&!n)throw new Error("Native Supervisor Shape requires children.yaml before confirmation");if(a&&o===void 0)throw new Error("Native Supervisor Shape requires --coordination-mode multi-session or single-session");if(!a&&e.coordinationMode!==void 0)throw new Error("--coordination-mode is only valid for a multi-child Native Supervisor Shape");let s=Ch({state:{...t,spec_changes:r},acceptance:i.map(p=>({...p}))});if(delete s.children_contract_hash,delete s.coordination_mode,n){s.children_contract_hash=oo({acceptance:s.acceptance,children:n.contract}),a&&(s.coordination_mode=o);let p=[...t.history].reverse().find(({outcome:v})=>v==="pass"||v==="fail");if(p?.outcome==="fail"&&p.unresolved_ids.length>0){let v=await nt({paths:e.paths,state:s}),m=new Map((v?.children??[]).map(({name:w,status:y})=>[w,y])),h=new Set(n.contract.children.filter(({name:w})=>{let y=m.get(w);return y!=="done"&&y!=="integrated"&&y!=="archived"}).flatMap(({covers:w})=>w)),g=p.unresolved_ids.filter(w=>!h.has(w));if(g.length>0)throw new Error(`Native parent repair plan requires an unfinished child covering: ${g.join(", ")}`)}}let c=null,l=n?.contract.schema==="comet.native.children.v2"?await U(e.paths,t.name):null,f=null,u=null;if(n?.contract.schema==="comet.native.children.v2"){if(f=t.workspace.target_branch??t.workspace.change_branch,!f)throw new Error("Native Supervisor v2 requires a target branch");if(u=kr(e.paths.projectRoot,f),!u)throw new Error(`Native Supervisor target branch has no commit: ${f}`);l||(l=await ro({paths:e.paths,parent:t.name,targetBranch:f,contract:n.contract})),l||(c=await Zp({projectRoot:e.paths.projectRoot,parent:t.name,targetBranch:f,sourceConfig:await we(e.paths.projectRoot)}))}let d=await Ne({paths:e.paths,previous:t,next:s});if(await L(D(e.paths,t.name),oe({portableState:d,projectRoot:e.paths.projectRoot,branch:Te(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n?.contract.schema==="comet.native.children.v2"&&f&&u){let p=l?th({state:l,contract:n.contract}):c?rl({parent:d.name,targetBranch:f,targetCommit:u,integrationBranch:c.binding.changeBranch,integrationWorktree:c.projectRoot,contract:n.contract}):null;if(!p)throw new Error("Native Supervisor integration state is unavailable");await ie(e.paths,p)}return d})}async function No(e){let t=await Mh(e),r=e.ignoreSpecOperationFor??(e.state.children_contract_hash?new Set(e.state.spec_changes.map(({capability:c})=>c)):void 0);if(!(t.length===e.state.spec_changes.length&&t.every((c,l)=>{let f=e.state.spec_changes[l];return f!==void 0&&c.capability===f.capability&&c.source===f.source&&(c.operation===f.operation||r?.has(c.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n=await Fh({...e,specChanges:t}),a=e.state.acceptance.map(({source:c,text:l})=>({source:c,text:l}));if(!jp(a,n))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let o;try{o=await Ki({changeDir:fe(e.paths,e.state.name),acceptanceIds:n.map(({id:c})=>c),validation:Ui({...e.state,acceptance:n})})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return(o?oo({acceptance:n,children:o.contract}):null)===(e.state.children_contract_hash??null)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native child declarations changed"}}async function Mt(e){let t=await No(e);if(!t.drifted)return;let r=t.reason??"Native confirmed requirements changed";throw await im({paths:e.paths,state:e.state,reason:r}),new Error(`${r}; Native change returned to Shape and requires confirmation`)}async function Wh(e){return x(e.paths,`submit portable candidate ${e.name}`,async()=>{let t=await I(e.paths,e.name);if(await Mt({paths:e.paths,state:t}),await Ki({changeDir:fe(e.paths,t.name),acceptanceIds:t.acceptance.map(({id:a})=>a),validation:Ui(t)})||t.children_contract_hash){let a=await nt({paths:e.paths,state:t});if(!a?.confirmed||!a.allDone)throw new Error("Native parent Build advances child changes before parent review");if(t.loop.stage==="repairing"&&t.verification_result==="fail")throw new Error("Native parent verification failed; complete the repair child first")}let i=Ph({state:t,input:e.input}),n=await Ne({paths:e.paths,previous:t,next:i});return await L(D(e.paths,t.name),oe({portableState:n,projectRoot:e.paths.projectRoot,branch:Te(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function bo(e){let t=await I(e.paths,e.name),r={trigger:e.trigger,parent:e.name,advanced:!1,message:null,blocker:null};if(t.phase!=="build"||t.status!=="active")return{state:t,parentAdvance:r};let i=await nt({paths:e.paths,state:t});if(!i||!i.confirmed||!i.allDone)return{state:t,parentAdvance:{...r,blocker:i&&!i.confirmed?"Supervisor child declarations require Shape confirmation":null}};if(t.loop.stage==="repairing"&&t.verification_result==="fail")return{state:t,parentAdvance:{...r,blocker:"Native parent verification failed; add and confirm a repair child"}};let n=t.language==="zh-CN"?"全部 Child 已完成;Supervisor 父级候选需要独立代码审查后再进入验证":"All Children are complete; the Supervisor parent candidate needs an independent code review before verification.";return{state:t,parentAdvance:{...r,message:n}}}function Rl(e,t,r){return{id:e.id,name:e.name,operationId:t,status:"planned",repeatable:e.repeatable,timeoutMs:e.timeoutMs,executionCount:0,argv:[e.executable,...e.argv],cwd:co(r,e.cwdRef),exitCode:null,startedAt:null,completedAt:null,log:`logs/checks/${t}-${e.id}.log`}}function zh(e,t,r,i){if(!e.repeatable)throw new Error(`Native check ${e.id} was interrupted and is not repeatable; user resolution is required`);return{...Rl(t,r,i),executionCount:e.executionCount}}function Jh(e,t){let r=ne.relative(ne.resolve(e),ne.resolve(t));if(ne.isAbsolute(r)||r===".."||r.startsWith(`..${ne.sep}`))throw new Error("Native local check cwd escaped the project root");let i=r.length===0?".":r.split(ne.sep).join("/");return co(e,i),i}function Cl(e,t){let[r,...i]=e.argv;if(!r)throw new Error(`Native local check ${e.id} has no executable`);return Xi({id:e.id,name:e.id,executable:r,argv:i,cwdRef:Jh(t,e.cwd),timeoutMs:e.timeoutMs,repeatable:e.repeatable})}function mx(e){return e.startedAt===null||e.completedAt===null?0:Math.max(0,Date.parse(e.completedAt)-Date.parse(e.startedAt))}function Lr(e){let t=new Map;for(let r of e.supplied){if(t.has(r.id))throw new Error(`Native Runtime check summaries contain duplicate ID ${r.id}`);t.set(r.id,r)}return e.local.checks.map(r=>{if(r.status==="planned"||r.status==="running")throw new Error(`Native Runtime check ${r.id} has not completed`);let i=e.requestedNames?.get(r.id)??r.name;return{id:r.id,name:H(i),argv_display:hl(r.argv.slice(1)).map(n=>H(n)),argv_truncated:!1,cwd_ref:Jh(e.projectRoot,r.cwd),status:r.status,exit_code:r.exitCode,duration_ms:mx(r)}})}function vx(e){return{id:e.id,name:e.name,executable:e.executable,argv:[...e.argv],cwdRef:e.cwdRef,timeoutMs:e.timeoutMs,repeatable:e.repeatable}}function an(e){if(e.local===null||e.local.change!==e.state.name)return oe({portableState:e.state,projectRoot:e.projectRoot,branch:Te(e.projectRoot)});let t=e.local.execution?.operationId??Pl();return{...e.local,basedOnStateVersion:e.state.state_version,execution:{operationId:t,stage:"checking",actor:"runtime",executionId:null,status:"completed",startedAt:e.local.execution?.startedAt??new Date().toISOString(),requestCheckRounds:0},checks:e.local.checks.map(r=>r.status==="running"||r.status==="planned"?{...r,operationId:t,status:"interrupted"}:{...r,operationId:t})}}async function Vr(e){try{let t=await ot(D(e.paths,e.state.name));return t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version?null:t}catch{return null}}function Gh(e){let{state:t,local:r,expected:i}=e;if(t.state_version!==i.stateVersion||t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.loop.iteration!==i.iteration||t.loop.attempt!==i.attempt||t.builder_handoff===null||r===null||r.basedOnStateVersion!==t.state_version||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running"||r.execution.executionId!==i.verifierExecutionRef)throw new Error("Native Verifier execution message is stale for the current attempt");return r}function gx(e){let{state:t,local:r,envelope:i}=e;if(!uo(i))throw new Error("Native Verifier result must come from the trusted Runner channel");if(t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.builder_handoff===null)throw new Error("Native Verifier result is stale for the current workflow state");if(i.candidateId!==t.builder_handoff.candidate_id||i.identityProvider!==t.builder_handoff.identity_provider||i.verifierExecutionRef===t.builder_handoff.builder_execution_ref)throw new Error("Native Verifier result is stale for the current candidate or identity");if(r===null||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running"||r.execution.executionId!==null&&r.execution.executionId!==i.verifierExecutionRef)throw new Error("Native Verifier result is stale for the active execution");return i}function wx(e){return e.kind==="final-result"?{iteration:e.result.iteration,attempt:e.result.attempt}:{iteration:e.iteration,attempt:e.attempt}}async function yo(e){let t=await Vr({paths:e.paths,state:e.state}),r=$h({state:e.state,summary:e.summary}),i=await Ne({paths:e.paths,previous:e.state,next:r});return await L(D(e.paths,e.state.name),an({local:t,state:i,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),i}function Lh(e,t,r){return e.checks.length!==t.length?!1:e.checks.every((i,n)=>Cl(i,r)===Xi(t[n]))}async function yx(e){return x(e.paths,`reserve portable checks ${e.name}`,async()=>{let t=await I(e.paths,e.name);if(await Mt({paths:e.paths,state:t}),t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native checks require Verify ready state");let r=D(e.paths,t.name),i=(await xl({file:r,portableState:t,projectRoot:e.projectRoot,branch:Te(e.projectRoot),containedRoot:e.paths.runtimeDir})).state;if(i.execution?.stage==="checking"&&i.execution.actor==="runtime"&&Lh(i,e.plans,e.projectRoot)){let o=i.execution;if(o.status==="running")throw new Error("Native check plan is already in progress");let s=i.checks.filter(c=>c.status==="interrupted");if(s.length===0&&o.status==="completed"){let c=new Map(e.plans.map(({id:l,name:f})=>[l,f]));return{kind:"reuse",state:t,checks:Lr({local:i,projectRoot:e.projectRoot,supplied:[],requestedNames:c})}}if(s.length>0&&s.some(c=>!c.repeatable)){let c=tn({state:t,reason:`A non-repeatable Runtime check was interrupted (${s.filter(f=>!f.repeatable).map(({id:f})=>f).join(", ")}); a new Builder candidate is required before it can run again.`}),l=await Ne({paths:e.paths,previous:t,next:c});throw await L(D(e.paths,t.name),oe({portableState:l,projectRoot:e.paths.projectRoot,branch:Te(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),new Error(`Native check ${s.find(f=>!f.repeatable).id} was interrupted and is not repeatable; the change returned to Build for a new candidate`)}}if(i.execution!==null&&i.checks.length>0){if(!(i.execution.stage==="checking"&&i.execution.actor==="runtime"&&i.checks.some(s=>s.status==="interrupted")&&Lh(i,e.plans,e.projectRoot)))throw new Error("Native check plan was already resolved with a different plan")}else if(i.execution!==null||i.checks.length>0)throw new Error("Native check plan was already resolved with a different plan");let n=Pl(),a={...i,execution:{operationId:n,stage:"checking",actor:"runtime",executionId:null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:e.plans.map(o=>{let s=i.checks.find(c=>c.id===o.id);return s?.status==="interrupted"?zh(s,o,n,e.projectRoot):s?{...s,operationId:n}:Rl(o,n,e.projectRoot)})};return await L(r,a,{containedRoot:e.paths.runtimeDir}),{kind:"execute",state:t,local:a,plans:e.plans.filter(o=>{let s=i.checks.find(c=>c.id===o.id);return s===void 0||s.status==="interrupted"})}})}async function go(e){return x(e.paths,`update portable checks ${e.state.name}`,async()=>{let t=await I(e.paths,e.state.name);if(t.state_version!==e.state.state_version||t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native check plan state changed during execution");let r=D(e.paths,t.name),i=await ot(r);if(i===null||i.basedOnStateVersion!==t.state_version||i.execution?.operationId!==e.operationId||i.execution.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="running")throw new Error("Native check plan reservation changed during execution");let n=e.update(i);return await L(r,n,{containedRoot:e.paths.runtimeDir}),n})}async function Uh(e){let t=e.projectRoot??e.paths.projectRoot;if(new Set(e.plans.map(({id:c})=>c)).size!==e.plans.length)throw new Error("Native check plan contains duplicate IDs");let r=[],i=new Set;for(let c of e.plans){lo(t,c);let l=Xi(c);i.has(l)||(i.add(l),r.push(c))}let n=await yx({...e,plans:r,projectRoot:t});if(n.kind==="reuse")return n;let a=n.local.execution.operationId,o=Ve(e.paths,n.state.name);try{for(let c of n.plans){let l=new Date().toISOString();await go({paths:e.paths,state:n.state,operationId:a,update:u=>({...u,checks:u.checks.map(d=>d.id===c.id?{...d,status:"running",executionCount:d.executionCount+1,startedAt:l}:d)})});let f=await ml({projectRoot:t,runtimeDir:o,operationId:a,plan:c});await go({paths:e.paths,state:n.state,operationId:a,update:u=>({...u,checks:u.checks.map(d=>d.id===c.id?{...d,status:f.status,exitCode:f.exitCode,startedAt:f.startedAt,completedAt:f.completedAt,log:f.logRef}:d)})})}await go({paths:e.paths,state:n.state,operationId:a,update:c=>({...c,execution:{...c.execution,status:"completed"}})})}catch(c){try{await go({paths:e.paths,state:n.state,operationId:a,update:l=>({...l,execution:{...l.execution,status:"interrupted"},checks:l.checks.map(f=>f.status==="planned"||f.status==="running"?{...f,status:"interrupted"}:f)})})}catch{}throw c}let s=await ot(D(e.paths,n.state.name));if(s===null)throw new Error("Native Runtime check state disappeared after execution");return{state:n.state,checks:Lr({local:s,projectRoot:t,supplied:[]})}}async function Nx(e){let t=D(e.paths,e.state.name),r=e.local;if(r===null||r.change!==e.state.name||r.basedOnStateVersion!==e.state.state_version||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running")throw new Error("Native Verifier request-checks has no active local execution");if(r.execution.executionId!==null&&r.execution.executionId!==e.envelope.verifierExecutionRef)throw new Error("Native Verifier request-checks changed execution within the same attempt");if(r.execution.requestCheckRounds>=yl)throw new Error(`Native Verifier request-checks exceeded ${yl} rounds for this attempt`);let i=new Map,n=new Map,a=new Map;for(let p of r.checks){let v=Cl(p,e.projectRoot);n.set(v,p),p.status!=="interrupted"&&i.set(v,p),a.set(p.id,v)}let o=new Map,s=new Map;for(let p of e.response.checks){let v=vx(p);lo(e.projectRoot,v);let m=Xi(v),h=s.get(v.id);if(h!==void 0&&h!==m)throw new Error(`Native Verifier check ID ${v.id} refers to conflicting commands`);let g=a.get(v.id);if(g!==void 0&&g!==m)throw new Error(`Native Verifier check ID ${v.id} conflicts with a Runtime check`);s.set(v.id,m);let w=n.get(m);if(w?.status==="interrupted"&&!w.repeatable)throw new Error(`Native check ${w.id} was interrupted and is not repeatable; user resolution is required`);o.has(m)||o.set(m,v)}let c=[...o.entries()],l=c.filter(([p])=>!i.has(p));if(r.execution.requestCheckRounds>0&&l.length===0)throw new Error("Native Verifier repeatedly requested only equivalent checks");let f=r.execution.requestCheckRounds+1,u=new Map(c.map(([,p])=>[p.id,p.name])),d={...r,execution:{...r.execution,stage:"checking",actor:"runtime",executionId:e.envelope.verifierExecutionRef,requestCheckRounds:f},checks:[...r.checks.map(p=>{let v=Cl(p,e.projectRoot),m=o.get(v);return m&&p.status==="interrupted"?zh(p,m,r.execution.operationId,e.projectRoot):p}),...l.filter(([p])=>!n.has(p)).map(([,p])=>Rl(p,r.execution.operationId,e.projectRoot))]};return await L(t,d,{containedRoot:e.paths.runtimeDir}),{state:e.state,local:d,verifierExecutionRef:e.envelope.verifierExecutionRef,round:f,novelPlans:l.map(([,p])=>p),requestedNames:u,reusedCheckIds:c.filter(([p])=>i.has(p)).map(([,p])=>p.id),suppliedChecks:e.suppliedChecks}}async function wo(e){return x(e.paths,`update Verifier-requested checks ${e.reservation.state.name}`,async()=>{let t=await I(e.paths,e.reservation.state.name);if(t.state_version!==e.reservation.state.state_version||t.phase!=="verify"||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier request-checks state changed during execution");let r=D(e.paths,t.name),i=await ot(r),n=i?.execution;if(i===null||i.basedOnStateVersion!==t.state_version||n===null||n===void 0||n.operationId!==e.reservation.local.execution?.operationId||n.stage!=="checking"||n.actor!=="runtime"||n.status!=="running"||n.executionId!==e.reservation.verifierExecutionRef||n.requestCheckRounds!==e.reservation.round)throw new Error("Native Verifier request-checks reservation changed during execution");let a=e.update(i);return await L(r,a,{containedRoot:e.paths.runtimeDir}),a})}async function bx(e){let t;try{for(let r of e.reservation.novelPlans){let i=new Date().toISOString();t=await wo({paths:e.paths,reservation:e.reservation,update:a=>({...a,checks:a.checks.map(o=>o.id===r.id?{...o,status:"running",executionCount:o.executionCount+1,startedAt:i}:o)})});let n=await ml({projectRoot:e.projectRoot,runtimeDir:Ve(e.paths,e.reservation.state.name),operationId:e.reservation.local.execution.operationId,plan:r});t=await wo({paths:e.paths,reservation:e.reservation,update:a=>({...a,checks:a.checks.map(o=>o.id===r.id?{...o,status:n.status,exitCode:n.exitCode,startedAt:n.startedAt,completedAt:n.completedAt,log:n.logRef}:o)})})}t=await wo({paths:e.paths,reservation:e.reservation,update:r=>({...r,execution:{...r.execution,stage:"verifying",actor:"verifier",executionId:e.reservation.verifierExecutionRef}})})}catch(r){try{await wo({paths:e.paths,reservation:e.reservation,update:i=>({...i,execution:{...i.execution,status:"interrupted"},checks:i.checks.map(n=>n.status==="planned"||n.status==="running"?{...n,status:"interrupted"}:n)})})}catch{}throw r}return{checks:Lr({local:t,projectRoot:e.projectRoot,supplied:e.reservation.suppliedChecks,requestedNames:e.reservation.requestedNames}),requestChecks:{round:e.reservation.round,reusedCheckIds:e.reservation.reusedCheckIds,executedCheckIds:e.reservation.novelPlans.map(({id:r})=>r)}}}async function Kh(e){return x(e.paths,`dispatch portable verifier ${e.name}`,async()=>{let t=await I(e.paths,e.name),r=e.projectRoot??e.paths.projectRoot;await Mt({paths:e.paths,state:t});let i=(await xl({file:D(e.paths,t.name),portableState:t,projectRoot:r,branch:Te(r),containedRoot:e.paths.runtimeDir})).state;if(i.execution?.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="completed")throw new Error("Native check plan must be explicitly resolved before Verifier dispatch");Lr({local:i,projectRoot:r,supplied:e.checks});let n=Rh(t),a=await Ne({paths:e.paths,previous:t,next:n}),o=D(e.paths,t.name),s=Pl();return await L(o,{...i,basedOnStateVersion:a.state_version,execution:{operationId:s,stage:"verifying",actor:"verifier",executionId:e.verifierExecutionId??null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:i.checks.map(c=>({...c,operationId:s}))},{containedRoot:e.paths.runtimeDir}),a})}async function Yh(e){if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let t=await x(e.paths,`apply portable verifier ${e.name}`,async()=>{let r=await I(e.paths,e.name),i=e.projectRoot??e.paths.projectRoot;await Mt({paths:e.paths,state:r});let n=await Vr({paths:e.paths,state:r}),a=gx({state:r,local:n,envelope:e.envelope}),o;try{o=wl(a.payload)}catch(u){let d=`Native Verifier response was invalid: ${u.message}`,p=await yo({paths:e.paths,state:r,summary:d});throw new Error(`${d}; execution error ${p.loop.execution_failure_count}/${en} was recorded`,{cause:u})}let s=wx(o);if(s.iteration!==r.loop.iteration||s.attempt!==r.loop.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");let c=[],l;try{n!==null&&(c=Lr({local:n,projectRoot:i,supplied:e.checks}));let u=Ah({state:r,envelope:a,checks:c,maxVerifyFailures:e.maxVerifyFailures});if(u.response.kind==="request-checks"){if(n===null)throw new Error("Native Verifier request-checks has no active local execution");let d=await Nx({paths:e.paths,projectRoot:i,state:r,local:n,envelope:a,response:u.response,suppliedChecks:c});return{kind:"request-checks",state:r,response:u.response,reservation:d}}if(n===null||n.execution===null||n.execution.stage!=="verifying"||n.execution.actor!=="verifier"||n.execution.status!=="running")throw new Error("Native Verifier final result has no active local execution");if(n.execution.executionId!==null&&n.execution.executionId!==a.verifierExecutionRef)throw new Error("Native Verifier final result changed execution within the same attempt");l=u}catch(u){let d=`Native Verifier response was invalid: ${u.message}`,p=await yo({paths:e.paths,state:r,summary:d});throw new Error(`${d}; execution error ${p.loop.execution_failure_count}/${en} was recorded`,{cause:u})}let f=await Ne({paths:e.paths,previous:r,next:l.state});return await L(D(e.paths,r.name),f.loop.next_action==="resolve-verifier-blocker"||f.loop.next_action==="run-final-full-verification"?an({local:n,state:f,projectRoot:i}):oe({portableState:f,projectRoot:i,branch:Te(i)}),{containedRoot:e.paths.runtimeDir}),f.verification!==null&&await Br({file:ne.join(fe(e.paths,r.name),"verification.md"),state:f}),{kind:"final-result",result:{state:f,response:l.response,checks:c,requestChecks:null}}});if(t.kind==="final-result")return t.result;try{let r=await bx({paths:e.paths,projectRoot:e.projectRoot??e.paths.projectRoot,reservation:t.reservation});return{state:t.state,response:t.response,checks:r.checks,requestChecks:r.requestChecks}}catch(r){let i=`Native Verifier response was invalid: ${r.message}`,n=await x(e.paths,`record Verifier-requested check failure ${e.name}`,async()=>{let a=await I(e.paths,e.name);return a.state_version!==t.state.state_version?null:yo({paths:e.paths,state:a,summary:i})});throw new Error(n?`${i}; execution error ${n.loop.execution_failure_count}/${en} was recorded`:`${i}; the portable state changed before the execution error could be recorded`,{cause:r})}}async function Xh(e){return x(e.paths,`record portable verifier failure ${e.name}`,async()=>{let t=await I(e.paths,e.name),r=await Vr({paths:e.paths,state:t});if(Gh({state:t,local:r,expected:e.expected}),e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");return yo({paths:e.paths,state:t,summary:e.summary})})}async function Qh(e){return x(e.paths,`record unavailable portable verifier ${e.name}`,async()=>{let t=await I(e.paths,e.name);await Mt({paths:e.paths,state:t});let r=await Vr({paths:e.paths,state:t}),i=Gh({state:t,local:r,expected:e.expected});if(e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");let n=Lr({local:i,projectRoot:e.paths.projectRoot,supplied:[]}),a=Ih({state:t,checks:n,verifierExecutionRef:i.execution.executionId,summary:e.summary}),o=await Ne({paths:e.paths,previous:t,next:a});return await L(D(e.paths,t.name),an({local:i,state:o,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),await Br({file:ne.join(fe(e.paths,t.name),"verification.md"),state:o}),o})}async function Zh(e){return x(e.paths,`confirm portable Skill-coordinated pass ${e.name}`,async()=>{let t=await I(e.paths,e.name);cr({state:t,expected:e.expectedContinuation,action:"accept-result"}),await Mt({paths:e.paths,state:t});let r=await U(e.paths,e.name);if(r?.finalVerification.status==="pending"){if(zi(r).stateVersion!==r.stateVersion)return nm({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; rerun the final full verification."});await ie(e.paths,Ji(r,t))}let i=_h(t),n=await Ne({paths:e.paths,previous:t,next:i});return await L(D(e.paths,t.name),oe({portableState:n,projectRoot:e.paths.projectRoot,branch:Te(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await Br({file:ne.join(fe(e.paths,t.name),"verification.md"),state:n}),n})}async function kx(e){let t=await I(e.paths,e.name),r=await U(e.paths,e.name),i=await Ya(e.paths,{kind:"archive",change:e.name}),n=i?.kind==="archive"?i:null;if(n&&r?.finalVerification.status==="pending"){if(n.journal.status!=="prepared"||n.journal.next_spec_index!==0)throw new Error("Native Supervisor final verification changed after Archive applied side effects; doctor intervention is required");if(t.phase==="verify"&&t.status==="active"&&t.verification===null&&t.verification_result==="pending"&&t.loop.stage==="verify-ready")return await sr.rm(n.file,{force:!0}),{state:t,action:"rerun-final-verification"}}if(t.archived||t.verification===null||t.verification_result!=="pass"||r?.finalVerification.status!=="pending")return{state:t,action:"none"};let a=zi(r);if(n||a.stateVersion!==r.stateVersion){let o=await nm({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; the final full verification will resume automatically."});return n&&await sr.rm(n.file,{force:!0}),{state:o,action:"rerun-final-verification"}}return await ie(e.paths,Ji(r,t)),{state:t,action:"recorded-final-verification"}}async function Al(e){return x(e.paths,`recover Supervisor final verification ${e.name}`,()=>kx(e),{allowedPortableTransaction:{kind:"archive",change:e.name}})}async function em(e){return x(e.paths,`confirm unavailable portable verifier ${e.name}`,async()=>{let t=await I(e.paths,e.name);cr({state:t,expected:e.expectedContinuation,action:"confirm-verifier-unavailable"}),await Mt({paths:e.paths,state:t});let r=Th({state:t,summary:e.summary}),i=await Ne({paths:e.paths,previous:t,next:r});return await L(D(e.paths,t.name),oe({portableState:i,projectRoot:e.paths.projectRoot,branch:Te(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await Br({file:ne.join(fe(e.paths,t.name),"verification.md"),state:i}),i})}async function tm(e){return x(e.paths,`resolve portable verifier blocker ${e.name}`,async()=>{let t=await I(e.paths,e.name);cr({state:t,expected:e.expectedContinuation,action:"resolve-verifier-blocker"}),await Mt({paths:e.paths,state:t});let r=await Vr({paths:e.paths,state:t}),i=jh(t,{reason:e.reason}),n=await Ne({paths:e.paths,previous:t,next:i});return await L(D(e.paths,t.name),an({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function rm(e){return x(e.paths,`retry portable verifier ${e.name}`,async()=>{let t=await I(e.paths,e.name);cr({state:t,expected:e.expectedContinuation,action:"retry-verifier"});let r=await Vr({paths:e.paths,state:t}),i=Oh(t),n=await Ne({paths:e.paths,previous:t,next:i});return await L(D(e.paths,t.name),an({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function ko(e){return x(e.paths,`return portable change ${e.name} to Build`,async()=>{let t=await I(e.paths,e.name);if(cr({state:t,expected:e.expectedContinuation,action:"revise-implementation"}),t.phase==="build")return t;let r=tn({state:t,reason:e.reason}),i=await Ne({paths:e.paths,previous:t,next:r});return await L(D(e.paths,t.name),oe({portableState:i,projectRoot:e.paths.projectRoot,branch:Te(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),i})}async function So(e){return x(e.paths,`return portable change ${e.name} to Shape`,async()=>{let t=await I(e.paths,e.name);if(cr({state:t,expected:e.expectedContinuation,action:"revise-requirements"}),e.allowedPhases&&!e.allowedPhases.includes(t.phase))throw new Error("--revise-requirements is only valid from Verify or Archive");return t.phase==="shape"?t:im({paths:e.paths,state:t,reason:e.reason})})}async function im(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let i={...de(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:H(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"confirm-shape"}};delete i.children_contract_hash;let n=await Ne({paths:e.paths,previous:t,next:i});return await L(D(e.paths,t.name),oe({portableState:n,projectRoot:e.paths.projectRoot,branch:Te(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function nm(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);if(t.verification===null||t.verification_result!=="pass")throw new Error("Native Supervisor recovery requires a persisted final verification pass");let i={...de(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:H(e.reason),completed_at:new Date().toISOString()}),phase:"verify",status:"active",state_version:t.state_version+1,acceptance:t.acceptance.map(a=>({...a,result:"pending",reason:null})),blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{...t.loop,stage:"verify-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:"run-final-full-verification"}},n=await Ne({paths:e.paths,previous:t,next:i});return await L(D(e.paths,t.name),oe({portableState:n,projectRoot:e.paths.projectRoot,branch:Te(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function Eo(e){if(e.state.verification===null)return"not-applicable";let t=ne.join(fe(e.paths,e.state.name),"verification.md");return await Bh({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await Br({file:t,state:e.state}),"rebuilt")}var am=["evidence.md","repair.md","archive.md","checkpoint.md"],xx="verification.md";async function Cx(e,t){let r=await Ya(e,{kind:"migration",change:t});return r?.kind==="migration"?r.journal:null}async function om(e,t){await on.mkdir(e.transactionsDir,{recursive:!0}),await ge(Ka(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function sm(e,t,r={}){let i=r.removeVerificationReport===!1?am:[...am,xx];await Promise.all([on.rm(Ve(e,t),{recursive:!0,force:!0}),on.rm(xc(e,t),{recursive:!0,force:!0}),...i.map(n=>on.rm(Ex.join(rt(e,t),n),{force:!0}))])}async function cm(e,t){await L(D(e,t.name),oe({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function lm(e,t){try{let r=await Hi(e,t);if(r?.schema==="comet.native.workspace.v3")return{isolation:r.isolation,change_branch:r.changeBranch,target_branch:r.targetBranch,finish:r.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function um(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let r=W(e.projectRoot);if(!r.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(r.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${r.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!r.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function Px(e){let t=rt(e.paths,e.state.name),r=await Y({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),i=[];for(let n of e.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await Y({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return Ja({briefMarkdown:r.text,specs:i})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function dm(e,t){let r=await Ep(e,t);if(!r.state)throw new Error(`Native legacy change ${t} is unreadable`);return r.state}async function fm(e){return x(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await Cx(e.paths,e.name),r=await nn(e.paths,e.name)?await Me(Je(e.paths,e.name)):null;if(!t&&r)return await sm(e.paths,e.name,{removeVerificationReport:!1}),await cm(e.paths,r),r;let i=null,n=null;for(t||(i=await dm(e.paths,e.name),n=await lm(e.paths,e.name),um(e.paths,n),t={schema:Ga,id:Sx(),change:i.name,fromSchema:i.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await om(e.paths,t));;){let a=Op(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?r||(i??=await dm(e.paths,e.name),n??=await lm(e.paths,e.name),um(e.paths,n),r=$p({state:i,acceptance:await Px({paths:e.paths,state:i}),workspace:n,migratedAt:e.now}),await ja(Je(e.paths,e.name),r,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await sm(e.paths,e.name):a.action==="commit-transaction"&&(r??=await Me(Je(e.paths,e.name)),await cm(e.paths,r)),t={...t,status:a.nextStatus},await om(e.paths,t)}return await on.rm(Ka(e.paths,{kind:"migration",change:e.name}),{force:!0}),r??Me(Je(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as pm}from"node:fs";import hm from"node:path";function _l(e,t){let r=W(e.projectRoot);if(t.workspace.change_branch!==null){if(!r.isGitWorktree)return"The portable change requires a Git branch/worktree";if(r.currentBranch!==t.workspace.change_branch)return`Expected Native change branch ${t.workspace.change_branch}, current branch is ${r.currentBranch??"(detached)"}`}return t.workspace.isolation==="current"?null:r.isGitWorktree?t.workspace.isolation==="worktree"&&!r.isSecondaryWorktree?"The portable change requires its linked worktree":null:"The portable change requires a Git branch/worktree"}function Rx(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function Ax(e,t,r){let i=new Date().toISOString(),n=e.verification===null?e:de(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:H(t),completed_at:i});return P({...n,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:r?Rx(e):e.acceptance,verification:null,verification_result:"pending",verification_report:null,blockers:[],loop:{...e.loop,stage:"verify-ready",next_action:"run-required-checks-and-dispatch-verifier"}})}async function _x(e){try{let t=await ot(e);return t===null?{local:null,reason:"missing"}:{local:t,reason:"available"}}catch(t){if(t.code&&t.code!=="ENOENT")throw t;return{local:null,reason:"invalid"}}}async function Il(e){return x(e.paths,`recover portable change ${e.name}`,async()=>{let t=await I(e.paths,e.name);if(t.status==="done")return await Eo({paths:e.paths,state:t}),{state:t,local:null,action:"done",reason:"done",message:"Archived Native changes do not require a local execution overlay."};let r=_l(e.paths,t);if(r)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:r};let i=D(e.paths,e.name),n=await _x(i),a=n.reason==="available"&&(n.local?.change!==t.name||n.local?.basedOnStateVersion!==t.state_version)?"stale":n.reason;if(a==="available"&&!e.preserveRunningExecution&&n.local?.execution!==null&&n.local?.execution?.status!=="completed"&&n.local&&(a="interrupted",n.local.execution?.status==="running"&&(n.local={...n.local,execution:{...n.local.execution,status:"interrupted"},checks:n.local.checks.map(d=>d.status==="planned"||d.status==="running"?{...d,status:"interrupted"}:d)},await L(i,n.local,{containedRoot:e.paths.runtimeDir}))),a==="available")return await Eo({paths:e.paths,state:t}),{state:t,local:n.local,action:"resume-stable-boundary",reason:a,message:"Native local execution overlay matches the portable state."};let s=a==="interrupted"?n.local?.checks.find(d=>d.status==="interrupted"&&!d.repeatable):void 0;if(s){let d=tn({state:t,reason:`Check ${s.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await $i({file:Je(e.paths,t.name),expectedStateVersion:t.state_version,next:d,containedRoot:e.paths.nativeRoot}),await pm.rm(hm.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let p=oe({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await L(i,p,{containedRoot:e.paths.runtimeDir}),{state:t,local:p,action:"resume-stable-boundary",reason:a,message:`Native check ${s.id} was not repeatable; the change returned to Build for a new candidate.`}}let c=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",l=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",f=c||l;if(f){let d=Ax(t,l?"Local Runtime was unavailable at Archive ready; the synchronized implementation must be verified again.":"The previous Verifier execution was unavailable; dispatch a new attempt from the stable Verify boundary.",l);t=await $i({file:Je(e.paths,t.name),expectedStateVersion:t.state_version,next:d,containedRoot:e.paths.nativeRoot})}let u=oe({portableState:t,projectRoot:e.paths.projectRoot,branch:W(e.paths.projectRoot).currentBranch});return await pm.mkdir(hm.dirname(D(e.paths,t.name)),{recursive:!0}),await L(i,u,{containedRoot:e.paths.runtimeDir}),await Eo({paths:e.paths,state:t}),{state:t,local:u,action:f?"reverify":"resume-stable-boundary",reason:a,message:f?"Rebuilt local execution from the portable boundary; previous pass/execution was not reused.":`Rebuilt local execution from the portable ${t.phase}/${t.loop.stage} boundary.`}})}function Ix(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function Ee(e){let t=e.acceptance.reduce((r,i)=>({...r,[i.result]:r[i.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:r})=>r==="failed"||r==="blocked").map(({id:r})=>r),verification_result:e.verification_result,blockers:e.blockers.slice(0,8).map(r=>({owner:r.owner,reason:Ix(r.reason.text),acceptance_ids:r.acceptance_ids,resolution_action:r.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}}import{randomUUID as Nm}from"node:crypto";import{promises as mm}from"node:fs";import cn from"node:path";function Mr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function pe(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function B(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} must be non-empty text`);return e}function jl(e,t){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,i)=>B(r,`${t}[${i}]`))}function Tx(e){if(!Array.isArray(e))throw new Error("Native Builder checks must be an array");return e.map((t,r)=>{let i=Mr(t,`Native Builder check ${r}`);if(pe(i,["name","result","note"],`Native Builder check ${r}`),!["passed","failed","not-run"].includes(String(i.result)))throw new Error(`Native Builder check ${r} result is invalid`);if(i.note!==null&&typeof i.note!="string")throw new Error(`Native Builder check ${r} note is invalid`);return{name:B(i.name,`Native Builder check ${r} name`),result:i.result,note:i.note}})}function jx(e){if(!Array.isArray(e))throw new Error("Native Runtime checks must be an array");return e.map((t,r)=>{let i=Mr(t,`Native Runtime check ${r}`);if(pe(i,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Runtime check ${r}`),!Array.isArray(i.argv)||!i.argv.every(n=>typeof n=="string"))throw new Error(`Native Runtime check ${r} argv is invalid`);if(!Number.isSafeInteger(i.timeoutMs)||i.timeoutMs<1)throw new Error(`Native Runtime check ${r} timeoutMs is invalid`);if(typeof i.repeatable!="boolean")throw new Error(`Native Runtime check ${r} repeatable is invalid`);return{id:B(i.id,`Native Runtime check ${r} id`),name:B(i.name,`Native Runtime check ${r} name`),executable:B(i.executable,`Native Runtime check ${r} executable`),argv:[...i.argv],cwdRef:B(i.cwdRef,`Native Runtime check ${r} cwdRef`),timeoutMs:i.timeoutMs,repeatable:i.repeatable}})}function vm(e,t){let r=e.stateVersion,i=e.iteration,n=e.attempt;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${t} stateVersion is invalid`);if(!Number.isSafeInteger(i)||i<1)throw new Error(`${t} iteration is invalid`);if(!Number.isSafeInteger(n)||n<1)throw new Error(`${t} attempt is invalid`);return{stateVersion:r,iteration:i,attempt:n,verifierExecutionRef:B(e.verifierExecutionRef,`${t} verifierExecutionRef`)}}function $x(e){let t=Mr(e,"Native Supervisor evidence");return pe(t,["summary","checks"],"Native Supervisor evidence"),{summary:B(t.summary,"Native Supervisor evidence summary"),checks:jl(t.checks,"Native Supervisor evidence checks")}}function Ox(e){if(!Array.isArray(e))throw new Error("Native Supervisor integration checks must be an array");return e.map((t,r)=>{let i=Mr(t,`Native Supervisor integration check ${r}`),n=new Set(["name","status","reason"]);if(Object.keys(i).some(a=>!n.has(a)))throw new Error(`Native Supervisor integration check ${r} fields are invalid`);if(!Object.hasOwn(i,"name")||!Object.hasOwn(i,"status"))throw new Error(`Native Supervisor integration check ${r} fields are invalid`);if(!["passed","failed","incomplete"].includes(String(i.status)))throw new Error(`Native Supervisor integration check ${r} status is invalid`);if(i.reason!==void 0&&i.reason!==null&&typeof i.reason!="string")throw new Error(`Native Supervisor integration check ${r} reason is invalid`);return{name:B(i.name,`Native Supervisor integration check ${r} name`),status:i.status,reason:i.reason??null}})}function Hx(e){let t=Mr(e,"Native Runner input");if(t.kind==="builder-handoff"){pe(t,["kind","summary","addressed_acceptance_ids","checks","known_limits","review"],"Native Runner Builder input");let r=Mr(t.review,"Native Builder review");if(pe(r,["status","summary","reviewer_execution_ref"],"Native Builder review"),r.status!=="passed")throw new Error("Native Builder review status must be passed");return{kind:"builder-handoff",summary:B(t.summary,"Native Builder summary"),addressed_acceptance_ids:jl(t.addressed_acceptance_ids,"Native Builder addressed acceptance IDs"),checks:Tx(t.checks),known_limits:jl(t.known_limits,"Native Builder known limits"),review:{status:"passed",summary:B(r.summary,"Native Builder review summary"),reviewer_execution_ref:B(r.reviewer_execution_ref,"Native Builder reviewer execution ref")}}}if(t.kind==="dispatch-verifier")return pe(t,["kind","checks"],"Native Runner dispatch input"),{kind:"dispatch-verifier",checks:jx(t.checks)};if(t.kind==="verifier-response")return pe(t,["kind","response"],"Native Runner Verifier input"),{kind:"verifier-response",response:t.response};if(t.kind==="verifier-execution-error")return pe(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner execution error input"),{kind:"verifier-execution-error",summary:B(t.summary,"Native Verifier execution error summary"),...vm(t,"Native Runner execution error input")};if(t.kind==="verifier-unavailable")return pe(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner unavailable Verifier input"),{kind:"verifier-unavailable",summary:B(t.summary,"Native unavailable Verifier summary"),...vm(t,"Native Runner unavailable Verifier input")};if(t.kind==="supervisor-builder-result")return pe(t,["kind","child","runId","candidateCommit"],"Native Supervisor Builder input"),{kind:"supervisor-builder-result",child:B(t.child,"Native Supervisor child"),runId:B(t.runId,"Native Supervisor runId"),candidateCommit:B(t.candidateCommit,"Native Supervisor candidate commit")};if(t.kind==="supervisor-builder-failure")return pe(t,["kind","child","runId","reason"],"Native Supervisor Builder failure input"),{kind:"supervisor-builder-failure",child:B(t.child,"Native Supervisor child"),runId:B(t.runId,"Native Supervisor runId"),reason:B(t.reason,"Native Supervisor Builder failure reason")};if(t.kind==="supervisor-reconnect")return pe(t,["kind","child","runId"],"Native Supervisor reconnect input"),{kind:"supervisor-reconnect",child:B(t.child,"Native Supervisor child"),runId:B(t.runId,"Native Supervisor runId")};if(t.kind==="supervisor-cancel")return pe(t,["kind","child","runId","reason"],"Native Supervisor cancel input"),{kind:"supervisor-cancel",child:B(t.child,"Native Supervisor child"),runId:B(t.runId,"Native Supervisor runId"),reason:B(t.reason,"Native Supervisor cancellation reason")};if(t.kind==="supervisor-verifier-result"){if(pe(t,["kind","child","runId","verdict","evidence"],"Native Supervisor Verifier input"),!["pass","fail","incomplete"].includes(String(t.verdict)))throw new Error("Native Supervisor Verifier verdict is invalid");return{kind:"supervisor-verifier-result",child:B(t.child,"Native Supervisor child"),runId:B(t.runId,"Native Supervisor runId"),verdict:t.verdict,evidence:$x(t.evidence)}}if(t.kind==="supervisor-integrate")return pe(t,["kind","child","checks"],"Native Supervisor integration input"),{kind:"supervisor-integrate",child:B(t.child,"Native Supervisor child"),checks:Ox(t.checks)};throw new Error("Native Runner input kind is invalid")}async function bm(e,t){let r=cn.resolve(t,e),i=await mm.lstat(r);if(!i.isFile()||i.isSymbolicLink())throw new Error("Native Runner input must be a regular non-symlink file");let n;try{n=JSON.parse(await mm.readFile(r,"utf8"))}catch(a){throw new Error("Native Runner input must be valid JSON",{cause:a})}return Hx(n)}function gm(e){return`${Q}:${e}:${Nm()}`}function wm(e,t,r,i){if(cn.resolve(_(e.projectRoot,["rev-parse","--show-toplevel"]))!==cn.resolve(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree identity is invalid`);if(_(e.projectRoot,["branch","--show-current"])!==i)throw new Error(`Native Supervisor ${r} result came from the wrong Child worktree branch`);if(!ut(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree must be clean before returning a commit`);if(_(e.projectRoot,["rev-parse","HEAD"])!==t)throw new Error(`Native Supervisor ${r} result is not bound to the worktree HEAD`);try{_(e.projectRoot,["merge-base","--is-ancestor",e.baseCommit,t])}catch(s){throw new Error(`Native Supervisor ${r} result is not based on its task base commit`,{cause:s})}}function Dx(e,t){let r=W(e.projectRoot),i=cn.resolve(r.currentWorktreeRoot??"");if(!r.isGitWorktree||i!==cn.resolve(e.projectRoot))throw new Error("Native Supervisor task worktree identity is invalid");if(r.currentBranch!==t)throw new Error("Native Supervisor task is attached to the wrong Child branch");let n=_(e.projectRoot,["rev-parse","HEAD"]);if(e.role==="verifier"){if(!ut(e.projectRoot)||n!==e.baseCommit)throw new Error("Native Supervisor Verifier task worktree is not at its candidate commit");return}try{_(e.projectRoot,["merge-base","--is-ancestor",e.baseCommit,n])}catch(a){throw new Error("Native Supervisor Builder task base commit is not an ancestor of its HEAD",{cause:a})}}function sn(e){if(e.builder_handoff===null)throw new Error("Native Skill coordination has no current Builder candidate");if(e.builder_handoff.identity_provider!==Q)throw new Error("Native candidate is owned by a host identity adapter and cannot use the generic Skill coordination bridge");if(!e.builder_handoff.review)throw new Error("Native Skill coordination requires a passed read-only review");return e.builder_handoff}function Bx(e){return[...e.history].reverse().find(({outcome:t})=>t==="recovery")?.summary}function ym(e){let{paths:t,state:r,checks:i,verifierExecutionRef:n,supervisor:a}=e,o=sn(r);if(!o.review)throw new Error("Native Skill coordination requires a passed read-only review");let s=Bx(r),c=r.acceptance.filter(({result:l})=>l==="pending").map(({id:l})=>l);return{coordination:Q,change:r.name,candidateId:o.candidate_id,stateVersion:r.state_version,iteration:r.loop.iteration,attempt:r.loop.attempt,verifierExecutionRef:n,projectRoot:t.projectRoot,verificationRoot:a?.integration.worktree??t.projectRoot,changeDir:fe(t,r.name),supervisorStateRef:a?to(t,r.name):null,briefRef:r.brief,specRefs:r.spec_changes.map(({capability:l,operation:f,source:u})=>({capability:l,operation:f,ref:u})),acceptanceCount:r.acceptance.length,scopeIds:c,detailsPageArgs:["comet","native","status",r.name,"--details","--json","--project-root",t.projectRoot],...s===void 0?{}:{recoveryContext:s},builderReview:{status:o.review.status,summary:o.review.summary},runtimeChecks:i.map(l=>({...l}))}}async function Tl(e){sn(e.state);let t=await ot(D(e.paths,e.state.name));if(t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version||t.execution===null||t.execution.stage!=="verifying"||t.execution.actor!=="verifier"||t.execution.status!=="running"||t.execution.executionId===null)throw new Error("Native Skill coordination has no active Verifier attempt");return t.execution.executionId}async function km(e){let t=await U(e.paths,e.name),r=e.input,i=t?await I(e.paths,e.name):null,n=t!==null&&i?.phase==="verify"&&t.children.every(({status:p})=>p==="integrated"||p==="archived"),a=t!==null&&i?.phase==="build"&&t.children.every(({status:p})=>p==="integrated"||p==="archived");if(t&&r.kind==="supervisor-builder-result")return x(e.paths,`apply Native Supervisor Builder result ${r.child}`,async()=>{let p=await U(e.paths,e.name);if(!p)throw new Error(`Native Supervisor state is missing for ${e.name}`);let v=p.children.find(({name:y})=>y===r.child);if(!v?.task||v.task.role!=="builder")throw new Error(`Native Supervisor Builder task is not active for ${r.child}`);try{wm(v.task,r.candidateCommit,"builder",`comet/supervisor/${p.parent}/${r.child}`)}catch(y){throw await ie(e.paths,io(p,{child:r.child,runId:r.runId,reason:y.message})),y}let m=v.task.projectRoot,h=nh(p,r),g=il(h,{role:"verifier",child:r.child,projectRoot:m,runId:Nm()});await ie(e.paths,g.state);let w=await I(e.paths,e.name);return{state:w,supervisorTask:g.task,checks:[],requestChecks:null,verifierDispatch:null,continuation:X(w)}});if(t&&r.kind==="supervisor-builder-failure")return x(e.paths,`cancel Native Supervisor Builder task ${r.child}`,async()=>{let p=await U(e.paths,e.name);if(!p)throw new Error(`Native Supervisor state is missing for ${e.name}`);let v=p.children.find(({name:g})=>g===r.child);if(!v?.task||v.task.role!=="builder")throw new Error(`Native Supervisor Builder failure is not valid for ${r.child}`);let m=al(p,{child:r.child,runId:r.runId,reason:r.reason});await ie(e.paths,m);let h=await I(e.paths,e.name);return{state:h,supervisorState:m,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:X(h)}});if(t&&r.kind==="supervisor-reconnect")return x(e.paths,`reconnect Native Supervisor task ${r.child}`,async()=>{let p=await U(e.paths,e.name);if(!p)throw new Error(`Native Supervisor state is missing for ${e.name}`);let v=p.children.find(({name:g})=>g===r.child)?.task;if(!v||v.runId!==r.runId)throw new Error(`Native Supervisor task runId is not current for ${r.child}`);try{Dx(v,`comet/supervisor/${p.parent}/${r.child}`)}catch(g){throw await ie(e.paths,io(p,{child:r.child,runId:r.runId,reason:g.message})),g}let m=rh(p,{child:r.child,runId:r.runId});await ie(e.paths,m.state);let h=await I(e.paths,e.name);return{state:h,supervisorState:m.state,supervisorTask:m.task,checks:[],requestChecks:null,verifierDispatch:null,continuation:X(h)}});if(t&&r.kind==="supervisor-cancel")return x(e.paths,`cancel Native Supervisor task ${r.child}`,async()=>{let p=await U(e.paths,e.name);if(!p)throw new Error(`Native Supervisor state is missing for ${e.name}`);let v=al(p,{child:r.child,runId:r.runId,reason:r.reason});await ie(e.paths,v);let m=await I(e.paths,e.name);return{state:m,supervisorState:v,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:X(m)}});if(t&&r.kind==="supervisor-verifier-result")return x(e.paths,`apply Native Supervisor Verifier result ${r.child}`,async()=>{let p=await U(e.paths,e.name);if(!p)throw new Error(`Native Supervisor state is missing for ${e.name}`);let v=p.children.find(({name:g})=>g===r.child);if(!v?.task||v.task.role!=="verifier"||!v.candidateCommit)throw new Error(`Native Supervisor Verifier task is not active for ${r.child}`);try{wm(v.task,v.candidateCommit,"verifier",`comet/supervisor/${p.parent}/${r.child}`)}catch(g){throw await ie(e.paths,io(p,{child:r.child,runId:r.runId,reason:g.message})),g}let m=ah(p,r);await ie(e.paths,m);let h=await I(e.paths,e.name);return{state:h,supervisorState:m,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:X(h)}});if(t&&r.kind==="supervisor-integrate"){let p=await oh({paths:e.paths,state:t,name:r.child,checks:r.checks}),v=await bo({paths:e.paths,name:e.name,trigger:"v2-integrate"}),m=v.state;return{state:m,supervisorState:p,supervisorTask:null,checks:r.checks,requestChecks:null,verifierDispatch:null,parentAdvance:v.parentAdvance,continuation:X(m)}}if(t&&(r.kind==="builder-handoff"||r.kind==="dispatch-verifier"||r.kind==="verifier-response"||r.kind==="verifier-execution-error"||r.kind==="verifier-unavailable"||r.kind==="supervisor-builder-result"||r.kind==="supervisor-builder-failure"||r.kind==="supervisor-reconnect"||r.kind==="supervisor-cancel"||r.kind==="supervisor-verifier-result")&&!n&&!(r.kind==="builder-handoff"&&a))throw new Error("Native Supervisor accepts only Supervisor task result inputs until every Child is integrated");if(r.kind==="builder-handoff"){let v=gl().captureExecutionIdentity({identityProvider:Q,executionRef:gm("builder")}),m=await Wh({paths:e.paths,name:e.name,input:{identity:v,summary:r.summary,addressedAcceptanceIds:r.addressed_acceptance_ids,checks:r.checks,knownLimits:r.known_limits,review:{status:r.review.status,summary:r.review.summary,reviewerExecutionRef:r.review.reviewer_execution_ref}}});return{state:m,checks:[],requestChecks:null,verifierDispatch:null,continuation:X(m)}}if(r.kind==="dispatch-verifier"){if(n&&r.checks.length===0)throw new Error("Native Supervisor parent verification requires at least one check");let p=await I(e.paths,e.name);if(p.builder_handoff!==null&&p.builder_handoff.identity_provider!==Q){let w=await ko({paths:e.paths,name:e.name,reason:"The previous Builder identity provider is unavailable to the generic Skill bridge; submit a new Builder candidate before dispatching a Verifier."});return{state:w,checks:[],requestChecks:null,verifierDispatch:null,continuation:X(w)}}sn(p);let m=(p.loop.next_action==="run-final-full-verification"&&p.verification?.verdict==="pass"&&p.verification.checks.every(({status:w})=>w==="passed")?p.verification.checks:null)??(await Uh({paths:e.paths,name:e.name,plans:r.checks,...n&&t?{projectRoot:t.integration.worktree}:{}})).checks,h=gm("verifier"),g=await Kh({paths:e.paths,name:e.name,checks:m,verifierExecutionId:h,...n&&t?{projectRoot:t.integration.worktree}:{}});return{state:g,checks:m,requestChecks:null,verifierDispatch:ym({paths:e.paths,state:g,checks:m,verifierExecutionRef:h,supervisor:n?t:null}),continuation:X(g)}}if(r.kind==="verifier-execution-error"){let p=await I(e.paths,e.name);sn(p),await Tl({paths:e.paths,state:p});let v=await Xh({paths:e.paths,name:e.name,summary:r.summary,expected:r,requireSkillCoordination:!0});return{state:v,checks:[],requestChecks:null,verifierDispatch:null,continuation:X(v)}}if(r.kind==="verifier-unavailable"){let p=await Qh({paths:e.paths,name:e.name,summary:r.summary,expected:r,requireSkillCoordination:!0});return{state:p,checks:p.verification?.checks??[],requestChecks:null,verifierDispatch:null,continuation:X(p)}}if(r.kind!=="verifier-response")throw new Error("Native Runner input kind is invalid for the portable verifier bridge");let o=await I(e.paths,e.name),s=sn(o),c=await Tl({paths:e.paths,state:o}),l=gl(),f=l.captureExecutionIdentity({identityProvider:Q,executionRef:c}),u=null;if(n&&typeof r.response=="object"&&r.response!==null&&"kind"in r.response&&r.response.kind==="final-result"){let p=await U(e.paths,e.name);if(!p)throw new Error("Native Supervisor state disappeared before final verification");u=zi(p)}let d=await Yh({paths:e.paths,name:e.name,envelope:l.envelopeVerifierResponse({candidateId:s.candidate_id,identity:f,payload:r.response}),checks:[],maxVerifyFailures:e.maxVerifyFailures,...n&&t?{projectRoot:t.integration.worktree}:{}});if(n&&d.response.kind==="final-result"){if(d.state.verification_result==="pass"&&(d.checks.length===0||d.checks.some(({status:m})=>m!=="passed")))throw new Error("Native Supervisor parent verification cannot pass without completed integration checks");let p=u??await U(e.paths,e.name);if(!p)throw new Error("Native Supervisor state disappeared during verification");let v=Ji(p,d.state);return await ie(e.paths,v),{...d,supervisorState:v,verifierDispatch:null,continuation:X(d.state)}}return{...d,verifierDispatch:d.requestChecks===null?null:ym({paths:e.paths,state:d.state,checks:d.checks,verifierExecutionRef:await Tl({paths:e.paths,state:d.state}),supervisor:n?t:null}),continuation:X(d.state)}}import un from"path";import{realpathSync as $C}from"fs";var vt={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function Sm(e){return e?e.command?`${vt.next} ${e.command}`:e.ask_user?`${vt.next} ${e.ask_user}`:null:null}function Em(e,t){let r=[e.summary],i=Sm(e.next);return i&&r.push(i),e.user_message&&r.push("",vt.relay,e.user_message),t!==void 0&&r.push("",vt.details,JSON.stringify(t,null,2)),`${r.join(`
243
+ `)}
244
+ `}function xm(e,t,r){let i=[e.summary],n=Sm(e.next);return n&&i.push(n),e.user_message&&i.push("",vt.relay,e.user_message),i.push("",`${vt.detail} ${t}`),r!==void 0&&i.push("",vt.details,JSON.stringify(r,null,2)),i.join(`
245
+ `)}var Vx=["outcome","scope","nonGoals","acceptanceExamples"],KO=[...Vx,"constraints","decisions","openQuestions","verificationExpectations"];var Mx=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});var Cm=1024*1024;var Rm="scoped-text-safety",Fx=1,qx=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var Wx="comet.native.checker-policy.v1";var d0=ve(Wx,{policy:Rm,version:Fx,limits:qx,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var zx=["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"],f0=new Set(zx);var Ux=Cm,A0=3*Ux;var Am={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:[]},Yx=_e("comet-native-runtime:v3:scope-reopen"),rH=[{skillVersion:"3",skillHash:_e("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:_e("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:_e("comet-native-runtime:v1")}];var Im=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],HH=new Set(Im),iC=new Set([...Im,"minimum_runtime_version","revision"]),DH=new Set([...iC,"operation"]),BH=512*1024,nC=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),LH=new Set([...nC,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);var WH={maxAcceptanceCriteria:za.maxCriteria};var KH={maxSpecs:64,maxFileBytes:fa,maxTotalBytes:4*1024*1024};import{execFile as pC}from"node:child_process";import{promisify as hC}from"node:util";var aD={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};var CD=512*1024;var ln=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};var KD=64*1024;var YD=3600*1e3;var XD=hC(pC);var xo=class extends Error{details;constructor(t){let r=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(i=>`${i.ref}${i.acceptanceId?`[${i.acceptanceId}]`:""} -> ${i.mismatches.join("; ")}`).join(" | ")}`;super(r),this.name="NativeVerificationReceiptBindingError",this.details=t}};var HB={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var JB=16*1024*1024,GB=256*1024,UB=16*1024;var eL=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var iL=16*1024;var mL=16*1024;var aV=16*1024*1024,Co=class extends Error{constructor(r,i,n,a){super(`Canonical spec conflict for ${r}: expected ${i??"(missing)"}, actual ${n??"(missing)"}`);this.capability=r;this.expectedHash=i;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},Po=class extends Error{constructor(r,i=r.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${r.findingCodes.join(", ")}`){super(i);this.preflight=r;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};function R(e,t,r){return e==="zh-CN"?r:t}var $l={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function $m(e,t){return typeof e=="string"&&$l[e]?R(t,$l[e].en,$l[e].zh):typeof e=="string"?e:""}function Ol(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 NC(e){let t={total:e.length,passed:0,failed:0,blocked:0,pending:0};for(let r of e){if(!r||typeof r!="object")return null;let i=r.result;if(i!=="passed"&&i!=="failed"&&i!=="blocked"&&i!=="pending")return null;t[i]+=1}return t}function Om(e,t){let r=[];e.failed>0&&r.push(R(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(R(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(R(t,`${e.pending} pending`,`${e.pending} 项待验`));let i=R(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function Hm(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 r=t.userCommunication;return!!(r&&typeof r=="object"&&typeof r.required=="boolean"&&(r.message===null||typeof r.message=="string")&&typeof r.agentInstruction=="string")}function Hl(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function bC(e,t,r){return e==="done"?R(r,"complete","已完成"):e==="await-user"?R(r,"waiting for a user decision","等待用户决定"):e==="blocked"?R(r,"paused: needs attention","已暂停,需要处理"):t?R(r,"waiting for a user decision","等待用户决定"):R(r,"ready to continue","可继续推进")}function kC(e,t,r){let i=Hl(e),n=[];r&&n.push(r);let a=R(i,`Change ${e.change}`,`需求 ${e.change}`),o=$m(e.phase,i),s=bC(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(Om(t,i));let c=e.userCommunication,l=Dm(e,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function Dm(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:R(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:R(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(e.disposition==="blocked")return{ask_user:R(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function SC(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function EC(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=$m(e.phase,t),n=e.status==="await-user"?R(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?R(t,"paused","已暂停"):e.status==="done"?R(t,"complete","已完成"):R(t,"in progress","进行中"),a=Ol(e.acceptance)?`${R(t,", ",",")}${Om(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function xC(e){for(let t of e){let r=t.continuation;if(r?.userCommunication&&typeof r.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(r.userCommunication.agentInstruction))return"zh-CN"}return"en"}function CC(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 PC(e){if(e.healthy){let i=e.repaired?R("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):R("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=RC(e.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:R("en",r>0?`Diagnostics found ${r} problem${r===1?"":"s"} that need attention before this change can continue.`:"Diagnostics found problems that need attention before this change can continue.",r>0?`诊断发现 ${r} 个需要处理的问题,处理后该需求才能继续。`:"诊断发现需要处理的问题,处理后该需求才能继续。"),next:{ask_user:R("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function RC(e){return Hm(e)?Dm(e,Hl(e)):void 0}function Bm(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(CC(t))return PC(t);if(SC(t)){let i=xC(t.items);return{summary:[t.total===t.items.length?R(i,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):R(i,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>EC(a,i))].join(`
246
+ `)}}let r=t.continuation;if(Hm(r))return kC(r,AC(t),_C(t,Hl(r)));if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let i=t.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in t;return{summary:R(i,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 AC(e){if(Ol(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(Ol(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return NC(r.acceptance)}return null}function _C(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return R(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?R(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function Lm(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"conflict":return{summary:R("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 r.change=="string"?{next:{command:`comet native status ${r.change} --json`}}:{}};case"baseline-incomplete":return{summary:R("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:R("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:R("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:R("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:R("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:R("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:R("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:R("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}var Vm=["--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."],Bl=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:Vm,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>]
247
+ 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]
248
+ 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 Dl(e,t){return`${e}:
245
249
  ${t.map(r=>` ${r}`).join(`
246
- `)}`}function Jx(e){let t=e.filter(i=>i!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return El[r]||t.length>1&&El[t[0]]?.subcommands?r:t[0]}function Gx(e=[]){let t=Jx(e),r=El[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.subcommands&&i.push("",Sl("Commands",r.subcommands));let n=t===""?r.options:[...r.options??[],...mm];return n&&n.length>0&&i.push("",Sl("Options",n)),i.push("",`Output:
247
- ${r.output}`),r.examples&&i.push("",Sl("Examples",r.examples)),t===""&&i.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${i.join(`
250
+ `)}`}function IC(e){let t=e.filter(i=>i!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return Bl[r]||t.length>1&&Bl[t[0]]?.subcommands?r:t[0]}function TC(e=[]){let t=IC(e),r=Bl[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.subcommands&&i.push("",Dl("Commands",r.subcommands));let n=t===""?r.options:[...r.options??[],...Vm];return n&&n.length>0&&i.push("",Dl("Options",n)),i.push("",`Output:
251
+ ${r.output}`),r.examples&&i.push("",Dl("Examples",r.examples)),t===""&&i.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${i.join(`
248
252
  `)}
249
- `}}var Ux=Gx().usage;var TL=10*1024*1024,B=class extends Error{};function ft(e,t){let r=e.flatMap((i,n)=>i===t?[n]:[]);if(r.length>1)throw new B(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function ht(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new B(`${t} may only be provided once`);if(r.length===0)return;let i=r[0],n=e[i+1];if(n===void 0||n.startsWith("--"))throw new B(`${t} requires a value`);return e.splice(i,2),n}function gm(e){if(e.length>0)throw new B(`Unexpected argument: ${e[0]}`)}function wm(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new B(`${t} is required`);return r}function xl(e,t){let r=en.normalize(vm(e)),i=en.normalize(vm(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function vm(e){let t=en.resolve(e);try{return Kx.native(t)}catch{return t}}function Yx(e){let t=en.resolve(e),r=F(process.cwd());if(!r.isSecondaryWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null)return t;let i=F(t);return!i.isGitWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null||!xl(r.primaryWorktreeRoot,i.primaryWorktreeRoot)||xl(r.currentWorktreeRoot,i.currentWorktreeRoot)?t:xl(process.cwd(),r.currentWorktreeRoot)?en.resolve(process.cwd()):r.currentWorktreeRoot}async function ym(e){return e?Yx(e):ha(process.cwd())}async function Nm(e){let t=await Hf({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function pt(e,t,r){return{command:e,exitCode:0,data:t,text:r??JSON.stringify(t,null,2)+`
250
- `}}function bm(e,t){if(t instanceof B)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof mo)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 vo)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof _a)return{command:e,exitCode:73,data:{change:t.change,expectedRevision:t.expectedRevision,actualRevision:t.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:t.message}};if(t instanceof _i)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 Tt)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Ia)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 po)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof Zi)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let r=t.code;if(r&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(r))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let i=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:i?73:65,error:{code:i?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function km(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}})+`
251
- `}:e.error?{exitCode:e.exitCode,stderr:e.error.message}:{exitCode:e.exitCode,stdout:e.text}}var Xx=new Set(["confirm-shape","accept-result","confirm-verifier-unavailable","revise-implementation","revise-requirements","retry-verifier","resolve-verifier-blocker"]);function Qx(e){let t=ht(e,"--expected-state-version"),r=ht(e,"--expected-action");if(!(t===void 0&&r===void 0)){if(t===void 0||r===void 0)throw new B("--expected-state-version and --expected-action must be provided together");if(!/^[1-9]\d*$/u.test(t)||!Number.isSafeInteger(Number(t)))throw new B("--expected-state-version must be a positive integer");if(!Xx.has(r))throw new B("--expected-action is not a recognized Native continuation action");return{stateVersion:Number(t),action:r}}}async function Or(e,t){let r=await Ze({paths:e,state:t});return{...r?{childSummary:r.children.reduce((i,n)=>({...i,[n.status]:(i[n.status]??0)+1}),{total:r.children.length}),readyChildren:r.readyChildren}:{},continuation:U(t,r)}}function Zx(e){return Object.fromEntries(Object.entries(e).filter(([t])=>t!=="state"&&t!=="response"&&t!=="supervisorState"))}function Sm(e){return{action:e.action,reason:e.reason,message:e.message}}async function Em(e,t){let r=wm(e,"change name"),i=ht(e,"--summary"),n=ht(e,"--runner-input"),a=ft(e,"--confirmed"),o=ft(e,"--accept-result"),s=ft(e,"--revise-implementation"),c=ft(e,"--revise-requirements"),l=ft(e,"--retry-verifier"),f=ft(e,"--resolve-verifier-blocker"),d=ht(e,"--coordination-mode"),u=d;if(d!==void 0&&!ga.includes(d))throw new B("--coordination-mode must be multi-session or single-session");if(u!==void 0&&!a)throw new B("--coordination-mode is only valid with --confirmed in Shape");let h=ht(e,"--max-parallel"),v=h===void 0?2:Number(h);if(!Number.isSafeInteger(v)||v<1)throw new B("--max-parallel must be a positive integer");let m=Qx(e);if([a,o,s,c,l,f].filter(Boolean).length>1)throw new B("--confirmed, --accept-result, --revise-implementation, --revise-requirements, --retry-verifier, and --resolve-verifier-blocker are mutually exclusive");gm(e);let p=await Nm(t);if(!await Ui(p.paths,r)){if(n)throw new B("--runner-input is only valid for portable Native changes");if(!i)throw new B("--summary is required");let S=await Yp({paths:p.paths,name:r});return pt("next",{state:rt(S),migration:{completed:!0,summary:i},continuation:U(S)})}if(n){if(i||a||o||s||c||l||f||m)throw new B("--runner-input cannot be combined with --summary, continuation expectations, or Agent transition flags");let S=await Nl({paths:p.paths,name:r,preserveRunningExecution:!0}),E=S.state;if(S.action==="await-user"||S.action==="done"||S.reason!=="available")return pt("next",{state:rt(E),recovery:Sm(S),...await Or(p.paths,E)});if(E.phase==="build"){let _=await co({paths:p.paths,state:E});if(_.drifted){let $=await fo({paths:p.paths,name:r,reason:_.reason??"Native confirmed requirements changed"});return pt("next",{state:rt($),...await Or(p.paths,$)})}let Y=await re(p.paths,r),ee=await Ze({paths:p.paths,state:E});if(ee&&!ee.allDone&&!Y)throw new B("Native parent Build advances child changes and does not accept a Builder handoff")}let x=await am(n,t),N=await om({paths:p.paths,name:r,input:x,maxVerifyFailures:p.config.native.max_verify_failures});return pt("next",{...Zx(N),state:rt(N.state),...await Or(p.paths,N.state),coordination:K})}let y=await Nl({paths:p.paths,name:r}),g=y.state;if(u!==void 0&&g.phase!=="shape")throw new B("--coordination-mode is only valid when confirming Shape");if(!i)throw new B("--summary is required");let w,k=null;if(a)if(g.phase==="shape")w=await Rp({paths:p.paths,name:r,...u===void 0?{}:{coordinationMode:u},expectedContinuation:m});else if(g.phase==="verify"&&g.status==="await-user"&&g.loop.next_action==="confirm-verifier-unavailable")w=await Lp({paths:p.paths,name:r,summary:i,expectedContinuation:m});else throw new B("--confirmed is only valid in Shape or for a user-accepted degraded verification fallback");else if(o){if(!m&&(g.phase!=="verify"||g.status!=="await-user"||g.loop.next_action!=="confirm-skill-coordinated-pass"))throw new B("--accept-result is only valid for a pending Verify pass decision");w=await Bp({paths:p.paths,name:r,expectedContinuation:m})}else if(s){if(g.phase!=="verify")throw new B("--revise-implementation is only valid from Verify");w=await uo({paths:p.paths,name:r,reason:i,expectedContinuation:m})}else if(c){if(!m&&g.phase!=="verify"&&g.phase!=="archive")throw new B("--revise-requirements is only valid from Verify or Archive");w=await fo({paths:p.paths,name:r,reason:i,allowedPhases:["verify","archive"],expectedContinuation:m})}else if(l)w=await Mp({paths:p.paths,name:r,expectedContinuation:m});else if(f)w=await Vp({paths:p.paths,name:r,expectedContinuation:m});else{if(y.reason!=="available")return pt("next",{state:rt(g),recovery:Sm(y),...await Or(p.paths,g)});if(g.phase==="build"){let E=await co({paths:p.paths,state:g});if(E.drifted)w=await fo({paths:p.paths,name:r,reason:E.reason??"Native confirmed requirements changed"});else{let x=await Ze({paths:p.paths,state:g});if(x){let N=x,_=[],Y=await re(p.paths,r);if(Y&&!x.allDone){let ee=await Wh({paths:p.paths,parent:r,maxParallel:v});_=ee.tasks,(_.length>0||ee.state.stateVersion!==Y.stateVersion)&&(N=await Ze({paths:p.paths,state:g})??N)}if(N.allDone&&!(g.loop.stage==="repairing"&&g.verification_result==="fail"))k=await lo({paths:p.paths,name:r,trigger:"recovery"}),w=k.state;else return pt("next",{state:rt(g),childSummary:N.children.reduce((ee,$)=>({...ee,[$.status]:(ee[$.status]??0)+1}),{total:N.children.length}),readyChildren:N.readyChildren,..._.length>0?{supervisorTasks:_}:{},continuation:U(g,N)})}}}if(w)return pt("next",{state:rt(w),...k?{parentAdvance:k.parentAdvance}:{},...await Or(p.paths,w)});let S=g.phase==="shape"?await Ze({paths:p.paths,state:g}):null;return{command:"next",exitCode:65,data:{state:rt(g),continuation:U(g,S)},error:{code:"invalid-data",message:"This Native step requires the skill-coordinated --runner-input action returned by continuation; public JSON cannot supply identity, provider, execution ref, or candidate binding"}}}return pt("next",{state:rt(w),...u===void 0?{}:{coordinationMode:u},...await Or(p.paths,w)})}function eP(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}})+`
252
- `}}async function xm(e,t,r=process.argv.slice(2)){let i=r.indexOf("--"),n=i<0?[...r]:r.slice(0,i),a=i<0?[]:r.slice(i),o=n.includes("--json"),s,c;try{ft(n,"--json"),s=ht(n,"--project-root");let f=[...n,...a],d=await ym(s);c=await t(f,d)}catch(f){c=bm(e,f)}let l=o?eP(c):km(c,!1);return l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr+(l.stderr.endsWith(`
253
+ `}}var jC=TC().usage;var EV=10*1024*1024,V=class extends Error{};function st(e,t){let r=e.flatMap((i,n)=>i===t?[n]:[]);if(r.length>1)throw new V(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function gt(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new V(`${t} may only be provided once`);if(r.length===0)return;let i=r[0],n=e[i+1];if(n===void 0||n.startsWith("--"))throw new V(`${t} requires a value`);return e.splice(i,2),n}function Fm(e){if(e.length>0)throw new V(`Unexpected argument: ${e[0]}`)}function qm(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new V(`${t} is required`);return r}function Ll(e,t){let r=un.normalize(Mm(e)),i=un.normalize(Mm(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function Mm(e){let t=un.resolve(e);try{return $C.native(t)}catch{return t}}function OC(e){let t=un.resolve(e),r=W(process.cwd());if(!r.isSecondaryWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null)return t;let i=W(t);return!i.isGitWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null||!Ll(r.primaryWorktreeRoot,i.primaryWorktreeRoot)||Ll(r.currentWorktreeRoot,i.currentWorktreeRoot)?t:Ll(process.cwd(),r.currentWorktreeRoot)?un.resolve(process.cwd()):r.currentWorktreeRoot}async function Wm(e){return e?OC(e):Ea(process.cwd())}async function zm(e){let t=await Yf({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function Jm(e){return JSON.stringify(e,null,2)+`
254
+ `}function je(e,t,r){return{command:e,exitCode:0,data:t,text:r??Jm(t)}}function HC(e,t){if(t instanceof V)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Co)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 Po)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof Fa)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 Di)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 Dt)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof qa)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 xo)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof ln)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let r=t.code;if(r&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(r))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let i=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:i?73:65,error:{code:i?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function Gm(e,t){let r=HC(e,t),i=r.error;if(!i)return r;let n=Lm({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function Um(e,t,r=!1){let i=e.envelope??Bm(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...i===void 0?{}:{summary:i.summary,...i.next===void 0?{}:{next:i.next},...i.user_message===void 0?{}:{user_message:i.user_message}},...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
255
+ `}:e.error?{exitCode:e.exitCode,stderr:i?xm(i,e.error.message,r?e.data:void 0):e.error.message}:i?{exitCode:e.exitCode,stdout:Em(i,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==Jm(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
256
+ ${vt.details}
257
+ ${JSON.stringify(e.data,null,2)}
258
+ `}:{exitCode:e.exitCode,stdout:e.text}}var DC=new Set(["confirm-shape","accept-result","confirm-verifier-unavailable","revise-implementation","revise-requirements","retry-verifier","resolve-verifier-blocker"]);function BC(e){let t=gt(e,"--expected-state-version"),r=gt(e,"--expected-action");if(!(t===void 0&&r===void 0)){if(t===void 0||r===void 0)throw new V("--expected-state-version and --expected-action must be provided together");if(!/^[1-9]\d*$/u.test(t)||!Number.isSafeInteger(Number(t)))throw new V("--expected-state-version must be a positive integer");if(!DC.has(r))throw new V("--expected-action is not a recognized Native continuation action");return{stateVersion:Number(t),action:r}}}async function wt(e,t){let r=await nt({paths:e,state:t});return{...r?{childSummary:r.children.reduce((i,n)=>({...i,[n.status]:(i[n.status]??0)+1}),{total:r.children.length}),readyChildren:r.readyChildren}:{},continuation:X(t,r)}}function LC(e){return Object.fromEntries(Object.entries(e).filter(([t])=>t!=="state"&&t!=="response"&&t!=="supervisorState"))}function Km(e){return{action:e.action,reason:e.reason,message:e.message}}async function Ym(e,t){let r=qm(e,"change name"),i=gt(e,"--summary"),n=gt(e,"--runner-input"),a=st(e,"--confirmed"),o=st(e,"--accept-result"),s=st(e,"--revise-implementation"),c=st(e,"--revise-requirements"),l=st(e,"--retry-verifier"),f=st(e,"--resolve-verifier-blocker"),u=gt(e,"--coordination-mode"),d=u;if(u!==void 0&&!Ra.includes(u))throw new V("--coordination-mode must be multi-session or single-session");if(d!==void 0&&!a)throw new V("--coordination-mode is only valid with --confirmed in Shape");let p=gt(e,"--max-parallel"),v=p===void 0?2:Number(p);if(!Number.isSafeInteger(v)||v<1)throw new V("--max-parallel must be a positive integer");let m=BC(e);if([a,o,s,c,l,f].filter(Boolean).length>1)throw new V("--confirmed, --accept-result, --revise-implementation, --revise-requirements, --retry-verifier, and --resolve-verifier-blocker are mutually exclusive");Fm(e);let h=await zm(t);if(!await nn(h.paths,r)){if(n)throw new V("--runner-input is only valid for portable Native changes");if(!i)throw new V("--summary is required");let b=await fm({paths:h.paths,name:r});return je("next",{state:Ee(b),migration:{completed:!0,summary:i},continuation:X(b)})}let g=await I(h.paths,r),w=_l(h.paths,g);if(w)return je("next",{state:Ee(g),recovery:{action:"await-user",reason:"workspace-mismatch",message:w},...await wt(h.paths,g)});if(n){if(i||a||o||s||c||l||f||m)throw new V("--runner-input cannot be combined with --summary, continuation expectations, or Agent transition flags");let b=await Al({paths:h.paths,name:r});if(b.action==="rerun-final-verification")return je("next",{state:Ee(b.state),...await wt(h.paths,b.state)});let T=await Il({paths:h.paths,name:r,preserveRunningExecution:!0}),F=T.state;if(T.action==="await-user"||T.action==="done"||T.reason!=="available")return je("next",{state:Ee(F),recovery:Km(T),...await wt(h.paths,F)});if(F.phase==="build"){let yt=await No({paths:h.paths,state:F});if(yt.drifted){let Vl=await So({paths:h.paths,name:r,reason:yt.reason??"Native confirmed requirements changed"});return je("next",{state:Ee(Vl),...await wt(h.paths,Vl)})}let Ft=await U(h.paths,r),qr=await nt({paths:h.paths,state:F});if(qr&&!qr.allDone&&!Ft)throw new V("Native parent Build advances child changes and does not accept a Builder handoff")}let Z=await bm(n,t),j=await km({paths:h.paths,name:r,input:Z,maxVerifyFailures:h.config.native.max_verify_failures});return je("next",{...LC(j),state:Ee(j.state),...await wt(h.paths,j.state),coordination:Q})}let y=await Al({paths:h.paths,name:r});if(y.action==="rerun-final-verification")return je("next",{state:Ee(y.state),...await wt(h.paths,y.state)});let S=await Il({paths:h.paths,name:r}),N=S.state;if(d!==void 0&&N.phase!=="shape")throw new V("--coordination-mode is only valid when confirming Shape");if(!i)throw new V("--summary is required");let E,C=null;if(a)if(N.phase==="shape")E=await qh({paths:h.paths,name:r,...d===void 0?{}:{coordinationMode:d},expectedContinuation:m});else if(N.phase==="verify"&&N.status==="await-user"&&N.loop.next_action==="confirm-verifier-unavailable")E=await em({paths:h.paths,name:r,summary:i,expectedContinuation:m});else throw new V("--confirmed is only valid in Shape or for a user-accepted degraded verification fallback");else if(o){if(!m&&(N.phase!=="verify"||N.status!=="await-user"||N.loop.next_action!=="confirm-skill-coordinated-pass"))throw new V("--accept-result is only valid for a pending Verify pass decision");E=await Zh({paths:h.paths,name:r,expectedContinuation:m})}else if(s){if(N.phase!=="verify")throw new V("--revise-implementation is only valid from Verify");E=await ko({paths:h.paths,name:r,reason:i,expectedContinuation:m})}else if(c){if(!m&&N.phase!=="verify"&&N.phase!=="archive")throw new V("--revise-requirements is only valid from Verify or Archive");E=await So({paths:h.paths,name:r,reason:i,allowedPhases:["verify","archive"],expectedContinuation:m})}else if(l)E=await rm({paths:h.paths,name:r,expectedContinuation:m});else if(f)E=await tm({paths:h.paths,name:r,reason:i,expectedContinuation:m});else{if(S.reason!=="available")return je("next",{state:Ee(N),recovery:Km(S),...await wt(h.paths,N)});if(N.phase==="build"){let T=await No({paths:h.paths,state:N});if(T.drifted)E=await So({paths:h.paths,name:r,reason:T.reason??"Native confirmed requirements changed"});else{let F=await nt({paths:h.paths,state:N});if(F){let Z=F,j=[],yt=await U(h.paths,r);if(yt&&!F.allDone){let Ft=await ih({paths:h.paths,parent:r,maxParallel:v});j=Ft.tasks,(j.length>0||Ft.state.stateVersion!==yt.stateVersion)&&(Z=await nt({paths:h.paths,state:N})??Z)}if(Z.allDone&&!(N.loop.stage==="repairing"&&N.verification_result==="fail"))C=await bo({paths:h.paths,name:r,trigger:"recovery"}),E=C.state;else return je("next",{state:Ee(N),childSummary:Z.children.reduce((Ft,qr)=>({...Ft,[qr.status]:(Ft[qr.status]??0)+1}),{total:Z.children.length}),readyChildren:Z.readyChildren,...j.length>0?{supervisorTasks:j}:{},continuation:X(N,Z)})}}}if(E)return je("next",{state:Ee(E),...C?{parentAdvance:C.parentAdvance}:{},...await wt(h.paths,E)});let b=N.phase==="shape"?await nt({paths:h.paths,state:N}):null;return{command:"next",exitCode:65,data:{state:Ee(N),continuation:X(N,b)},error:{code:"invalid-data",message:"This Native step requires the skill-coordinated --runner-input action returned by continuation; public JSON cannot supply identity, provider, execution ref, or candidate binding"}}}return je("next",{state:Ee(E),...d===void 0?{}:{coordinationMode:d},...await wt(h.paths,E)})}async function Xm(e,t,r=process.argv.slice(2)){let i=r.indexOf("--"),n=i<0?[...r]:r.slice(0,i),a=i<0?[]:r.slice(i),o=n.includes("--json"),s=n.includes("--verbose"),c,l;try{st(n,"--json"),st(n,"--verbose"),c=gt(n,"--project-root");let u=[...n,...a],d=await Wm(c);l=await t(u,d)}catch(u){l=Gm(e,u)}let f=Um(l,o,s);return f.stdout&&process.stdout.write(f.stdout),f.stderr&&process.stderr.write(f.stderr+(f.stderr.endsWith(`
253
259
  `)?"":`
254
- `)),l.exitCode}process.exitCode=await xm("next",Em);
260
+ `)),f.exitCode}process.exitCode=await Xm("next",Ym);