@rpamis/comet 0.4.0-rc.2 → 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 (353) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +1 -1
  3. package/assets/manifest.json +1 -1
  4. package/assets/skills/comet/scripts/comet-archive.mjs +55 -55
  5. package/assets/skills/comet/scripts/comet-entry-runtime.mjs +1 -1
  6. package/assets/skills/comet/scripts/comet-guard.mjs +79 -79
  7. package/assets/skills/comet/scripts/comet-handoff.mjs +64 -64
  8. package/assets/skills/comet/scripts/comet-hook-guard.mjs +51 -51
  9. package/assets/skills/comet/scripts/comet-hook-router.mjs +123 -123
  10. package/assets/skills/comet/scripts/comet-resume-probe.mjs +48 -48
  11. package/assets/skills/comet/scripts/comet-runtime.mjs +128 -128
  12. package/assets/skills/comet/scripts/comet-state.mjs +60 -60
  13. package/assets/skills/comet/scripts/comet-yaml-validate.mjs +15 -15
  14. package/assets/skills/comet-native/SKILL.md +2 -2
  15. package/assets/skills/comet-native/reference/commands.md +3 -2
  16. package/assets/skills/comet-native/scripts/comet-native-archive.mjs +120 -120
  17. package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +126 -126
  18. package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +62 -62
  19. package/assets/skills/comet-native/scripts/comet-native-init.mjs +57 -57
  20. package/assets/skills/comet-native/scripts/comet-native-new.mjs +87 -87
  21. package/assets/skills/comet-native/scripts/comet-native-next.mjs +129 -129
  22. package/assets/skills/comet-native/scripts/comet-native-root.mjs +67 -67
  23. package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +157 -157
  24. package/assets/skills/comet-native/scripts/comet-native-select.mjs +98 -98
  25. package/assets/skills/comet-native/scripts/comet-native-show.mjs +88 -88
  26. package/assets/skills/comet-native/scripts/comet-native-spec.mjs +94 -94
  27. package/assets/skills/comet-native/scripts/comet-native-status.mjs +91 -91
  28. package/assets/skills-zh/comet-native/SKILL.md +2 -2
  29. package/assets/skills-zh/comet-native/reference/commands.md +3 -2
  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/update.d.ts.map +1 -1
  43. package/dist/app/commands/update.js +12 -5
  44. package/dist/app/commands/update.js.map +1 -1
  45. package/dist/domains/agent-learning/policy-compiler.d.ts.map +1 -1
  46. package/dist/domains/agent-learning/policy-compiler.js.map +1 -1
  47. package/dist/domains/agent-learning/types.d.ts.map +1 -1
  48. package/dist/domains/agent-learning/types.js.map +1 -1
  49. package/dist/domains/bundle/authoring.d.ts.map +1 -1
  50. package/dist/domains/bundle/authoring.js.map +1 -1
  51. package/dist/domains/bundle/next-action.d.ts.map +1 -1
  52. package/dist/domains/bundle/next-action.js.map +1 -1
  53. package/dist/domains/bundle/readiness-user-summary.d.ts.map +1 -1
  54. package/dist/domains/bundle/readiness-user-summary.js.map +1 -1
  55. package/dist/domains/bundle/types.d.ts.map +1 -1
  56. package/dist/domains/comet-classic/classic-layout-initialization.d.ts.map +1 -1
  57. package/dist/domains/comet-classic/classic-layout-initialization.js.map +1 -1
  58. package/dist/domains/comet-entry/current-selection.d.ts.map +1 -1
  59. package/dist/domains/comet-entry/current-selection.js.map +1 -1
  60. package/dist/domains/comet-entry/init-workflow.d.ts.map +1 -1
  61. package/dist/domains/comet-entry/init-workflow.js.map +1 -1
  62. package/dist/domains/comet-entry/types.d.ts.map +1 -1
  63. package/dist/domains/comet-memory/personal-memory.d.ts.map +1 -1
  64. package/dist/domains/comet-memory/personal-memory.js.map +1 -1
  65. package/dist/domains/comet-memory/types.d.ts.map +1 -1
  66. package/dist/domains/comet-memory/types.js.map +1 -1
  67. package/dist/domains/comet-native/native-atomic-file.d.ts +1 -0
  68. package/dist/domains/comet-native/native-atomic-file.d.ts.map +1 -1
  69. package/dist/domains/comet-native/native-atomic-file.js +19 -0
  70. package/dist/domains/comet-native/native-atomic-file.js.map +1 -1
  71. package/dist/domains/comet-native/native-children.d.ts +1 -0
  72. package/dist/domains/comet-native/native-children.d.ts.map +1 -1
  73. package/dist/domains/comet-native/native-children.js +15 -4
  74. package/dist/domains/comet-native/native-children.js.map +1 -1
  75. package/dist/domains/comet-native/native-cli-help.js +1 -1
  76. package/dist/domains/comet-native/native-cli-help.js.map +1 -1
  77. package/dist/domains/comet-native/native-cli-shared.js.map +1 -1
  78. package/dist/domains/comet-native/native-evidence-storage.d.ts.map +1 -1
  79. package/dist/domains/comet-native/native-evidence-storage.js.map +1 -1
  80. package/dist/domains/comet-native/native-lock.d.ts.map +1 -1
  81. package/dist/domains/comet-native/native-lock.js +10 -1
  82. package/dist/domains/comet-native/native-lock.js.map +1 -1
  83. package/dist/domains/comet-native/native-loop-runtime.d.ts.map +1 -1
  84. package/dist/domains/comet-native/native-loop-runtime.js +21 -3
  85. package/dist/domains/comet-native/native-loop-runtime.js.map +1 -1
  86. package/dist/domains/comet-native/native-next-command.d.ts.map +1 -1
  87. package/dist/domains/comet-native/native-next-command.js +35 -2
  88. package/dist/domains/comet-native/native-next-command.js.map +1 -1
  89. package/dist/domains/comet-native/native-output-language.d.ts.map +1 -1
  90. package/dist/domains/comet-native/native-output-language.js.map +1 -1
  91. package/dist/domains/comet-native/native-portable-archive.d.ts.map +1 -1
  92. package/dist/domains/comet-native/native-portable-archive.js +17 -1
  93. package/dist/domains/comet-native/native-portable-archive.js.map +1 -1
  94. package/dist/domains/comet-native/native-portable-continuation.d.ts.map +1 -1
  95. package/dist/domains/comet-native/native-portable-continuation.js +28 -29
  96. package/dist/domains/comet-native/native-portable-continuation.js.map +1 -1
  97. package/dist/domains/comet-native/native-portable-migration.d.ts.map +1 -1
  98. package/dist/domains/comet-native/native-portable-migration.js.map +1 -1
  99. package/dist/domains/comet-native/native-portable-recovery.d.ts +1 -0
  100. package/dist/domains/comet-native/native-portable-recovery.d.ts.map +1 -1
  101. package/dist/domains/comet-native/native-portable-recovery.js +2 -2
  102. package/dist/domains/comet-native/native-portable-recovery.js.map +1 -1
  103. package/dist/domains/comet-native/native-portable-runtime.d.ts +21 -0
  104. package/dist/domains/comet-native/native-portable-runtime.d.ts.map +1 -1
  105. package/dist/domains/comet-native/native-portable-runtime.js +113 -3
  106. package/dist/domains/comet-native/native-portable-runtime.js.map +1 -1
  107. package/dist/domains/comet-native/native-portable-types.d.ts.map +1 -1
  108. package/dist/domains/comet-native/native-portable-types.js.map +1 -1
  109. package/dist/domains/comet-native/native-runner-input.d.ts.map +1 -1
  110. package/dist/domains/comet-native/native-runner-input.js +14 -27
  111. package/dist/domains/comet-native/native-runner-input.js.map +1 -1
  112. package/dist/domains/comet-native/native-schema-migration.d.ts.map +1 -1
  113. package/dist/domains/comet-native/native-schema-migration.js.map +1 -1
  114. package/dist/domains/comet-native/native-supervisor.d.ts +11 -1
  115. package/dist/domains/comet-native/native-supervisor.d.ts.map +1 -1
  116. package/dist/domains/comet-native/native-supervisor.js +61 -0
  117. package/dist/domains/comet-native/native-supervisor.js.map +1 -1
  118. package/dist/domains/comet-native/native-types.d.ts.map +1 -1
  119. package/dist/domains/comet-native/native-verification-receipt.d.ts.map +1 -1
  120. package/dist/domains/comet-native/native-verification-receipt.js.map +1 -1
  121. package/dist/domains/comet-native/native-workspace.d.ts.map +1 -1
  122. package/dist/domains/comet-native/native-workspace.js.map +1 -1
  123. package/dist/domains/comet-plugin/integration.d.ts +2 -0
  124. package/dist/domains/comet-plugin/integration.d.ts.map +1 -1
  125. package/dist/domains/comet-plugin/integration.js +10 -6
  126. package/dist/domains/comet-plugin/integration.js.map +1 -1
  127. package/dist/domains/dashboard/collector.js +1 -1
  128. package/dist/domains/dashboard/default-plugin-host.d.ts +3 -0
  129. package/dist/domains/dashboard/default-plugin-host.d.ts.map +1 -1
  130. package/dist/domains/dashboard/default-plugin-host.js +38 -4
  131. package/dist/domains/dashboard/default-plugin-host.js.map +1 -1
  132. package/dist/domains/dashboard/native-adapter.d.ts.map +1 -1
  133. package/dist/domains/dashboard/native-adapter.js.map +1 -1
  134. package/dist/domains/dashboard/web/assets/abnfDiagram-VCTEODGH-UcCx24DV.js +1 -0
  135. package/dist/domains/dashboard/web/assets/arc-n8qsRq7W.js +1 -0
  136. package/dist/domains/dashboard/web/assets/architecture-7GRP2DOG-B5p4GzJf.js +1 -0
  137. package/dist/domains/dashboard/web/assets/architectureDiagram-5GKGNRK7-D4pJ8CU0.js +36 -0
  138. package/dist/domains/dashboard/web/assets/array-BifhSqXX.js +1 -0
  139. package/dist/domains/dashboard/web/assets/blockDiagram-I7D4REHJ-C7n-qrSQ.js +129 -0
  140. package/dist/domains/dashboard/web/assets/browser-CgwPGwaV.js +107 -0
  141. package/dist/domains/dashboard/web/assets/c4Diagram-7LVT6UL2-cMVrWYOm.js +38 -0
  142. package/dist/domains/dashboard/web/assets/channel-BZeSeXVb.js +1 -0
  143. package/dist/domains/dashboard/web/assets/chunk-2Q5K7J3B-C1jixKkw.js +1 -0
  144. package/dist/domains/dashboard/web/assets/chunk-4HAMMTFA-CE5QrCQd.js +62 -0
  145. package/dist/domains/dashboard/web/assets/{chunk-5VM5RSS4-CopXcnFA.js → chunk-5VM5RSS4-ZNzvKenW.js} +2 -2
  146. package/dist/domains/dashboard/web/assets/chunk-75Z2AOVW-BtZqN-pM.js +2 -0
  147. package/dist/domains/dashboard/web/assets/chunk-DU6HZSFF-CChv0huc.js +125 -0
  148. package/dist/domains/dashboard/web/assets/chunk-F27PBJKO-CDT1ttJ8.js +1 -0
  149. package/dist/domains/dashboard/web/assets/chunk-FOHPRMQF-DHwB1DNv.js +161 -0
  150. package/dist/domains/dashboard/web/assets/chunk-GMAD6QVW-y5m6LMR7.js +72 -0
  151. package/dist/domains/dashboard/web/assets/chunk-GVQU2GXP-DkhKkaHd.js +1 -0
  152. package/dist/domains/dashboard/web/assets/chunk-IMKFNOWR-BaDSh7Jp.js +231 -0
  153. package/dist/domains/dashboard/web/assets/chunk-JWPE2WC7-DVXcaiue.js +1 -0
  154. package/dist/domains/dashboard/web/assets/chunk-L3NEJ4N5-B4ztH2fV.js +1 -0
  155. package/dist/domains/dashboard/web/assets/chunk-OSK3NFVY-BhX6NVzA.js +10 -0
  156. package/dist/domains/dashboard/web/assets/chunk-P2QGCYS3-BCNdGJkX.js +1 -0
  157. package/dist/domains/dashboard/web/assets/chunk-POPQ4Y6H-DwYVuiXw.js +1 -0
  158. package/dist/domains/dashboard/web/assets/chunk-PWAF6VOD-Cyg0IO0R.js +1 -0
  159. package/dist/domains/dashboard/web/assets/chunk-SHT3W25Y-BZ6skx8I.js +168 -0
  160. package/dist/domains/dashboard/web/assets/chunk-SVP7TREG-CLIGmSO0.js +88 -0
  161. package/dist/domains/dashboard/web/assets/chunk-TICWLB2K-BAQBbsn9.js +206 -0
  162. package/dist/domains/dashboard/web/assets/chunk-XXDRQBXY-D07UbEpV.js +1 -0
  163. package/dist/domains/dashboard/web/assets/chunk-Y2CYZVJY-DsF7k-Jl.js +1 -0
  164. package/dist/domains/dashboard/web/assets/classDiagram-ZZMXUADV-2fcinal6.js +1 -0
  165. package/dist/domains/dashboard/web/assets/classDiagram-v2-VYDZK3BY-2fcinal6.js +1 -0
  166. package/dist/domains/dashboard/web/assets/cose-bilkent-JH36ORCC-wIi0mUih.js +1 -0
  167. package/dist/domains/dashboard/web/assets/cynefin-OW5HDTMX-DBdxyuTN.js +1 -0
  168. package/dist/domains/dashboard/web/assets/cynefinDiagram-5FMLGOSQ-DzO3jXxV.js +62 -0
  169. package/dist/domains/dashboard/web/assets/cytoscape.esm-CGd-uY3x.js +321 -0
  170. package/dist/domains/dashboard/web/assets/dagre-GXQ25YYZ-CE7H_hZS.js +4 -0
  171. package/dist/domains/dashboard/web/assets/dagre-PrKaheQc.js +1 -0
  172. package/dist/domains/dashboard/web/assets/defaultLocale-BFoDCU3G.js +1 -0
  173. package/dist/domains/dashboard/web/assets/demo-DrJ2uuUL.js +456 -0
  174. package/dist/domains/dashboard/web/assets/diagram-S7CK7UJ4-jUGQk5n-.js +30 -0
  175. package/dist/domains/dashboard/web/assets/diagram-UQ7AKVKN-DaH_zW8T.js +41 -0
  176. package/dist/domains/dashboard/web/assets/diagram-VSXAHHWV-DmG80db0.js +3 -0
  177. package/dist/domains/dashboard/web/assets/diagram-VX7I27RA-ltQ6niKn.js +24 -0
  178. package/dist/domains/dashboard/web/assets/diagram-Z3DM3KII-x92ex4lK.js +24 -0
  179. package/dist/domains/dashboard/web/assets/dist-Cf0h0n6i.js +1 -0
  180. package/dist/domains/dashboard/web/assets/ebnfDiagram-PWID7BFC-CI2u976k.js +1 -0
  181. package/dist/domains/dashboard/web/assets/erDiagram-RLTQ6QDP-DKs90SRd.js +99 -0
  182. package/dist/domains/dashboard/web/assets/es-D7xGlyQk.js +10 -0
  183. package/dist/domains/dashboard/web/assets/eventmodeling-NTZA5JFV-uARcGZPD.js +1 -0
  184. package/dist/domains/dashboard/web/assets/flowDiagram-HODETNUW-DXL1E4Bl.js +1 -0
  185. package/dist/domains/dashboard/web/assets/ganttDiagram-EL5Y4UJY-D3z6G60S.js +292 -0
  186. package/dist/domains/dashboard/web/assets/gitGraph-4MIJSDKK-vT1UnORT.js +1 -0
  187. package/dist/domains/dashboard/web/assets/gitGraphDiagram-WWUBYQGX-BJmJ96jv.js +106 -0
  188. package/dist/domains/dashboard/web/assets/graphlib-DS17s2tU.js +1 -0
  189. package/dist/domains/dashboard/web/assets/index-BG3MF8re.js +261 -0
  190. package/dist/domains/dashboard/web/assets/index-C2Hlo7VZ.css +1 -0
  191. package/dist/domains/dashboard/web/assets/info-A6RAGUB7-DFeLqqen.js +1 -0
  192. package/dist/domains/dashboard/web/assets/infoDiagram-27XIBGKW-DxuY43XD.js +2 -0
  193. package/dist/domains/dashboard/web/assets/init-C-OQMol4.js +1 -0
  194. package/dist/domains/dashboard/web/assets/ishikawaDiagram-5VMMS53U-DxillfWQ.js +70 -0
  195. package/dist/domains/dashboard/web/assets/journeyDiagram-3NMN7TZE-BPngQ3ag.js +139 -0
  196. package/dist/domains/dashboard/web/assets/kanban-definition-UXKFOSKX-DHMLEGD4.js +89 -0
  197. package/dist/domains/dashboard/web/assets/katex-CXMH3UgJ.js +257 -0
  198. package/dist/domains/dashboard/web/assets/line-D31peBjo.js +1 -0
  199. package/dist/domains/dashboard/web/assets/linear-B7X50T2m.js +1 -0
  200. package/dist/domains/dashboard/web/assets/marked.esm-BtJme7Pf.js +65 -0
  201. package/dist/domains/dashboard/web/assets/mermaid-parser.core-CX3Pzygh.js +7 -0
  202. package/dist/domains/dashboard/web/assets/mermaid.core-DlMjBFb6.js +44 -0
  203. package/dist/domains/dashboard/web/assets/mindmap-definition-YA3MSWOX-BKuSGF75.js +96 -0
  204. package/dist/domains/dashboard/web/assets/ordinal-BDEzSJ7C.js +1 -0
  205. package/dist/domains/dashboard/web/assets/packet-AYTQ26CC-B1T8Bds9.js +1 -0
  206. package/dist/domains/dashboard/web/assets/path-fybaL0A-.js +1 -0
  207. package/dist/domains/dashboard/web/assets/pegDiagram-XKGWAZYB-BYgTNxLw.js +1 -0
  208. package/dist/domains/dashboard/web/assets/pie-WAS4IAKB-fqAjmoQw.js +1 -0
  209. package/dist/domains/dashboard/web/assets/pieDiagram-E7YTZNPT-BAO0Ufky.js +39 -0
  210. package/dist/domains/dashboard/web/assets/purify.es-ChwZkWde.js +3 -0
  211. package/dist/domains/dashboard/web/assets/quadrantDiagram-AXDQQJYC-SA_1-7DT.js +7 -0
  212. package/dist/domains/dashboard/web/assets/radar-RG4KPBEZ-Bl_UfUle.js +1 -0
  213. package/dist/domains/dashboard/web/assets/railroad-74A4TZTK-yj6dkiSy.js +1 -0
  214. package/dist/domains/dashboard/web/assets/railroad-abnf-HS5TGJTU-CvouMciM.js +1 -0
  215. package/dist/domains/dashboard/web/assets/railroad-ebnf-LZEXJU2U-CkYQEX72.js +1 -0
  216. package/dist/domains/dashboard/web/assets/railroad-peg-WCYAUIDC-B0uYr48F.js +1 -0
  217. package/dist/domains/dashboard/web/assets/railroadDiagram-O6MQD6OU-DqV18Y46.js +1 -0
  218. package/dist/domains/dashboard/web/assets/requirementDiagram-BXWQKSXE-Ca2K5LuT.js +84 -0
  219. package/dist/domains/dashboard/web/assets/rough.esm-Dy-Kn_BL.js +1 -0
  220. package/dist/domains/dashboard/web/assets/sankeyDiagram-P5KCCOFB-D9MKl-Nr.js +40 -0
  221. package/dist/domains/dashboard/web/assets/sequenceDiagram-WJ2MYXX4-CXfvIzRx.js +162 -0
  222. package/dist/domains/dashboard/web/assets/sizeCapture-INFHLROL-B0uUizjq.js +1 -0
  223. package/dist/domains/dashboard/web/assets/src-CquUPIQx.js +1 -0
  224. package/dist/domains/dashboard/web/assets/stateDiagram-D77RDMKH-B7iaZHW7.js +1 -0
  225. package/dist/domains/dashboard/web/assets/stateDiagram-v2-MP3YSRHH-B6KoHQVe.js +1 -0
  226. package/dist/domains/dashboard/web/assets/swimlanes-42K2YHIH-OK-62yZl.js +1 -0
  227. package/dist/domains/dashboard/web/assets/swimlanesDiagram-VR7AAH4N-CjdOls9K.js +8 -0
  228. package/dist/domains/dashboard/web/assets/timeline-definition-24CTP7MA-D0l01B1h.js +120 -0
  229. package/dist/domains/dashboard/web/assets/treeView-Q6P3EWNA-Bg5u_o3A.js +1 -0
  230. package/dist/domains/dashboard/web/assets/treemap-WGGIJYW6-x89ccozk.js +1 -0
  231. package/dist/domains/dashboard/web/assets/vennDiagram-4TSXK5OY-DV19Cqhv.js +34 -0
  232. package/dist/domains/dashboard/web/assets/wardley-WFR3VGLG-BWoeoVk5.js +1 -0
  233. package/dist/domains/dashboard/web/assets/wardleyDiagram-VM6X3IG4-D4fCpoIP.js +78 -0
  234. package/dist/domains/dashboard/web/assets/xychartDiagram-S5SC5T6Z-DALnOMLb.js +7 -0
  235. package/dist/domains/dashboard/web/index.html +16 -16
  236. package/dist/domains/factory/artifacts.d.ts.map +1 -1
  237. package/dist/domains/factory/artifacts.js.map +1 -1
  238. package/dist/domains/factory/types.d.ts.map +1 -1
  239. package/dist/domains/integrations/codegraph.d.ts.map +1 -1
  240. package/dist/domains/integrations/codegraph.js.map +1 -1
  241. package/dist/domains/project-knowledge/local-store.d.ts +21 -0
  242. package/dist/domains/project-knowledge/local-store.d.ts.map +1 -1
  243. package/dist/domains/project-knowledge/local-store.js +97 -0
  244. package/dist/domains/project-knowledge/local-store.js.map +1 -1
  245. package/dist/domains/project-knowledge/types.d.ts.map +1 -1
  246. package/dist/domains/skill/platform-inspect.d.ts +1 -1
  247. package/dist/domains/skill/platform-inspect.d.ts.map +1 -1
  248. package/dist/domains/skill/platform-inspect.js +50 -10
  249. package/dist/domains/skill/platform-inspect.js.map +1 -1
  250. package/dist/domains/skill/platform-install.d.ts +10 -5
  251. package/dist/domains/skill/platform-install.d.ts.map +1 -1
  252. package/dist/domains/skill/platform-install.js +107 -17
  253. package/dist/domains/skill/platform-install.js.map +1 -1
  254. package/dist/domains/skill/uninstall.d.ts.map +1 -1
  255. package/dist/domains/skill/uninstall.js +38 -61
  256. package/dist/domains/skill/uninstall.js.map +1 -1
  257. package/dist/domains/workflow-contract/contained-atomic-write.d.ts +1 -0
  258. package/dist/domains/workflow-contract/contained-atomic-write.d.ts.map +1 -1
  259. package/dist/domains/workflow-contract/contained-atomic-write.js +19 -0
  260. package/dist/domains/workflow-contract/contained-atomic-write.js.map +1 -1
  261. package/dist/domains/workflow-contract/global-config.d.ts +8 -0
  262. package/dist/domains/workflow-contract/global-config.d.ts.map +1 -1
  263. package/dist/domains/workflow-contract/global-config.js +25 -0
  264. package/dist/domains/workflow-contract/global-config.js.map +1 -1
  265. package/dist/domains/workflow-contract/index.d.ts +1 -1
  266. package/dist/domains/workflow-contract/index.d.ts.map +1 -1
  267. package/dist/domains/workflow-contract/index.js +1 -1
  268. package/dist/domains/workflow-contract/index.js.map +1 -1
  269. package/dist/domains/workflow-contract/project-config.d.ts +1 -1
  270. package/dist/domains/workflow-contract/project-config.d.ts.map +1 -1
  271. package/dist/domains/workflow-contract/project-config.js +1 -0
  272. package/dist/domains/workflow-contract/project-config.js.map +1 -1
  273. package/dist/domains/workflow-contract/types.d.ts.map +1 -1
  274. package/dist/platform/install/platforms.d.ts +4 -0
  275. package/dist/platform/install/platforms.d.ts.map +1 -1
  276. package/dist/platform/install/platforms.js +15 -3
  277. package/dist/platform/install/platforms.js.map +1 -1
  278. package/dist/platform/paths/project-knowledge-storage.d.ts +1 -1
  279. package/dist/platform/paths/project-knowledge-storage.d.ts.map +1 -1
  280. package/dist/platform/paths/project-knowledge-storage.js +9 -4
  281. package/dist/platform/paths/project-knowledge-storage.js.map +1 -1
  282. package/eval/local/tasks/comet-classic-layout-lifecycle/environment/current-comet-package.json +13 -13
  283. package/eval/local/tasks/comet-native-wave-f-dashboard-readonly/environment/current-comet-package.json +13 -13
  284. package/package.json +24 -24
  285. package/dist/domains/dashboard/web/assets/abnfDiagram-N423BO3Z-BkUJc7LK.js +0 -1
  286. package/dist/domains/dashboard/web/assets/arc-DY4Y9tSO.js +0 -1
  287. package/dist/domains/dashboard/web/assets/architectureDiagram-T3A2C74G-7wC9YZS-.js +0 -36
  288. package/dist/domains/dashboard/web/assets/blockDiagram-VBNYF7ZC-Biqe-SaL.js +0 -132
  289. package/dist/domains/dashboard/web/assets/c4Diagram-5PPSVZJV-CccUFD1S.js +0 -10
  290. package/dist/domains/dashboard/web/assets/channel-DnRvSkOm.js +0 -1
  291. package/dist/domains/dashboard/web/assets/chunk-2GRJ4B5K-BUL4dDxo.js +0 -1
  292. package/dist/domains/dashboard/web/assets/chunk-2Q5K7J3B-BnKtDH9O.js +0 -1
  293. package/dist/domains/dashboard/web/assets/chunk-5RXB4S5H-C9pHQ1n3.js +0 -231
  294. package/dist/domains/dashboard/web/assets/chunk-6Q2QTUOP-CxrbngCi.js +0 -88
  295. package/dist/domains/dashboard/web/assets/chunk-GF5L2VYU-01mzgCUh.js +0 -206
  296. package/dist/domains/dashboard/web/assets/chunk-JWPE2WC7-wTiZVDvw.js +0 -1
  297. package/dist/domains/dashboard/web/assets/chunk-KBJHAD2P-Bxdv5bl-.js +0 -1
  298. package/dist/domains/dashboard/web/assets/chunk-RYQCIY6F-B5vF9l9A.js +0 -1
  299. package/dist/domains/dashboard/web/assets/chunk-XXDRQBXY-Dra3NnDp.js +0 -1
  300. package/dist/domains/dashboard/web/assets/classDiagram-JCYQIIEL-D3E-rgaQ.js +0 -1
  301. package/dist/domains/dashboard/web/assets/classDiagram-v2-OCEON4UE-D3E-rgaQ.js +0 -1
  302. package/dist/domains/dashboard/web/assets/cose-bilkent-JH36ORCC-DC96ge-n.js +0 -1
  303. package/dist/domains/dashboard/web/assets/cynefin-VYW2F7L2-Tt_NiopT.js +0 -166
  304. package/dist/domains/dashboard/web/assets/cynefinDiagram-MW4NZA55-BQ5__1hv.js +0 -62
  305. package/dist/domains/dashboard/web/assets/cytoscape.esm-D3_iZ_3b.js +0 -321
  306. package/dist/domains/dashboard/web/assets/dagre-VZM6K2ZE-Cr2zq3ro.js +0 -4
  307. package/dist/domains/dashboard/web/assets/defaultLocale-DX6XiGOO.js +0 -1
  308. package/dist/domains/dashboard/web/assets/demo-lxXhgJ9-.js +0 -456
  309. package/dist/domains/dashboard/web/assets/diagram-7IWD3JNH-BRpYDwPl.js +0 -30
  310. package/dist/domains/dashboard/web/assets/diagram-B4RE2ZJO-D7u-VBxW.js +0 -3
  311. package/dist/domains/dashboard/web/assets/diagram-LBJQPF4R-CHYuv2JD.js +0 -24
  312. package/dist/domains/dashboard/web/assets/diagram-Q27KOJAE-CV3ZE8Q3.js +0 -24
  313. package/dist/domains/dashboard/web/assets/diagram-UB23O5K3-co_OsTiQ.js +0 -41
  314. package/dist/domains/dashboard/web/assets/ebnfDiagram-BXEA7PRR-CETcWswS.js +0 -1
  315. package/dist/domains/dashboard/web/assets/erDiagram-JOGREHBK-edkItb7Z.js +0 -85
  316. package/dist/domains/dashboard/web/assets/flowDiagram-UKHOOZJN-D_oFJtSf.js +0 -156
  317. package/dist/domains/dashboard/web/assets/ganttDiagram-PKOTCBZU-CFjLVoA1.js +0 -292
  318. package/dist/domains/dashboard/web/assets/gitGraphDiagram-DS77QQ5N-BfD0tiKH.js +0 -106
  319. package/dist/domains/dashboard/web/assets/graph-DOmOIIwC.js +0 -1
  320. package/dist/domains/dashboard/web/assets/index-BzyqCfMb.css +0 -1
  321. package/dist/domains/dashboard/web/assets/index-CCKHH_A9.js +0 -10
  322. package/dist/domains/dashboard/web/assets/index-D8dxsTJY.js +0 -271
  323. package/dist/domains/dashboard/web/assets/index-DlSYK56b.js +0 -139
  324. package/dist/domains/dashboard/web/assets/infoDiagram-6WML65LV-Cx6xa9DS.js +0 -2
  325. package/dist/domains/dashboard/web/assets/init-Gi6I4Gst.js +0 -1
  326. package/dist/domains/dashboard/web/assets/ishikawaDiagram-WSZJBQD7-BjNLyyv_.js +0 -70
  327. package/dist/domains/dashboard/web/assets/journeyDiagram-NVQOT4AX-D2n9vrhx.js +0 -139
  328. package/dist/domains/dashboard/web/assets/kanban-definition-27J2QSJJ-kJL7v018.js +0 -89
  329. package/dist/domains/dashboard/web/assets/katex-HP8lGamR.js +0 -257
  330. package/dist/domains/dashboard/web/assets/layout-D-LzfAck.js +0 -1
  331. package/dist/domains/dashboard/web/assets/linear-CeHtd5-l.js +0 -1
  332. package/dist/domains/dashboard/web/assets/map-DxJ2ADlA.js +0 -1
  333. package/dist/domains/dashboard/web/assets/marked.esm-DECB3bxB.js +0 -64
  334. package/dist/domains/dashboard/web/assets/mermaid.core-B0EPSHs2.js +0 -306
  335. package/dist/domains/dashboard/web/assets/mindmap-definition-FAOFIHXS-bQQWINF4.js +0 -96
  336. package/dist/domains/dashboard/web/assets/ordinal-Cboi1Yqb.js +0 -1
  337. package/dist/domains/dashboard/web/assets/pegDiagram-VL7TDLO6-LxLY1W7W.js +0 -1
  338. package/dist/domains/dashboard/web/assets/pieDiagram-7S7Q4E2Y-BMDQqvuT.js +0 -39
  339. package/dist/domains/dashboard/web/assets/purify.es-Cz4mVeUR.js +0 -3
  340. package/dist/domains/dashboard/web/assets/quadrantDiagram-CIZ2JOQS-XWYjcuZN.js +0 -7
  341. package/dist/domains/dashboard/web/assets/railroadDiagram-AXF67PYL-p-OlQTa7.js +0 -1
  342. package/dist/domains/dashboard/web/assets/requirementDiagram-LRYGKXZP-BL4N8Vsl.js +0 -84
  343. package/dist/domains/dashboard/web/assets/sankeyDiagram-W5VNT64P-Btu-o6LN.js +0 -40
  344. package/dist/domains/dashboard/web/assets/sequenceDiagram-SI44F4Z6-9HpdQQ47.js +0 -162
  345. package/dist/domains/dashboard/web/assets/sizeCapture-X5ZJPWSS-5AnBiBHD.js +0 -1
  346. package/dist/domains/dashboard/web/assets/stateDiagram-OKZ733FA-Dv8IDsai.js +0 -1
  347. package/dist/domains/dashboard/web/assets/stateDiagram-v2-UEYNNEHI-DxOMyFOm.js +0 -1
  348. package/dist/domains/dashboard/web/assets/swimlanes-SLNWSIFB-BfJcN7dK.js +0 -2
  349. package/dist/domains/dashboard/web/assets/swimlanesDiagram-ULZ7WXOC-BnHRSbDk.js +0 -8
  350. package/dist/domains/dashboard/web/assets/timeline-definition-Z64GVDOM-DEOuEHi5.js +0 -120
  351. package/dist/domains/dashboard/web/assets/vennDiagram-T6HMQDX7-BqsGpwgo.js +0 -34
  352. package/dist/domains/dashboard/web/assets/wardleyDiagram-T6FBY63Y-CXlOp9so.js +0 -78
  353. package/dist/domains/dashboard/web/assets/xychartDiagram-ELKLHX3M-DyqqtC9X.js +0 -7
@@ -1,77 +1,77 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cometCreateRequire } from 'module';
3
3
  const require = __cometCreateRequire(import.meta.url);
4
- var hP=Object.create;var Wm=Object.defineProperty;var pP=Object.getOwnPropertyDescriptor;var mP=Object.getOwnPropertyNames;var vP=Object.getPrototypeOf,gP=Object.prototype.hasOwnProperty;var Js=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,i)=>(typeof require<"u"?require:t)[i]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var C=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}};var wP=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of mP(t))!gP.call(e,n)&&n!==i&&Wm(e,n,{get:()=>t[n],enumerable:!(r=pP(t,n))||r.enumerable});return e};var Rn=(e,t,i)=>(i=e!=null?hP(vP(e)):{},wP(t||!e||!e.__esModule?Wm(i,"default",{value:e,enumerable:!0}):i,e));var G=C(je=>{"use strict";var hd=Symbol.for("yaml.alias"),ev=Symbol.for("yaml.document"),Ks=Symbol.for("yaml.map"),tv=Symbol.for("yaml.pair"),pd=Symbol.for("yaml.scalar"),Ys=Symbol.for("yaml.seq"),Ri=Symbol.for("yaml.node.type"),SP=e=>!!e&&typeof e=="object"&&e[Ri]===hd,EP=e=>!!e&&typeof e=="object"&&e[Ri]===ev,PP=e=>!!e&&typeof e=="object"&&e[Ri]===Ks,RP=e=>!!e&&typeof e=="object"&&e[Ri]===tv,iv=e=>!!e&&typeof e=="object"&&e[Ri]===pd,CP=e=>!!e&&typeof e=="object"&&e[Ri]===Ys;function rv(e){if(e&&typeof e=="object")switch(e[Ri]){case Ks:case Ys:return!0}return!1}function xP(e){if(e&&typeof e=="object")switch(e[Ri]){case hd:case Ks:case pd:case Ys:return!0}return!1}var AP=e=>(iv(e)||rv(e))&&!!e.anchor;je.ALIAS=hd;je.DOC=ev;je.MAP=Ks;je.NODE_TYPE=Ri;je.PAIR=tv;je.SCALAR=pd;je.SEQ=Ys;je.hasAnchor=AP;je.isAlias=SP;je.isCollection=rv;je.isDocument=EP;je.isMap=PP;je.isNode=xP;je.isPair=RP;je.isScalar=iv;je.isSeq=CP});var Wa=C(md=>{"use strict";var Ce=G(),ot=Symbol("break visit"),nv=Symbol("skip children"),oi=Symbol("remove node");function Xs(e,t){let i=av(t);Ce.isDocument(e)?Cn(null,e.contents,i,Object.freeze([e]))===oi&&(e.contents=null):Cn(null,e,i,Object.freeze([]))}Xs.BREAK=ot;Xs.SKIP=nv;Xs.REMOVE=oi;function Cn(e,t,i,r){let n=ov(e,t,i,r);if(Ce.isNode(n)||Ce.isPair(n))return sv(e,r,n),Cn(e,n,i,r);if(typeof n!="symbol"){if(Ce.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=Cn(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===ot)return ot;o===oi&&(t.items.splice(a,1),a-=1)}}}else if(Ce.isPair(t)){r=Object.freeze(r.concat(t));let a=Cn("key",t.key,i,r);if(a===ot)return ot;a===oi&&(t.key=null);let o=Cn("value",t.value,i,r);if(o===ot)return ot;o===oi&&(t.value=null)}}return n}async function Qs(e,t){let i=av(t);Ce.isDocument(e)?await xn(null,e.contents,i,Object.freeze([e]))===oi&&(e.contents=null):await xn(null,e,i,Object.freeze([]))}Qs.BREAK=ot;Qs.SKIP=nv;Qs.REMOVE=oi;async function xn(e,t,i,r){let n=await ov(e,t,i,r);if(Ce.isNode(n)||Ce.isPair(n))return sv(e,r,n),xn(e,n,i,r);if(typeof n!="symbol"){if(Ce.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=await xn(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===ot)return ot;o===oi&&(t.items.splice(a,1),a-=1)}}}else if(Ce.isPair(t)){r=Object.freeze(r.concat(t));let a=await xn("key",t.key,i,r);if(a===ot)return ot;a===oi&&(t.key=null);let o=await xn("value",t.value,i,r);if(o===ot)return ot;o===oi&&(t.value=null)}}return n}function av(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function ov(e,t,i,r){if(typeof i=="function")return i(e,t,r);if(Ce.isMap(t))return i.Map?.(e,t,r);if(Ce.isSeq(t))return i.Seq?.(e,t,r);if(Ce.isPair(t))return i.Pair?.(e,t,r);if(Ce.isScalar(t))return i.Scalar?.(e,t,r);if(Ce.isAlias(t))return i.Alias?.(e,t,r)}function sv(e,t,i){let r=t[t.length-1];if(Ce.isCollection(r))r.items[e]=i;else if(Ce.isPair(r))e==="key"?r.key=i:r.value=i;else if(Ce.isDocument(r))r.contents=i;else{let n=Ce.isAlias(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}md.visit=Xs;md.visitAsync=Qs});var vd=C(lv=>{"use strict";var cv=G(),_P=Wa(),TP={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},IP=e=>e.replace(/[!,[\]{}]/g,t=>TP[t]),za=class e{constructor(t,i){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,i)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,i){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let r=t.trim().split(/[ \t]+/),n=r.shift();switch(n){case"%TAG":{if(r.length!==2&&(i(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[a,o]=r;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return i(0,"%YAML directive should contain exactly one part"),!1;let[a]=r;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return i(6,`Unsupported YAML version ${a}`,o),!1}}default:return i(0,`Unknown directive ${n}`,!0),!1}}tagName(t,i){if(t==="!")return"!";if(t[0]!=="!")return i(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(i(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&i("Verbatim tags must end with a >"),o)}let[,r,n]=t.match(/^(.*!)([^!]*)$/s);n||i(`The ${t} tag has no suffix`);let a=this.tags[r];if(a)try{return a+decodeURIComponent(n)}catch(o){return i(String(o)),null}return r==="!"?t:(i(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[i,r]of Object.entries(this.tags))if(t.startsWith(r))return i+IP(t.substring(r.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let i=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),n;if(t&&r.length>0&&cv.isNode(t.contents)){let a={};_P.visit(t.contents,(o,s)=>{cv.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of r)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&i.push(`%TAG ${a} ${o}`);return i.join(`
5
- `)}};za.defaultYaml={explicit:!1,version:"1.2"};za.defaultTags={"!!":"tag:yaml.org,2002:"};lv.Directives=za});var Zs=C(Ja=>{"use strict";var uv=G(),jP=Wa();function $P(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let i=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(i)}return!0}function dv(e){let t=new Set;return jP.visit(e,{Value(i,r){r.anchor&&t.add(r.anchor)}}),t}function fv(e,t){for(let i=1;;++i){let r=`${e}${i}`;if(!t.has(r))return r}}function OP(e,t){let i=[],r=new Map,n=null;return{onAnchor:a=>{i.push(a),n??(n=dv(e));let o=fv(t,n);return n.add(o),o},setAnchors:()=>{for(let a of i){let o=r.get(a);if(typeof o=="object"&&o.anchor&&(uv.isScalar(o.node)||uv.isCollection(o.node)))o.node.anchor=o.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=a,s}}},sourceObjects:r}}Ja.anchorIsValid=$P;Ja.anchorNames=dv;Ja.createNodeAnchors=OP;Ja.findNewAnchor=fv});var gd=C(hv=>{"use strict";function Ga(e,t,i,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let n=0,a=r.length;n<a;++n){let o=r[n],s=Ga(e,r,String(n),o);s===void 0?delete r[n]:s!==o&&(r[n]=s)}else if(r instanceof Map)for(let n of Array.from(r.keys())){let a=r.get(n),o=Ga(e,r,n,a);o===void 0?r.delete(n):o!==a&&r.set(n,o)}else if(r instanceof Set)for(let n of Array.from(r)){let a=Ga(e,r,n,n);a===void 0?r.delete(n):a!==n&&(r.delete(n),r.add(a))}else for(let[n,a]of Object.entries(r)){let o=Ga(e,r,n,a);o===void 0?delete r[n]:o!==a&&(r[n]=o)}return e.call(t,i,r)}hv.applyReviver=Ga});var Gi=C(mv=>{"use strict";var HP=G();function pv(e,t,i){if(Array.isArray(e))return e.map((r,n)=>pv(r,String(n),i));if(e&&typeof e.toJSON=="function"){if(!i||!HP.hasAnchor(e))return e.toJSON(t,i);let r={aliasCount:0,count:1,res:void 0};i.anchors.set(e,r),i.onCreate=a=>{r.res=a,delete i.onCreate};let n=e.toJSON(t,i);return i.onCreate&&i.onCreate(n),n}return typeof e=="bigint"&&!i?.keep?Number(e):e}mv.toJS=pv});var ec=C(gv=>{"use strict";var DP=gd(),vv=G(),LP=Gi(),wd=class{constructor(t){Object.defineProperty(this,vv.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:i,maxAliasCount:r,onAnchor:n,reviver:a}={}){if(!vv.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},s=LP.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?DP.applyReviver(a,{"":s},"",s):s}};gv.NodeBase=wd});var Ua=C(wv=>{"use strict";var MP=Zs(),FP=Wa(),An=G(),BP=ec(),VP=Gi(),yd=class extends BP.NodeBase{constructor(t){super(An.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,i){if(i?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;i?.aliasResolveCache?r=i.aliasResolveCache:(r=[],FP.visit(t,{Node:(a,o)=>{(An.isAlias(o)||An.hasAnchor(o))&&r.push(o)}}),i&&(i.aliasResolveCache=r));let n;for(let a of r){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,i){if(!i)return{source:this.source};let{anchors:r,doc:n,maxAliasCount:a}=i,o=this.resolve(n,i);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=r.get(o);if(s||(VP.toJS(o,null,i),s=r.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=tc(n,o,r)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,i,r){let n=`*${this.source}`;if(t){if(MP.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(t.implicitKey)return`${n} `}return n}};function tc(e,t,i){if(An.isAlias(t)){let r=t.resolve(e),n=i&&r&&i.get(r);return n?n.count*n.aliasCount:0}else if(An.isCollection(t)){let r=0;for(let n of t.items){let a=tc(e,n,i);a>r&&(r=a)}return r}else if(An.isPair(t)){let r=tc(e,t.key,i),n=tc(e,t.value,i);return Math.max(r,n)}return 1}wv.Alias=yd});var ke=C(Nd=>{"use strict";var qP=G(),WP=ec(),zP=Gi(),JP=e=>!e||typeof e!="function"&&typeof e!="object",Ui=class extends WP.NodeBase{constructor(t){super(qP.SCALAR),this.value=t}toJSON(t,i){return i?.keep?this.value:zP.toJS(this.value,t,i)}toString(){return String(this.value)}};Ui.BLOCK_FOLDED="BLOCK_FOLDED";Ui.BLOCK_LITERAL="BLOCK_LITERAL";Ui.PLAIN="PLAIN";Ui.QUOTE_DOUBLE="QUOTE_DOUBLE";Ui.QUOTE_SINGLE="QUOTE_SINGLE";Nd.Scalar=Ui;Nd.isScalarValue=JP});var Ka=C(Nv=>{"use strict";var GP=Ua(),Jr=G(),yv=ke(),UP="tag:yaml.org,2002:";function KP(e,t,i){if(t){let r=i.filter(a=>a.tag===t),n=r.find(a=>!a.format)??r[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return i.find(r=>r.identify?.(e)&&!r.format)}function YP(e,t,i){if(Jr.isDocument(e)&&(e=e.contents),Jr.isNode(e))return e;if(Jr.isPair(e)){let d=i.schema[Jr.MAP].createNode?.(i.schema,null,i);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=i,c;if(r&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new GP.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=UP+t.slice(2));let l=KP(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new yv.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[Jr.MAP]:Symbol.iterator in Object(e)?o[Jr.SEQ]:o[Jr.MAP]}a&&(a(l),delete i.onTagObj);let u=l?.createNode?l.createNode(i.schema,e,i):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(i.schema,e,i):new yv.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}Nv.createNode=YP});var rc=C(ic=>{"use strict";var XP=Ka(),si=G(),QP=ec();function bd(e,t,i){let r=i;for(let n=t.length-1;n>=0;--n){let a=t[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=r,r=o}else r=new Map([[a,r]])}return XP.createNode(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var bv=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,kd=class extends QP.NodeBase{constructor(t,i){super(t),Object.defineProperty(this,"schema",{value:i,configurable:!0,enumerable:!1,writable:!0})}clone(t){let i=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(i.schema=t),i.items=i.items.map(r=>si.isNode(r)||si.isPair(r)?r.clone(t):r),this.range&&(i.range=this.range.slice()),i}addIn(t,i){if(bv(t))this.add(i);else{let[r,...n]=t,a=this.get(r,!0);if(si.isCollection(a))a.addIn(n,i);else if(a===void 0&&this.schema)this.set(r,bd(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}deleteIn(t){let[i,...r]=t;if(r.length===0)return this.delete(i);let n=this.get(i,!0);if(si.isCollection(n))return n.deleteIn(r);throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}getIn(t,i){let[r,...n]=t,a=this.get(r,!0);return n.length===0?!i&&si.isScalar(a)?a.value:a:si.isCollection(a)?a.getIn(n,i):void 0}hasAllNullValues(t){return this.items.every(i=>{if(!si.isPair(i))return!1;let r=i.value;return r==null||t&&si.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(t){let[i,...r]=t;if(r.length===0)return this.has(i);let n=this.get(i,!0);return si.isCollection(n)?n.hasIn(r):!1}setIn(t,i){let[r,...n]=t;if(n.length===0)this.set(r,i);else{let a=this.get(r,!0);if(si.isCollection(a))a.setIn(n,i);else if(a===void 0&&this.schema)this.set(r,bd(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}};ic.Collection=kd;ic.collectionFromPath=bd;ic.isEmptyPath=bv});var Ya=C(nc=>{"use strict";var ZP=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Sd(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var eR=(e,t,i)=>e.endsWith(`
6
- `)?Sd(i,t):i.includes(`
4
+ var wP=Object.create;var zm=Object.defineProperty;var yP=Object.getOwnPropertyDescriptor;var NP=Object.getOwnPropertyNames;var bP=Object.getPrototypeOf,kP=Object.prototype.hasOwnProperty;var Ks=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,i)=>(typeof require<"u"?require:t)[i]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var C=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}};var SP=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of NP(t))!kP.call(e,n)&&n!==i&&zm(e,n,{get:()=>t[n],enumerable:!(r=yP(t,n))||r.enumerable});return e};var Tn=(e,t,i)=>(i=e!=null?wP(bP(e)):{},SP(t||!e||!e.__esModule?zm(i,"default",{value:e,enumerable:!0}):i,e));var G=C($e=>{"use strict";var wd=Symbol.for("yaml.alias"),tv=Symbol.for("yaml.document"),Qs=Symbol.for("yaml.map"),iv=Symbol.for("yaml.pair"),yd=Symbol.for("yaml.scalar"),Zs=Symbol.for("yaml.seq"),Ci=Symbol.for("yaml.node.type"),xP=e=>!!e&&typeof e=="object"&&e[Ci]===wd,AP=e=>!!e&&typeof e=="object"&&e[Ci]===tv,_P=e=>!!e&&typeof e=="object"&&e[Ci]===Qs,TP=e=>!!e&&typeof e=="object"&&e[Ci]===iv,rv=e=>!!e&&typeof e=="object"&&e[Ci]===yd,IP=e=>!!e&&typeof e=="object"&&e[Ci]===Zs;function nv(e){if(e&&typeof e=="object")switch(e[Ci]){case Qs:case Zs:return!0}return!1}function jP(e){if(e&&typeof e=="object")switch(e[Ci]){case wd:case Qs:case yd:case Zs:return!0}return!1}var $P=e=>(rv(e)||nv(e))&&!!e.anchor;$e.ALIAS=wd;$e.DOC=tv;$e.MAP=Qs;$e.NODE_TYPE=Ci;$e.PAIR=iv;$e.SCALAR=yd;$e.SEQ=Zs;$e.hasAnchor=$P;$e.isAlias=xP;$e.isCollection=nv;$e.isDocument=AP;$e.isMap=_P;$e.isNode=jP;$e.isPair=TP;$e.isScalar=rv;$e.isSeq=IP});var Ka=C(Nd=>{"use strict";var xe=G(),ot=Symbol("break visit"),av=Symbol("skip children"),si=Symbol("remove node");function ec(e,t){let i=ov(t);xe.isDocument(e)?In(null,e.contents,i,Object.freeze([e]))===si&&(e.contents=null):In(null,e,i,Object.freeze([]))}ec.BREAK=ot;ec.SKIP=av;ec.REMOVE=si;function In(e,t,i,r){let n=sv(e,t,i,r);if(xe.isNode(n)||xe.isPair(n))return cv(e,r,n),In(e,n,i,r);if(typeof n!="symbol"){if(xe.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=In(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===ot)return ot;o===si&&(t.items.splice(a,1),a-=1)}}}else if(xe.isPair(t)){r=Object.freeze(r.concat(t));let a=In("key",t.key,i,r);if(a===ot)return ot;a===si&&(t.key=null);let o=In("value",t.value,i,r);if(o===ot)return ot;o===si&&(t.value=null)}}return n}async function tc(e,t){let i=ov(t);xe.isDocument(e)?await jn(null,e.contents,i,Object.freeze([e]))===si&&(e.contents=null):await jn(null,e,i,Object.freeze([]))}tc.BREAK=ot;tc.SKIP=av;tc.REMOVE=si;async function jn(e,t,i,r){let n=await sv(e,t,i,r);if(xe.isNode(n)||xe.isPair(n))return cv(e,r,n),jn(e,n,i,r);if(typeof n!="symbol"){if(xe.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=await jn(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===ot)return ot;o===si&&(t.items.splice(a,1),a-=1)}}}else if(xe.isPair(t)){r=Object.freeze(r.concat(t));let a=await jn("key",t.key,i,r);if(a===ot)return ot;a===si&&(t.key=null);let o=await jn("value",t.value,i,r);if(o===ot)return ot;o===si&&(t.value=null)}}return n}function ov(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 sv(e,t,i,r){if(typeof i=="function")return i(e,t,r);if(xe.isMap(t))return i.Map?.(e,t,r);if(xe.isSeq(t))return i.Seq?.(e,t,r);if(xe.isPair(t))return i.Pair?.(e,t,r);if(xe.isScalar(t))return i.Scalar?.(e,t,r);if(xe.isAlias(t))return i.Alias?.(e,t,r)}function cv(e,t,i){let r=t[t.length-1];if(xe.isCollection(r))r.items[e]=i;else if(xe.isPair(r))e==="key"?r.key=i:r.value=i;else if(xe.isDocument(r))r.contents=i;else{let n=xe.isAlias(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}Nd.visit=ec;Nd.visitAsync=tc});var bd=C(uv=>{"use strict";var lv=G(),OP=Ka(),HP={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},DP=e=>e.replace(/[!,[\]{}]/g,t=>HP[t]),Ya=class e{constructor(t,i){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,i)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,i){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let r=t.trim().split(/[ \t]+/),n=r.shift();switch(n){case"%TAG":{if(r.length!==2&&(i(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[a,o]=r;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return i(0,"%YAML directive should contain exactly one part"),!1;let[a]=r;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return i(6,`Unsupported YAML version ${a}`,o),!1}}default:return i(0,`Unknown directive ${n}`,!0),!1}}tagName(t,i){if(t==="!")return"!";if(t[0]!=="!")return i(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(i(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&i("Verbatim tags must end with a >"),o)}let[,r,n]=t.match(/^(.*!)([^!]*)$/s);n||i(`The ${t} tag has no suffix`);let a=this.tags[r];if(a)try{return a+decodeURIComponent(n)}catch(o){return i(String(o)),null}return r==="!"?t:(i(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[i,r]of Object.entries(this.tags))if(t.startsWith(r))return i+DP(t.substring(r.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let i=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),n;if(t&&r.length>0&&lv.isNode(t.contents)){let a={};OP.visit(t.contents,(o,s)=>{lv.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of r)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&i.push(`%TAG ${a} ${o}`);return i.join(`
5
+ `)}};Ya.defaultYaml={explicit:!1,version:"1.2"};Ya.defaultTags={"!!":"tag:yaml.org,2002:"};uv.Directives=Ya});var ic=C(Xa=>{"use strict";var dv=G(),LP=Ka();function MP(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let i=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(i)}return!0}function fv(e){let t=new Set;return LP.visit(e,{Value(i,r){r.anchor&&t.add(r.anchor)}}),t}function hv(e,t){for(let i=1;;++i){let r=`${e}${i}`;if(!t.has(r))return r}}function FP(e,t){let i=[],r=new Map,n=null;return{onAnchor:a=>{i.push(a),n??(n=fv(e));let o=hv(t,n);return n.add(o),o},setAnchors:()=>{for(let a of i){let o=r.get(a);if(typeof o=="object"&&o.anchor&&(dv.isScalar(o.node)||dv.isCollection(o.node)))o.node.anchor=o.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=a,s}}},sourceObjects:r}}Xa.anchorIsValid=MP;Xa.anchorNames=fv;Xa.createNodeAnchors=FP;Xa.findNewAnchor=hv});var kd=C(pv=>{"use strict";function Qa(e,t,i,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let n=0,a=r.length;n<a;++n){let o=r[n],s=Qa(e,r,String(n),o);s===void 0?delete r[n]:s!==o&&(r[n]=s)}else if(r instanceof Map)for(let n of Array.from(r.keys())){let a=r.get(n),o=Qa(e,r,n,a);o===void 0?r.delete(n):o!==a&&r.set(n,o)}else if(r instanceof Set)for(let n of Array.from(r)){let a=Qa(e,r,n,n);a===void 0?r.delete(n):a!==n&&(r.delete(n),r.add(a))}else for(let[n,a]of Object.entries(r)){let o=Qa(e,r,n,a);o===void 0?delete r[n]:o!==a&&(r[n]=o)}return e.call(t,i,r)}pv.applyReviver=Qa});var Yi=C(vv=>{"use strict";var BP=G();function mv(e,t,i){if(Array.isArray(e))return e.map((r,n)=>mv(r,String(n),i));if(e&&typeof e.toJSON=="function"){if(!i||!BP.hasAnchor(e))return e.toJSON(t,i);let r={aliasCount:0,count:1,res:void 0};i.anchors.set(e,r),i.onCreate=a=>{r.res=a,delete i.onCreate};let n=e.toJSON(t,i);return i.onCreate&&i.onCreate(n),n}return typeof e=="bigint"&&!i?.keep?Number(e):e}vv.toJS=mv});var rc=C(wv=>{"use strict";var VP=kd(),gv=G(),qP=Yi(),Sd=class{constructor(t){Object.defineProperty(this,gv.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:i,maxAliasCount:r,onAnchor:n,reviver:a}={}){if(!gv.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},s=qP.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?VP.applyReviver(a,{"":s},"",s):s}};wv.NodeBase=Sd});var Za=C(yv=>{"use strict";var WP=ic(),zP=Ka(),$n=G(),JP=rc(),GP=Yi(),Ed=class extends JP.NodeBase{constructor(t){super($n.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,i){if(i?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;i?.aliasResolveCache?r=i.aliasResolveCache:(r=[],zP.visit(t,{Node:(a,o)=>{($n.isAlias(o)||$n.hasAnchor(o))&&r.push(o)}}),i&&(i.aliasResolveCache=r));let n;for(let a of r){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,i){if(!i)return{source:this.source};let{anchors:r,doc:n,maxAliasCount:a}=i,o=this.resolve(n,i);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=r.get(o);if(s||(GP.toJS(o,null,i),s=r.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=nc(n,o,r)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,i,r){let n=`*${this.source}`;if(t){if(WP.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 nc(e,t,i){if($n.isAlias(t)){let r=t.resolve(e),n=i&&r&&i.get(r);return n?n.count*n.aliasCount:0}else if($n.isCollection(t)){let r=0;for(let n of t.items){let a=nc(e,n,i);a>r&&(r=a)}return r}else if($n.isPair(t)){let r=nc(e,t.key,i),n=nc(e,t.value,i);return Math.max(r,n)}return 1}yv.Alias=Ed});var ke=C(Pd=>{"use strict";var UP=G(),KP=rc(),YP=Yi(),XP=e=>!e||typeof e!="function"&&typeof e!="object",Xi=class extends KP.NodeBase{constructor(t){super(UP.SCALAR),this.value=t}toJSON(t,i){return i?.keep?this.value:YP.toJS(this.value,t,i)}toString(){return String(this.value)}};Xi.BLOCK_FOLDED="BLOCK_FOLDED";Xi.BLOCK_LITERAL="BLOCK_LITERAL";Xi.PLAIN="PLAIN";Xi.QUOTE_DOUBLE="QUOTE_DOUBLE";Xi.QUOTE_SINGLE="QUOTE_SINGLE";Pd.Scalar=Xi;Pd.isScalarValue=XP});var eo=C(bv=>{"use strict";var QP=Za(),Ur=G(),Nv=ke(),ZP="tag:yaml.org,2002:";function eR(e,t,i){if(t){let r=i.filter(a=>a.tag===t),n=r.find(a=>!a.format)??r[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return i.find(r=>r.identify?.(e)&&!r.format)}function tR(e,t,i){if(Ur.isDocument(e)&&(e=e.contents),Ur.isNode(e))return e;if(Ur.isPair(e)){let d=i.schema[Ur.MAP].createNode?.(i.schema,null,i);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=i,c;if(r&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new QP.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=ZP+t.slice(2));let l=eR(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new Nv.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[Ur.MAP]:Symbol.iterator in Object(e)?o[Ur.SEQ]:o[Ur.MAP]}a&&(a(l),delete i.onTagObj);let u=l?.createNode?l.createNode(i.schema,e,i):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(i.schema,e,i):new Nv.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}bv.createNode=tR});var oc=C(ac=>{"use strict";var iR=eo(),ci=G(),rR=rc();function Rd(e,t,i){let r=i;for(let n=t.length-1;n>=0;--n){let a=t[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=r,r=o}else r=new Map([[a,r]])}return iR.createNode(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var kv=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Cd=class extends rR.NodeBase{constructor(t,i){super(t),Object.defineProperty(this,"schema",{value:i,configurable:!0,enumerable:!1,writable:!0})}clone(t){let i=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(i.schema=t),i.items=i.items.map(r=>ci.isNode(r)||ci.isPair(r)?r.clone(t):r),this.range&&(i.range=this.range.slice()),i}addIn(t,i){if(kv(t))this.add(i);else{let[r,...n]=t,a=this.get(r,!0);if(ci.isCollection(a))a.addIn(n,i);else if(a===void 0&&this.schema)this.set(r,Rd(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}deleteIn(t){let[i,...r]=t;if(r.length===0)return this.delete(i);let n=this.get(i,!0);if(ci.isCollection(n))return n.deleteIn(r);throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}getIn(t,i){let[r,...n]=t,a=this.get(r,!0);return n.length===0?!i&&ci.isScalar(a)?a.value:a:ci.isCollection(a)?a.getIn(n,i):void 0}hasAllNullValues(t){return this.items.every(i=>{if(!ci.isPair(i))return!1;let r=i.value;return r==null||t&&ci.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(t){let[i,...r]=t;if(r.length===0)return this.has(i);let n=this.get(i,!0);return ci.isCollection(n)?n.hasIn(r):!1}setIn(t,i){let[r,...n]=t;if(n.length===0)this.set(r,i);else{let a=this.get(r,!0);if(ci.isCollection(a))a.setIn(n,i);else if(a===void 0&&this.schema)this.set(r,Rd(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}};ac.Collection=Cd;ac.collectionFromPath=Rd;ac.isEmptyPath=kv});var to=C(sc=>{"use strict";var nR=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function xd(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var aR=(e,t,i)=>e.endsWith(`
6
+ `)?xd(i,t):i.includes(`
7
7
  `)?`
8
- `+Sd(i,t):(e.endsWith(" ")?"":" ")+i;nc.indentComment=Sd;nc.lineComment=eR;nc.stringifyComment=ZP});var Sv=C(Xa=>{"use strict";var tR="flow",Ed="block",ac="quoted";function iR(e,t,i="flow",{indentAtStart:r,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;n<a&&(a=0);let c=Math.max(1+a,1+n-t.length);if(e.length<=c)return e;let l=[],u={},d=n-t.length;typeof r=="number"&&(r>n-Math.max(2,a)?l.push(0):d=n-r);let f,h,v=!1,m=-1,p=-1,b=-1;i===Ed&&(m=kv(e,m,t.length),m!==-1&&(d=m+c));for(let y;y=e[m+=1];){if(i===ac&&y==="\\"){switch(p=m,e[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}b=m}if(y===`
9
- `)i===Ed&&(m=kv(e,m,t.length)),d=m+t.length+c,f=void 0;else{if(y===" "&&h&&h!==" "&&h!==`
8
+ `+xd(i,t):(e.endsWith(" ")?"":" ")+i;sc.indentComment=xd;sc.lineComment=aR;sc.stringifyComment=nR});var Ev=C(io=>{"use strict";var oR="flow",Ad="block",cc="quoted";function sR(e,t,i="flow",{indentAtStart:r,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;n<a&&(a=0);let c=Math.max(1+a,1+n-t.length);if(e.length<=c)return e;let l=[],u={},d=n-t.length;typeof r=="number"&&(r>n-Math.max(2,a)?l.push(0):d=n-r);let f,h,v=!1,m=-1,p=-1,b=-1;i===Ad&&(m=Sv(e,m,t.length),m!==-1&&(d=m+c));for(let y;y=e[m+=1];){if(i===cc&&y==="\\"){switch(p=m,e[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}b=m}if(y===`
9
+ `)i===Ad&&(m=Sv(e,m,t.length)),d=m+t.length+c,f=void 0;else{if(y===" "&&h&&h!==" "&&h!==`
10
10
  `&&h!==" "){let E=e[m+1];E&&E!==" "&&E!==`
11
- `&&E!==" "&&(f=m)}if(m>=d)if(f)l.push(f),d=f+c,f=void 0;else if(i===ac){for(;h===" "||h===" ";)h=y,y=e[m+=1],v=!0;let E=m>b+1?m-2:p-1;if(u[E])return e;l.push(E),u[E]=!0,d=E+c,f=void 0}else v=!0}h=y}if(v&&s&&s(),l.length===0)return e;o&&o();let g=e.slice(0,l[0]);for(let y=0;y<l.length;++y){let E=l[y],k=l[y+1]||e.length;E===0?g=`
12
- ${t}${e.slice(0,k)}`:(i===ac&&u[E]&&(g+=`${e[E]}\\`),g+=`
13
- ${t}${e.slice(E+1,k)}`)}return g}function kv(e,t,i){let r=t,n=t+1,a=e[n];for(;a===" "||a===" ";)if(t<n+i)a=e[++t];else{do a=e[++t];while(a&&a!==`
14
- `);r=t,n=t+1,a=e[n]}return r}Xa.FOLD_BLOCK=Ed;Xa.FOLD_FLOW=tR;Xa.FOLD_QUOTED=ac;Xa.foldFlowLines=iR});var Za=C(Ev=>{"use strict";var Wt=ke(),Ki=Sv(),sc=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),cc=e=>/^(%|---|\.\.\.)/m.test(e);function rR(e,t,i){if(!t||t<0)return!1;let r=t-i,n=e.length;if(n<=r)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
15
- `){if(a-o>r)return!0;if(o=a+1,n-o<=r)return!1}return!0}function Qa(e,t){let i=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return i;let{implicitKey:r}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(cc(e)?" ":""),o="",s=0;for(let c=0,l=i[c];l;l=i[++c])if(l===" "&&i[c+1]==="\\"&&i[c+2]==="n"&&(o+=i.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(i[c+1]){case"u":{o+=i.slice(s,c);let u=i.substr(c+2,4);switch(u){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=i.substr(c,6)}c+=5,s=c+1}break;case"n":if(r||i[c+2]==='"'||i.length<n)c+=1;else{for(o+=i.slice(s,c)+`
11
+ `&&E!==" "&&(f=m)}if(m>=d)if(f)l.push(f),d=f+c,f=void 0;else if(i===cc){for(;h===" "||h===" ";)h=y,y=e[m+=1],v=!0;let E=m>b+1?m-2:p-1;if(u[E])return e;l.push(E),u[E]=!0,d=E+c,f=void 0}else v=!0}h=y}if(v&&s&&s(),l.length===0)return e;o&&o();let g=e.slice(0,l[0]);for(let y=0;y<l.length;++y){let E=l[y],k=l[y+1]||e.length;E===0?g=`
12
+ ${t}${e.slice(0,k)}`:(i===cc&&u[E]&&(g+=`${e[E]}\\`),g+=`
13
+ ${t}${e.slice(E+1,k)}`)}return g}function Sv(e,t,i){let r=t,n=t+1,a=e[n];for(;a===" "||a===" ";)if(t<n+i)a=e[++t];else{do a=e[++t];while(a&&a!==`
14
+ `);r=t,n=t+1,a=e[n]}return r}io.FOLD_BLOCK=Ad;io.FOLD_FLOW=oR;io.FOLD_QUOTED=cc;io.foldFlowLines=sR});var no=C(Pv=>{"use strict";var Wt=ke(),Qi=Ev(),uc=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),dc=e=>/^(%|---|\.\.\.)/m.test(e);function cR(e,t,i){if(!t||t<0)return!1;let r=t-i,n=e.length;if(n<=r)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
15
+ `){if(a-o>r)return!0;if(o=a+1,n-o<=r)return!1}return!0}function ro(e,t){let i=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return i;let{implicitKey:r}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(dc(e)?" ":""),o="",s=0;for(let c=0,l=i[c];l;l=i[++c])if(l===" "&&i[c+1]==="\\"&&i[c+2]==="n"&&(o+=i.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(i[c+1]){case"u":{o+=i.slice(s,c);let u=i.substr(c+2,4);switch(u){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=i.substr(c,6)}c+=5,s=c+1}break;case"n":if(r||i[c+2]==='"'||i.length<n)c+=1;else{for(o+=i.slice(s,c)+`
16
16
 
17
17
  `;i[c+2]==="\\"&&i[c+3]==="n"&&i[c+4]!=='"';)o+=`
18
- `,c+=2;o+=a,i[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+i.slice(s):i,r?o:Ki.foldFlowLines(o,a,Ki.FOLD_QUOTED,sc(t,!1))}function Pd(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
19
- `)||/[ \t]\n|\n[ \t]/.test(e))return Qa(e,t);let i=t.indent||(cc(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
20
- ${i}`)+"'";return t.implicitKey?r:Ki.foldFlowLines(r,i,Ki.FOLD_FLOW,sc(t,!1))}function _n(e,t){let{singleQuote:i}=t.options,r;if(i===!1)r=Qa;else{let n=e.includes('"'),a=e.includes("'");n&&!a?r=Pd:a&&!n?r=Qa:r=i?Pd:Qa}return r(e,t)}var Rd;try{Rd=new RegExp(`(^|(?<!
18
+ `,c+=2;o+=a,i[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+i.slice(s):i,r?o:Qi.foldFlowLines(o,a,Qi.FOLD_QUOTED,uc(t,!1))}function _d(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
19
+ `)||/[ \t]\n|\n[ \t]/.test(e))return ro(e,t);let i=t.indent||(dc(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
20
+ ${i}`)+"'";return t.implicitKey?r:Qi.foldFlowLines(r,i,Qi.FOLD_FLOW,uc(t,!1))}function On(e,t){let{singleQuote:i}=t.options,r;if(i===!1)r=ro;else{let n=e.includes('"'),a=e.includes("'");n&&!a?r=_d:a&&!n?r=ro:r=i?_d:ro}return r(e,t)}var Td;try{Td=new RegExp(`(^|(?<!
21
21
  ))
22
22
  +(?!
23
- |$)`,"g")}catch{Rd=/\n+(?!\n|$)/g}function oc({comment:e,type:t,value:i},r,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(i))return _n(i,r);let l=r.indent||(r.forceBlockIndent||cc(i)?" ":""),u=o==="literal"?!0:o==="folded"||t===Wt.Scalar.BLOCK_FOLDED?!1:t===Wt.Scalar.BLOCK_LITERAL?!0:!rR(i,c,l.length);if(!i)return u?`|
23
+ |$)`,"g")}catch{Td=/\n+(?!\n|$)/g}function lc({comment:e,type:t,value:i},r,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(i))return On(i,r);let l=r.indent||(r.forceBlockIndent||dc(i)?" ":""),u=o==="literal"?!0:o==="folded"||t===Wt.Scalar.BLOCK_FOLDED?!1:t===Wt.Scalar.BLOCK_LITERAL?!0:!cR(i,c,l.length);if(!i)return u?`|
24
24
  `:`>
25
25
  `;let d,f;for(f=i.length;f>0;--f){let k=i[f-1];if(k!==`
26
26
  `&&k!==" "&&k!==" ")break}let h=i.substring(f),v=h.indexOf(`
27
27
  `);v===-1?d="-":i===h||v!==h.length-1?(d="+",a&&a()):d="",h&&(i=i.slice(0,-h.length),h[h.length-1]===`
28
- `&&(h=h.slice(0,-1)),h=h.replace(Rd,`$&${l}`));let m=!1,p,b=-1;for(p=0;p<i.length;++p){let k=i[p];if(k===" ")m=!0;else if(k===`
28
+ `&&(h=h.slice(0,-1)),h=h.replace(Td,`$&${l}`));let m=!1,p,b=-1;for(p=0;p<i.length;++p){let k=i[p];if(k===" ")m=!0;else if(k===`
29
29
  `)b=p;else break}let g=i.substring(0,b<p?b+1:p);g&&(i=i.substring(g.length),g=g.replace(/\n+/g,`$&${l}`));let E=(m?l?"2":"1":"")+d;if(e&&(E+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!u){let k=i.replace(/\n+/g,`
30
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),S=!1,R=sc(r,!0);o!=="folded"&&t!==Wt.Scalar.BLOCK_FOLDED&&(R.onOverflow=()=>{S=!0});let N=Ki.foldFlowLines(`${g}${k}${h}`,l,Ki.FOLD_BLOCK,R);if(!S)return`>${E}
30
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),S=!1,R=uc(r,!0);o!=="folded"&&t!==Wt.Scalar.BLOCK_FOLDED&&(R.onOverflow=()=>{S=!0});let N=Qi.foldFlowLines(`${g}${k}${h}`,l,Qi.FOLD_BLOCK,R);if(!S)return`>${E}
31
31
  ${l}${N}`}return i=i.replace(/\n+/g,`$&${l}`),`|${E}
32
- ${l}${g}${i}${h}`}function nR(e,t,i,r){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
33
- `)||u&&/[[\]{},]/.test(a))return _n(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
34
- `)?_n(a,t):oc(e,t,i,r);if(!s&&!u&&n!==Wt.Scalar.PLAIN&&a.includes(`
35
- `))return oc(e,t,i,r);if(cc(a)){if(c==="")return t.forceBlockIndent=!0,oc(e,t,i,r);if(s&&c===l)return _n(a,t)}let d=a.replace(/\n+/g,`$&
36
- ${c}`);if(o){let f=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(d),{compat:h,tags:v}=t.doc.schema;if(v.some(f)||h?.some(f))return _n(a,t)}return s?d:Ki.foldFlowLines(d,c,Ki.FOLD_FLOW,sc(t,!1))}function aR(e,t,i,r){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==Wt.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=Wt.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case Wt.Scalar.BLOCK_FOLDED:case Wt.Scalar.BLOCK_LITERAL:return n||a?_n(o.value,t):oc(o,t,i,r);case Wt.Scalar.QUOTE_DOUBLE:return Qa(o.value,t);case Wt.Scalar.QUOTE_SINGLE:return Pd(o.value,t);case Wt.Scalar.PLAIN:return nR(o,t,i,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:d}=t.options,f=n&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}Ev.stringifyString=aR});var eo=C(Cd=>{"use strict";var oR=Zs(),Yi=G(),sR=Ya(),cR=Za();function lR(e,t){let i=Object.assign({blockQuote:!0,commentString:sR.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),r;switch(i.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:i.flowCollectionPadding?" ":"",indent:"",indentStep:typeof i.indent=="number"?" ".repeat(i.indent):" ",inFlow:r,options:i}}function uR(e,t){if(t.tag){let n=e.filter(a=>a.tag===t.tag);if(n.length>0)return n.find(a=>a.format===t.format)??n[0]}let i,r;if(Yi.isScalar(t)){r=t.value;let n=e.filter(a=>a.identify?.(r));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}i=n.find(a=>a.format===t.format)??n.find(a=>!a.format)}else r=t,i=e.find(n=>n.nodeClass&&r instanceof n.nodeClass);if(!i){let n=r?.constructor?.name??(r===null?"null":typeof r);throw new Error(`Tag not resolved for ${n} value`)}return i}function dR(e,t,{anchors:i,doc:r}){if(!r.directives)return"";let n=[],a=(Yi.isScalar(e)||Yi.isCollection(e))&&e.anchor;a&&oR.anchorIsValid(a)&&(i.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(r.directives.tagString(o)),n.join(" ")}function fR(e,t,i,r){if(Yi.isPair(e))return e.toString(t,i,r);if(Yi.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let n,a=Yi.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=uR(t.doc.schema.tags,a));let o=dR(a,n,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,t,i,r):Yi.isScalar(a)?cR.stringifyString(a,t,i,r):a.toString(t,i,r);return o?Yi.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
- ${t.indent}${s}`:s}Cd.createStringifyContext=lR;Cd.stringify=fR});var xv=C(Cv=>{"use strict";var Ci=G(),Pv=ke(),Rv=eo(),to=Ya();function hR({key:e,value:t},i,r,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=i,f=Ci.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(Ci.isCollection(e)||!Ci.isNode(e)&&typeof e=="object"){let R="With simple keys, collection cannot be used as a key value";throw new Error(R)}}let h=!d&&(!e||f&&t==null&&!i.inFlow||Ci.isCollection(e)||(Ci.isScalar(e)?e.type===Pv.Scalar.BLOCK_FOLDED||e.type===Pv.Scalar.BLOCK_LITERAL:typeof e=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!h&&(d||!a),indent:s+c});let v=!1,m=!1,p=Rv.stringify(e,i,()=>v=!0,()=>m=!0);if(!h&&!i.inFlow&&p.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(i.inFlow){if(a||t==null)return v&&r&&r(),p===""?"?":h?`? ${p}`:p}else if(a&&!d||t==null&&h)return p=`? ${p}`,f&&!v?p+=to.lineComment(p,i.indent,l(f)):m&&n&&n(),p;v&&(f=null),h?(f&&(p+=to.lineComment(p,i.indent,l(f))),p=`? ${p}
38
- ${s}:`):(p=`${p}:`,f&&(p+=to.lineComment(p,i.indent,l(f))));let b,g,y;Ci.isNode(t)?(b=!!t.spaceBefore,g=t.commentBefore,y=t.comment):(b=!1,g=null,y=null,t&&typeof t=="object"&&(t=o.createNode(t))),i.implicitKey=!1,!h&&!f&&Ci.isScalar(t)&&(i.indentAtStart=p.length+1),m=!1,!u&&c.length>=2&&!i.inFlow&&!h&&Ci.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(i.indent=i.indent.substring(2));let E=!1,k=Rv.stringify(t,i,()=>E=!0,()=>m=!0),S=" ";if(f||b||g){if(S=b?`
32
+ ${l}${g}${i}${h}`}function lR(e,t,i,r){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
33
+ `)||u&&/[[\]{},]/.test(a))return On(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
34
+ `)?On(a,t):lc(e,t,i,r);if(!s&&!u&&n!==Wt.Scalar.PLAIN&&a.includes(`
35
+ `))return lc(e,t,i,r);if(dc(a)){if(c==="")return t.forceBlockIndent=!0,lc(e,t,i,r);if(s&&c===l)return On(a,t)}let d=a.replace(/\n+/g,`$&
36
+ ${c}`);if(o){let f=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(d),{compat:h,tags:v}=t.doc.schema;if(v.some(f)||h?.some(f))return On(a,t)}return s?d:Qi.foldFlowLines(d,c,Qi.FOLD_FLOW,uc(t,!1))}function uR(e,t,i,r){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==Wt.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=Wt.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case Wt.Scalar.BLOCK_FOLDED:case Wt.Scalar.BLOCK_LITERAL:return n||a?On(o.value,t):lc(o,t,i,r);case Wt.Scalar.QUOTE_DOUBLE:return ro(o.value,t);case Wt.Scalar.QUOTE_SINGLE:return _d(o.value,t);case Wt.Scalar.PLAIN:return lR(o,t,i,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:d}=t.options,f=n&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}Pv.stringifyString=uR});var ao=C(Id=>{"use strict";var dR=ic(),Zi=G(),fR=to(),hR=no();function pR(e,t){let i=Object.assign({blockQuote:!0,commentString:fR.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),r;switch(i.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:i.flowCollectionPadding?" ":"",indent:"",indentStep:typeof i.indent=="number"?" ".repeat(i.indent):" ",inFlow:r,options:i}}function mR(e,t){if(t.tag){let n=e.filter(a=>a.tag===t.tag);if(n.length>0)return n.find(a=>a.format===t.format)??n[0]}let i,r;if(Zi.isScalar(t)){r=t.value;let n=e.filter(a=>a.identify?.(r));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}i=n.find(a=>a.format===t.format)??n.find(a=>!a.format)}else r=t,i=e.find(n=>n.nodeClass&&r instanceof n.nodeClass);if(!i){let n=r?.constructor?.name??(r===null?"null":typeof r);throw new Error(`Tag not resolved for ${n} value`)}return i}function vR(e,t,{anchors:i,doc:r}){if(!r.directives)return"";let n=[],a=(Zi.isScalar(e)||Zi.isCollection(e))&&e.anchor;a&&dR.anchorIsValid(a)&&(i.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(r.directives.tagString(o)),n.join(" ")}function gR(e,t,i,r){if(Zi.isPair(e))return e.toString(t,i,r);if(Zi.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=Zi.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=mR(t.doc.schema.tags,a));let o=vR(a,n,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,t,i,r):Zi.isScalar(a)?hR.stringifyString(a,t,i,r):a.toString(t,i,r);return o?Zi.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
+ ${t.indent}${s}`:s}Id.createStringifyContext=pR;Id.stringify=gR});var Av=C(xv=>{"use strict";var xi=G(),Rv=ke(),Cv=ao(),oo=to();function wR({key:e,value:t},i,r,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=i,f=xi.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(xi.isCollection(e)||!xi.isNode(e)&&typeof e=="object"){let R="With simple keys, collection cannot be used as a key value";throw new Error(R)}}let h=!d&&(!e||f&&t==null&&!i.inFlow||xi.isCollection(e)||(xi.isScalar(e)?e.type===Rv.Scalar.BLOCK_FOLDED||e.type===Rv.Scalar.BLOCK_LITERAL:typeof e=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!h&&(d||!a),indent:s+c});let v=!1,m=!1,p=Cv.stringify(e,i,()=>v=!0,()=>m=!0);if(!h&&!i.inFlow&&p.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(i.inFlow){if(a||t==null)return v&&r&&r(),p===""?"?":h?`? ${p}`:p}else if(a&&!d||t==null&&h)return p=`? ${p}`,f&&!v?p+=oo.lineComment(p,i.indent,l(f)):m&&n&&n(),p;v&&(f=null),h?(f&&(p+=oo.lineComment(p,i.indent,l(f))),p=`? ${p}
38
+ ${s}:`):(p=`${p}:`,f&&(p+=oo.lineComment(p,i.indent,l(f))));let b,g,y;xi.isNode(t)?(b=!!t.spaceBefore,g=t.commentBefore,y=t.comment):(b=!1,g=null,y=null,t&&typeof t=="object"&&(t=o.createNode(t))),i.implicitKey=!1,!h&&!f&&xi.isScalar(t)&&(i.indentAtStart=p.length+1),m=!1,!u&&c.length>=2&&!i.inFlow&&!h&&xi.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(i.indent=i.indent.substring(2));let E=!1,k=Cv.stringify(t,i,()=>E=!0,()=>m=!0),S=" ";if(f||b||g){if(S=b?`
39
39
  `:"",g){let R=l(g);S+=`
40
- ${to.indentComment(R,i.indent)}`}k===""&&!i.inFlow?S===`
40
+ ${oo.indentComment(R,i.indent)}`}k===""&&!i.inFlow?S===`
41
41
  `&&y&&(S=`
42
42
 
43
43
  `):S+=`
44
- ${i.indent}`}else if(!h&&Ci.isCollection(t)){let R=k[0],N=k.indexOf(`
44
+ ${i.indent}`}else if(!h&&xi.isCollection(t)){let R=k[0],N=k.indexOf(`
45
45
  `),w=N!==-1,P=i.inFlow??t.flow??t.items.length===0;if(w||!P){let F=!1;if(w&&(R==="&"||R==="!")){let $=k.indexOf(" ");R==="&"&&$!==-1&&$<N&&k[$+1]==="!"&&($=k.indexOf(" ",$+1)),($===-1||N<$)&&(F=!0)}F||(S=`
46
46
  ${i.indent}`)}}else(k===""||k[0]===`
47
- `)&&(S="");return p+=S+k,i.inFlow?E&&r&&r():y&&!E?p+=to.lineComment(p,i.indent,l(y)):m&&n&&n(),p}Cv.stringifyPair=hR});var Ad=C(xd=>{"use strict";var Av=Js("process");function pR(e,...t){e==="debug"&&console.log(...t)}function mR(e,t){(e==="debug"||e==="warn")&&(typeof Av.emitWarning=="function"?Av.emitWarning(t):console.warn(t))}xd.debug=pR;xd.warn=mR});var hc=C(fc=>{"use strict";var dc=G(),_v=ke(),lc="<<",uc={identify:e=>e===lc||typeof e=="symbol"&&e.description===lc,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new _v.Scalar(Symbol(lc)),{addToJSMap:Tv}),stringify:()=>lc},vR=(e,t)=>(uc.identify(t)||dc.isScalar(t)&&(!t.type||t.type===_v.Scalar.PLAIN)&&uc.identify(t.value))&&e?.doc.schema.tags.some(i=>i.tag===uc.tag&&i.default);function Tv(e,t,i){let r=Iv(e,i);if(dc.isSeq(r))for(let n of r.items)_d(e,t,n);else if(Array.isArray(r))for(let n of r)_d(e,t,n);else _d(e,t,r)}function _d(e,t,i){let r=Iv(e,i);if(!dc.isMap(r))throw new Error("Merge sources must be maps or map aliases");let n=r.toJSON(null,e,Map);for(let[a,o]of n)t instanceof Map?t.has(a)||t.set(a,o):t instanceof Set?t.add(a):Object.prototype.hasOwnProperty.call(t,a)||Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function Iv(e,t){return e&&dc.isAlias(t)?t.resolve(e.doc,e):t}fc.addMergeToJSMap=Tv;fc.isMergeKey=vR;fc.merge=uc});var Id=C(Ov=>{"use strict";var gR=Ad(),jv=hc(),wR=eo(),$v=G(),Td=Gi();function yR(e,t,{key:i,value:r}){if($v.isNode(i)&&i.addToJSMap)i.addToJSMap(e,t,r);else if(jv.isMergeKey(e,i))jv.addMergeToJSMap(e,t,r);else{let n=Td.toJS(i,"",e);if(t instanceof Map)t.set(n,Td.toJS(r,n,e));else if(t instanceof Set)t.add(n);else{let a=NR(i,n,e),o=Td.toJS(r,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function NR(e,t,i){if(t===null)return"";if(typeof t!="object")return String(t);if($v.isNode(e)&&i?.doc){let r=wR.createStringifyContext(i.doc,{});r.anchors=new Set;for(let a of i.anchors.keys())r.anchors.add(a.anchor);r.inFlow=!0,r.inStringifyKey=!0;let n=e.toString(r);if(!i.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),gR.warn(i.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),i.mapKeyWarned=!0}return n}return JSON.stringify(t)}Ov.addPairToJSMap=yR});var Xi=C(jd=>{"use strict";var Hv=Ka(),bR=xv(),kR=Id(),pc=G();function SR(e,t,i){let r=Hv.createNode(e,void 0,i),n=Hv.createNode(t,void 0,i);return new mc(r,n)}var mc=class e{constructor(t,i=null){Object.defineProperty(this,pc.NODE_TYPE,{value:pc.PAIR}),this.key=t,this.value=i}clone(t){let{key:i,value:r}=this;return pc.isNode(i)&&(i=i.clone(t)),pc.isNode(r)&&(r=r.clone(t)),new e(i,r)}toJSON(t,i){let r=i?.mapAsMap?new Map:{};return kR.addPairToJSMap(i,r,this)}toString(t,i,r){return t?.doc?bR.stringifyPair(this,t,i,r):JSON.stringify(this)}};jd.Pair=mc;jd.createPair=SR});var $d=C(Lv=>{"use strict";var Gr=G(),Dv=eo(),vc=Ya();function ER(e,t,i){return(t.inFlow??e.flow?RR:PR)(e,t,i)}function PR({comment:e,items:t},i,{blockItemPrefix:r,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=i,u=Object.assign({},i,{indent:a,type:null}),d=!1,f=[];for(let v=0;v<t.length;++v){let m=t[v],p=null;if(Gr.isNode(m))!d&&m.spaceBefore&&f.push(""),gc(i,f,m.commentBefore,d),m.comment&&(p=m.comment);else if(Gr.isPair(m)){let g=Gr.isNode(m.key)?m.key:null;g&&(!d&&g.spaceBefore&&f.push(""),gc(i,f,g.commentBefore,d))}d=!1;let b=Dv.stringify(m,u,()=>p=null,()=>d=!0);p&&(b+=vc.lineComment(b,a,l(p))),d&&p&&(d=!1),f.push(r+b)}let h;if(f.length===0)h=n.start+n.end;else{h=f[0];for(let v=1;v<f.length;++v){let m=f[v];h+=m?`
47
+ `)&&(S="");return p+=S+k,i.inFlow?E&&r&&r():y&&!E?p+=oo.lineComment(p,i.indent,l(y)):m&&n&&n(),p}xv.stringifyPair=wR});var $d=C(jd=>{"use strict";var _v=Ks("process");function yR(e,...t){e==="debug"&&console.log(...t)}function NR(e,t){(e==="debug"||e==="warn")&&(typeof _v.emitWarning=="function"?_v.emitWarning(t):console.warn(t))}jd.debug=yR;jd.warn=NR});var vc=C(mc=>{"use strict";var pc=G(),Tv=ke(),fc="<<",hc={identify:e=>e===fc||typeof e=="symbol"&&e.description===fc,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Tv.Scalar(Symbol(fc)),{addToJSMap:Iv}),stringify:()=>fc},bR=(e,t)=>(hc.identify(t)||pc.isScalar(t)&&(!t.type||t.type===Tv.Scalar.PLAIN)&&hc.identify(t.value))&&e?.doc.schema.tags.some(i=>i.tag===hc.tag&&i.default);function Iv(e,t,i){let r=jv(e,i);if(pc.isSeq(r))for(let n of r.items)Od(e,t,n);else if(Array.isArray(r))for(let n of r)Od(e,t,n);else Od(e,t,r)}function Od(e,t,i){let r=jv(e,i);if(!pc.isMap(r))throw new Error("Merge sources must be maps or map aliases");let n=r.toJSON(null,e,Map);for(let[a,o]of n)t instanceof Map?t.has(a)||t.set(a,o):t instanceof Set?t.add(a):Object.prototype.hasOwnProperty.call(t,a)||Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function jv(e,t){return e&&pc.isAlias(t)?t.resolve(e.doc,e):t}mc.addMergeToJSMap=Iv;mc.isMergeKey=bR;mc.merge=hc});var Dd=C(Hv=>{"use strict";var kR=$d(),$v=vc(),SR=ao(),Ov=G(),Hd=Yi();function ER(e,t,{key:i,value:r}){if(Ov.isNode(i)&&i.addToJSMap)i.addToJSMap(e,t,r);else if($v.isMergeKey(e,i))$v.addMergeToJSMap(e,t,r);else{let n=Hd.toJS(i,"",e);if(t instanceof Map)t.set(n,Hd.toJS(r,n,e));else if(t instanceof Set)t.add(n);else{let a=PR(i,n,e),o=Hd.toJS(r,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function PR(e,t,i){if(t===null)return"";if(typeof t!="object")return String(t);if(Ov.isNode(e)&&i?.doc){let r=SR.createStringifyContext(i.doc,{});r.anchors=new Set;for(let a of i.anchors.keys())r.anchors.add(a.anchor);r.inFlow=!0,r.inStringifyKey=!0;let n=e.toString(r);if(!i.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),kR.warn(i.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),i.mapKeyWarned=!0}return n}return JSON.stringify(t)}Hv.addPairToJSMap=ER});var er=C(Ld=>{"use strict";var Dv=eo(),RR=Av(),CR=Dd(),gc=G();function xR(e,t,i){let r=Dv.createNode(e,void 0,i),n=Dv.createNode(t,void 0,i);return new wc(r,n)}var wc=class e{constructor(t,i=null){Object.defineProperty(this,gc.NODE_TYPE,{value:gc.PAIR}),this.key=t,this.value=i}clone(t){let{key:i,value:r}=this;return gc.isNode(i)&&(i=i.clone(t)),gc.isNode(r)&&(r=r.clone(t)),new e(i,r)}toJSON(t,i){let r=i?.mapAsMap?new Map:{};return CR.addPairToJSMap(i,r,this)}toString(t,i,r){return t?.doc?RR.stringifyPair(this,t,i,r):JSON.stringify(this)}};Ld.Pair=wc;Ld.createPair=xR});var Md=C(Mv=>{"use strict";var Kr=G(),Lv=ao(),yc=to();function AR(e,t,i){return(t.inFlow??e.flow?TR:_R)(e,t,i)}function _R({comment:e,items:t},i,{blockItemPrefix:r,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=i,u=Object.assign({},i,{indent:a,type:null}),d=!1,f=[];for(let v=0;v<t.length;++v){let m=t[v],p=null;if(Kr.isNode(m))!d&&m.spaceBefore&&f.push(""),Nc(i,f,m.commentBefore,d),m.comment&&(p=m.comment);else if(Kr.isPair(m)){let g=Kr.isNode(m.key)?m.key:null;g&&(!d&&g.spaceBefore&&f.push(""),Nc(i,f,g.commentBefore,d))}d=!1;let b=Lv.stringify(m,u,()=>p=null,()=>d=!0);p&&(b+=yc.lineComment(b,a,l(p))),d&&p&&(d=!1),f.push(r+b)}let h;if(f.length===0)h=n.start+n.end;else{h=f[0];for(let v=1;v<f.length;++v){let m=f[v];h+=m?`
48
48
  ${c}${m}`:`
49
49
  `}}return e?(h+=`
50
- `+vc.indentComment(l(e),c),s&&s()):d&&o&&o(),h}function RR({items:e},t,{flowChars:i,itemIndent:r}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;r+=a;let c=Object.assign({},t,{indent:r,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let v=0;v<e.length;++v){let m=e[v],p=null;if(Gr.isNode(m))m.spaceBefore&&d.push(""),gc(t,d,m.commentBefore,!1),m.comment&&(p=m.comment);else if(Gr.isPair(m)){let g=Gr.isNode(m.key)?m.key:null;g&&(g.spaceBefore&&d.push(""),gc(t,d,g.commentBefore,!1),g.comment&&(l=!0));let y=Gr.isNode(m.value)?m.value:null;y?(y.comment&&(p=y.comment),y.commentBefore&&(l=!0)):m.value==null&&g?.comment&&(p=g.comment)}p&&(l=!0);let b=Dv.stringify(m,c,()=>p=null);l||(l=d.length>u||b.includes(`
51
- `)),v<e.length-1?b+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((g,y)=>g+y.length+2,2)+(b.length+2)>t.options.lineWidth)),l&&(b+=",")),p&&(b+=vc.lineComment(b,r,s(p))),d.push(b),u=d.length}let{start:f,end:h}=i;if(d.length===0)return f+h;if(!l){let v=d.reduce((m,p)=>m+p.length+2,2);l=t.options.lineWidth>0&&v>t.options.lineWidth}if(l){let v=f;for(let m of d)v+=m?`
50
+ `+yc.indentComment(l(e),c),s&&s()):d&&o&&o(),h}function TR({items:e},t,{flowChars:i,itemIndent:r}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;r+=a;let c=Object.assign({},t,{indent:r,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let v=0;v<e.length;++v){let m=e[v],p=null;if(Kr.isNode(m))m.spaceBefore&&d.push(""),Nc(t,d,m.commentBefore,!1),m.comment&&(p=m.comment);else if(Kr.isPair(m)){let g=Kr.isNode(m.key)?m.key:null;g&&(g.spaceBefore&&d.push(""),Nc(t,d,g.commentBefore,!1),g.comment&&(l=!0));let y=Kr.isNode(m.value)?m.value:null;y?(y.comment&&(p=y.comment),y.commentBefore&&(l=!0)):m.value==null&&g?.comment&&(p=g.comment)}p&&(l=!0);let b=Lv.stringify(m,c,()=>p=null);l||(l=d.length>u||b.includes(`
51
+ `)),v<e.length-1?b+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((g,y)=>g+y.length+2,2)+(b.length+2)>t.options.lineWidth)),l&&(b+=",")),p&&(b+=yc.lineComment(b,r,s(p))),d.push(b),u=d.length}let{start:f,end:h}=i;if(d.length===0)return f+h;if(!l){let v=d.reduce((m,p)=>m+p.length+2,2);l=t.options.lineWidth>0&&v>t.options.lineWidth}if(l){let v=f;for(let m of d)v+=m?`
52
52
  ${a}${n}${m}`:`
53
53
  `;return`${v}
54
- ${n}${h}`}else return`${f}${o}${d.join(" ")}${o}${h}`}function gc({indent:e,options:{commentString:t}},i,r,n){if(r&&n&&(r=r.replace(/^\n+/,"")),r){let a=vc.indentComment(t(r),e);i.push(a.trimStart())}}Lv.stringifyCollection=ER});var Zi=C(Hd=>{"use strict";var CR=$d(),xR=Id(),AR=rc(),Qi=G(),wc=Xi(),_R=ke();function io(e,t){let i=Qi.isScalar(t)?t.value:t;for(let r of e)if(Qi.isPair(r)&&(r.key===t||r.key===i||Qi.isScalar(r.key)&&r.key.value===i))return r}var Od=class extends AR.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Qi.MAP,t),this.items=[]}static from(t,i,r){let{keepUndefined:n,replacer:a}=r,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(i,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||n)&&o.items.push(wc.createPair(c,l,r))};if(i instanceof Map)for(let[c,l]of i)s(c,l);else if(i&&typeof i=="object")for(let c of Object.keys(i))s(c,i[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,i){let r;Qi.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new wc.Pair(t,t?.value):r=new wc.Pair(t.key,t.value);let n=io(this.items,r.key),a=this.schema?.sortMapEntries;if(n){if(!i)throw new Error(`Key ${r.key} already set`);Qi.isScalar(n.value)&&_R.isScalarValue(r.value)?n.value.value=r.value:n.value=r.value}else if(a){let o=this.items.findIndex(s=>a(r,s)<0);o===-1?this.items.push(r):this.items.splice(o,0,r)}else this.items.push(r)}delete(t){let i=io(this.items,t);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(t,i){let n=io(this.items,t)?.value;return(!i&&Qi.isScalar(n)?n.value:n)??void 0}has(t){return!!io(this.items,t)}set(t,i){this.add(new wc.Pair(t,i),!0)}toJSON(t,i,r){let n=r?new r:i?.mapAsMap?new Map:{};i?.onCreate&&i.onCreate(n);for(let a of this.items)xR.addPairToJSMap(i,n,a);return n}toString(t,i,r){if(!t)return JSON.stringify(this);for(let n of this.items)if(!Qi.isPair(n))throw new Error(`Map items must all be pairs; found ${JSON.stringify(n)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),CR.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:i})}};Hd.YAMLMap=Od;Hd.findPair=io});var Tn=C(Fv=>{"use strict";var TR=G(),Mv=Zi(),IR={collection:"map",default:!0,nodeClass:Mv.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return TR.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,i)=>Mv.YAMLMap.from(e,t,i)};Fv.map=IR});var er=C(Bv=>{"use strict";var jR=Ka(),$R=$d(),OR=rc(),Nc=G(),HR=ke(),DR=Gi(),Dd=class extends OR.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Nc.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let i=yc(t);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(t,i){let r=yc(t);if(typeof r!="number")return;let n=this.items[r];return!i&&Nc.isScalar(n)?n.value:n}has(t){let i=yc(t);return typeof i=="number"&&i<this.items.length}set(t,i){let r=yc(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[r];Nc.isScalar(n)&&HR.isScalarValue(i)?n.value=i:this.items[r]=i}toJSON(t,i){let r=[];i?.onCreate&&i.onCreate(r);let n=0;for(let a of this.items)r.push(DR.toJS(a,String(n++),i));return r}toString(t,i,r){return t?$R.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:r,onComment:i}):JSON.stringify(this)}static from(t,i,r){let{replacer:n}=r,a=new this(t);if(i&&Symbol.iterator in Object(i)){let o=0;for(let s of i){if(typeof n=="function"){let c=i instanceof Set?s:String(o++);s=n.call(i,c,s)}a.items.push(jR.createNode(s,void 0,r))}}return a}};function yc(e){let t=Nc.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Bv.YAMLSeq=Dd});var In=C(qv=>{"use strict";var LR=G(),Vv=er(),MR={collection:"seq",default:!0,nodeClass:Vv.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return LR.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,i)=>Vv.YAMLSeq.from(e,t,i)};qv.seq=MR});var ro=C(Wv=>{"use strict";var FR=Za(),BR={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,i,r){return t=Object.assign({actualString:!0},t),FR.stringifyString(e,t,i,r)}};Wv.string=BR});var bc=C(Gv=>{"use strict";var zv=ke(),Jv={identify:e=>e==null,createNode:()=>new zv.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new zv.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Jv.test.test(e)?e:t.options.nullStr};Gv.nullTag=Jv});var Ld=C(Kv=>{"use strict";var VR=ke(),Uv={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new VR.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},i){if(e&&Uv.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?i.options.trueStr:i.options.falseStr}};Kv.boolTag=Uv});var jn=C(Yv=>{"use strict";function qR({format:e,minFractionDigits:t,tag:i,value:r}){if(typeof r=="bigint")return String(r);let n=typeof r=="number"?r:Number(r);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let a=Object.is(r,-0)?"-0":JSON.stringify(r);if(!e&&t&&(!i||i==="tag:yaml.org,2002:float")&&/^-?\d/.test(a)&&!a.includes("e")){let o=a.indexOf(".");o<0&&(o=a.length,a+=".");let s=t-(a.length-o-1);for(;s-- >0;)a+="0"}return a}Yv.stringifyNumber=qR});var Fd=C(kc=>{"use strict";var WR=ke(),Md=jn(),zR={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Md.stringifyNumber},JR={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():Md.stringifyNumber(e)}},GR={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new WR.Scalar(parseFloat(e)),i=e.indexOf(".");return i!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-i-1),t},stringify:Md.stringifyNumber};kc.float=GR;kc.floatExp=JR;kc.floatNaN=zR});var Vd=C(Ec=>{"use strict";var Xv=jn(),Sc=e=>typeof e=="bigint"||Number.isInteger(e),Bd=(e,t,i,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),i);function Qv(e,t,i){let{value:r}=e;return Sc(r)&&r>=0?i+r.toString(t):Xv.stringifyNumber(e)}var UR={identify:e=>Sc(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,i)=>Bd(e,2,8,i),stringify:e=>Qv(e,8,"0o")},KR={identify:Sc,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,i)=>Bd(e,0,10,i),stringify:Xv.stringifyNumber},YR={identify:e=>Sc(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,i)=>Bd(e,2,16,i),stringify:e=>Qv(e,16,"0x")};Ec.int=KR;Ec.intHex=YR;Ec.intOct=UR});var eg=C(Zv=>{"use strict";var XR=Tn(),QR=bc(),ZR=In(),eC=ro(),tC=Ld(),qd=Fd(),Wd=Vd(),iC=[XR.map,ZR.seq,eC.string,QR.nullTag,tC.boolTag,Wd.intOct,Wd.int,Wd.intHex,qd.floatNaN,qd.floatExp,qd.float];Zv.schema=iC});var rg=C(ig=>{"use strict";var rC=ke(),nC=Tn(),aC=In();function tg(e){return typeof e=="bigint"||Number.isInteger(e)}var Pc=({value:e})=>JSON.stringify(e),oC=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Pc},{identify:e=>e==null,createNode:()=>new rC.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Pc},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Pc},{identify:tg,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:i})=>i?BigInt(e):parseInt(e,10),stringify:({value:e})=>tg(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:Pc}],sC={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},cC=[nC.map,aC.seq].concat(oC,sC);ig.schema=cC});var Jd=C(ng=>{"use strict";var no=Js("buffer"),zd=ke(),lC=Za(),uC={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof no.Buffer=="function")return no.Buffer.from(e,"base64");if(typeof atob=="function"){let i=atob(e.replace(/[\n\r]/g,"")),r=new Uint8Array(i.length);for(let n=0;n<i.length;++n)r[n]=i.charCodeAt(n);return r}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:i},r,n,a){if(!i)return"";let o=i,s;if(typeof no.Buffer=="function")s=o instanceof no.Buffer?o.toString("base64"):no.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let l=0;l<o.length;++l)c+=String.fromCharCode(o[l]);s=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=zd.Scalar.BLOCK_LITERAL),t!==zd.Scalar.QUOTE_DOUBLE){let c=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),l=Math.ceil(s.length/c),u=new Array(l);for(let d=0,f=0;d<l;++d,f+=c)u[d]=s.substr(f,c);s=u.join(t===zd.Scalar.BLOCK_LITERAL?`
55
- `:" ")}return lC.stringifyString({comment:e,type:t,value:s},r,n,a)}};ng.binary=uC});var xc=C(Cc=>{"use strict";var Rc=G(),Gd=Xi(),dC=ke(),fC=er();function ag(e,t){if(Rc.isSeq(e))for(let i=0;i<e.items.length;++i){let r=e.items[i];if(!Rc.isPair(r)){if(Rc.isMap(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");let n=r.items[0]||new Gd.Pair(new dC.Scalar(null));if(r.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${r.commentBefore}
54
+ ${n}${h}`}else return`${f}${o}${d.join(" ")}${o}${h}`}function Nc({indent:e,options:{commentString:t}},i,r,n){if(r&&n&&(r=r.replace(/^\n+/,"")),r){let a=yc.indentComment(t(r),e);i.push(a.trimStart())}}Mv.stringifyCollection=AR});var ir=C(Bd=>{"use strict";var IR=Md(),jR=Dd(),$R=oc(),tr=G(),bc=er(),OR=ke();function so(e,t){let i=tr.isScalar(t)?t.value:t;for(let r of e)if(tr.isPair(r)&&(r.key===t||r.key===i||tr.isScalar(r.key)&&r.key.value===i))return r}var Fd=class extends $R.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(tr.MAP,t),this.items=[]}static from(t,i,r){let{keepUndefined:n,replacer:a}=r,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(i,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||n)&&o.items.push(bc.createPair(c,l,r))};if(i instanceof Map)for(let[c,l]of i)s(c,l);else if(i&&typeof i=="object")for(let c of Object.keys(i))s(c,i[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,i){let r;tr.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new bc.Pair(t,t?.value):r=new bc.Pair(t.key,t.value);let n=so(this.items,r.key),a=this.schema?.sortMapEntries;if(n){if(!i)throw new Error(`Key ${r.key} already set`);tr.isScalar(n.value)&&OR.isScalarValue(r.value)?n.value.value=r.value:n.value=r.value}else if(a){let o=this.items.findIndex(s=>a(r,s)<0);o===-1?this.items.push(r):this.items.splice(o,0,r)}else this.items.push(r)}delete(t){let i=so(this.items,t);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(t,i){let n=so(this.items,t)?.value;return(!i&&tr.isScalar(n)?n.value:n)??void 0}has(t){return!!so(this.items,t)}set(t,i){this.add(new bc.Pair(t,i),!0)}toJSON(t,i,r){let n=r?new r:i?.mapAsMap?new Map:{};i?.onCreate&&i.onCreate(n);for(let a of this.items)jR.addPairToJSMap(i,n,a);return n}toString(t,i,r){if(!t)return JSON.stringify(this);for(let n of this.items)if(!tr.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})),IR.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:i})}};Bd.YAMLMap=Fd;Bd.findPair=so});var Hn=C(Bv=>{"use strict";var HR=G(),Fv=ir(),DR={collection:"map",default:!0,nodeClass:Fv.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return HR.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,i)=>Fv.YAMLMap.from(e,t,i)};Bv.map=DR});var rr=C(Vv=>{"use strict";var LR=eo(),MR=Md(),FR=oc(),Sc=G(),BR=ke(),VR=Yi(),Vd=class extends FR.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Sc.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let i=kc(t);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(t,i){let r=kc(t);if(typeof r!="number")return;let n=this.items[r];return!i&&Sc.isScalar(n)?n.value:n}has(t){let i=kc(t);return typeof i=="number"&&i<this.items.length}set(t,i){let r=kc(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[r];Sc.isScalar(n)&&BR.isScalarValue(i)?n.value=i:this.items[r]=i}toJSON(t,i){let r=[];i?.onCreate&&i.onCreate(r);let n=0;for(let a of this.items)r.push(VR.toJS(a,String(n++),i));return r}toString(t,i,r){return t?MR.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:r,onComment:i}):JSON.stringify(this)}static from(t,i,r){let{replacer:n}=r,a=new this(t);if(i&&Symbol.iterator in Object(i)){let o=0;for(let s of i){if(typeof n=="function"){let c=i instanceof Set?s:String(o++);s=n.call(i,c,s)}a.items.push(LR.createNode(s,void 0,r))}}return a}};function kc(e){let t=Sc.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Vv.YAMLSeq=Vd});var Dn=C(Wv=>{"use strict";var qR=G(),qv=rr(),WR={collection:"seq",default:!0,nodeClass:qv.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return qR.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,i)=>qv.YAMLSeq.from(e,t,i)};Wv.seq=WR});var co=C(zv=>{"use strict";var zR=no(),JR={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,i,r){return t=Object.assign({actualString:!0},t),zR.stringifyString(e,t,i,r)}};zv.string=JR});var Ec=C(Uv=>{"use strict";var Jv=ke(),Gv={identify:e=>e==null,createNode:()=>new Jv.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Jv.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Gv.test.test(e)?e:t.options.nullStr};Uv.nullTag=Gv});var qd=C(Yv=>{"use strict";var GR=ke(),Kv={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new GR.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},i){if(e&&Kv.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?i.options.trueStr:i.options.falseStr}};Yv.boolTag=Kv});var Ln=C(Xv=>{"use strict";function UR({format:e,minFractionDigits:t,tag:i,value:r}){if(typeof r=="bigint")return String(r);let n=typeof r=="number"?r:Number(r);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let a=Object.is(r,-0)?"-0":JSON.stringify(r);if(!e&&t&&(!i||i==="tag:yaml.org,2002:float")&&/^-?\d/.test(a)&&!a.includes("e")){let o=a.indexOf(".");o<0&&(o=a.length,a+=".");let s=t-(a.length-o-1);for(;s-- >0;)a+="0"}return a}Xv.stringifyNumber=UR});var zd=C(Pc=>{"use strict";var KR=ke(),Wd=Ln(),YR={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Wd.stringifyNumber},XR={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():Wd.stringifyNumber(e)}},QR={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 KR.Scalar(parseFloat(e)),i=e.indexOf(".");return i!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-i-1),t},stringify:Wd.stringifyNumber};Pc.float=QR;Pc.floatExp=XR;Pc.floatNaN=YR});var Gd=C(Cc=>{"use strict";var Qv=Ln(),Rc=e=>typeof e=="bigint"||Number.isInteger(e),Jd=(e,t,i,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),i);function Zv(e,t,i){let{value:r}=e;return Rc(r)&&r>=0?i+r.toString(t):Qv.stringifyNumber(e)}var ZR={identify:e=>Rc(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,i)=>Jd(e,2,8,i),stringify:e=>Zv(e,8,"0o")},eC={identify:Rc,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,i)=>Jd(e,0,10,i),stringify:Qv.stringifyNumber},tC={identify:e=>Rc(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,i)=>Jd(e,2,16,i),stringify:e=>Zv(e,16,"0x")};Cc.int=eC;Cc.intHex=tC;Cc.intOct=ZR});var tg=C(eg=>{"use strict";var iC=Hn(),rC=Ec(),nC=Dn(),aC=co(),oC=qd(),Ud=zd(),Kd=Gd(),sC=[iC.map,nC.seq,aC.string,rC.nullTag,oC.boolTag,Kd.intOct,Kd.int,Kd.intHex,Ud.floatNaN,Ud.floatExp,Ud.float];eg.schema=sC});var ng=C(rg=>{"use strict";var cC=ke(),lC=Hn(),uC=Dn();function ig(e){return typeof e=="bigint"||Number.isInteger(e)}var xc=({value:e})=>JSON.stringify(e),dC=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:xc},{identify:e=>e==null,createNode:()=>new cC.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:xc},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:xc},{identify:ig,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:i})=>i?BigInt(e):parseInt(e,10),stringify:({value:e})=>ig(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:xc}],fC={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},hC=[lC.map,uC.seq].concat(dC,fC);rg.schema=hC});var Xd=C(ag=>{"use strict";var lo=Ks("buffer"),Yd=ke(),pC=no(),mC={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof lo.Buffer=="function")return lo.Buffer.from(e,"base64");if(typeof atob=="function"){let i=atob(e.replace(/[\n\r]/g,"")),r=new Uint8Array(i.length);for(let n=0;n<i.length;++n)r[n]=i.charCodeAt(n);return r}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:i},r,n,a){if(!i)return"";let o=i,s;if(typeof lo.Buffer=="function")s=o instanceof lo.Buffer?o.toString("base64"):lo.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=Yd.Scalar.BLOCK_LITERAL),t!==Yd.Scalar.QUOTE_DOUBLE){let c=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),l=Math.ceil(s.length/c),u=new Array(l);for(let d=0,f=0;d<l;++d,f+=c)u[d]=s.substr(f,c);s=u.join(t===Yd.Scalar.BLOCK_LITERAL?`
55
+ `:" ")}return pC.stringifyString({comment:e,type:t,value:s},r,n,a)}};ag.binary=mC});var Tc=C(_c=>{"use strict";var Ac=G(),Qd=er(),vC=ke(),gC=rr();function og(e,t){if(Ac.isSeq(e))for(let i=0;i<e.items.length;++i){let r=e.items[i];if(!Ac.isPair(r)){if(Ac.isMap(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");let n=r.items[0]||new Qd.Pair(new vC.Scalar(null));if(r.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${r.commentBefore}
56
56
  ${n.key.commentBefore}`:r.commentBefore),r.comment){let a=n.value??n.key;a.comment=a.comment?`${r.comment}
57
- ${a.comment}`:r.comment}r=n}e.items[i]=Rc.isPair(r)?r:new Gd.Pair(r)}}else t("Expected a sequence for this tag");return e}function og(e,t,i){let{replacer:r}=i,n=new fC.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof r=="function"&&(o=r.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(Gd.createPair(s,c,i))}return n}var hC={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:ag,createNode:og};Cc.createPairs=og;Cc.pairs=hC;Cc.resolvePairs=ag});var Yd=C(Kd=>{"use strict";var sg=G(),Ud=Gi(),ao=Zi(),pC=er(),cg=xc(),Ur=class e extends pC.YAMLSeq{constructor(){super(),this.add=ao.YAMLMap.prototype.add.bind(this),this.delete=ao.YAMLMap.prototype.delete.bind(this),this.get=ao.YAMLMap.prototype.get.bind(this),this.has=ao.YAMLMap.prototype.has.bind(this),this.set=ao.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,i){if(!i)return super.toJSON(t);let r=new Map;i?.onCreate&&i.onCreate(r);for(let n of this.items){let a,o;if(sg.isPair(n)?(a=Ud.toJS(n.key,"",i),o=Ud.toJS(n.value,a,i)):a=Ud.toJS(n,"",i),r.has(a))throw new Error("Ordered maps must not include duplicate keys");r.set(a,o)}return r}static from(t,i,r){let n=cg.createPairs(t,i,r),a=new this;return a.items=n.items,a}};Ur.tag="tag:yaml.org,2002:omap";var mC={collection:"seq",identify:e=>e instanceof Map,nodeClass:Ur,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=cg.resolvePairs(e,t),r=[];for(let{key:n}of i.items)sg.isScalar(n)&&(r.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new Ur,i)},createNode:(e,t,i)=>Ur.from(e,t,i)};Kd.YAMLOMap=Ur;Kd.omap=mC});var hg=C(Xd=>{"use strict";var lg=ke();function ug({value:e,source:t},i){return t&&(e?dg:fg).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var dg={identify:e=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new lg.Scalar(!0),stringify:ug},fg={identify:e=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new lg.Scalar(!1),stringify:ug};Xd.falseTag=fg;Xd.trueTag=dg});var pg=C(Ac=>{"use strict";var vC=ke(),Qd=jn(),gC={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Qd.stringifyNumber},wC={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():Qd.stringifyNumber(e)}},yC={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new vC.Scalar(parseFloat(e.replace(/_/g,""))),i=e.indexOf(".");if(i!==-1){let r=e.substring(i+1).replace(/_/g,"");r[r.length-1]==="0"&&(t.minFractionDigits=r.length)}return t},stringify:Qd.stringifyNumber};Ac.float=yC;Ac.floatExp=wC;Ac.floatNaN=gC});var vg=C(so=>{"use strict";var mg=jn(),oo=e=>typeof e=="bigint"||Number.isInteger(e);function _c(e,t,i,{intAsBigInt:r}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),r){switch(i){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return n==="-"?BigInt(-1)*o:o}let a=parseInt(e,i);return n==="-"?-1*a:a}function Zd(e,t,i){let{value:r}=e;if(oo(r)){let n=r.toString(t);return r<0?"-"+i+n.substr(1):i+n}return mg.stringifyNumber(e)}var NC={identify:oo,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>_c(e,2,2,i),stringify:e=>Zd(e,2,"0b")},bC={identify:oo,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>_c(e,1,8,i),stringify:e=>Zd(e,8,"0")},kC={identify:oo,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>_c(e,0,10,i),stringify:mg.stringifyNumber},SC={identify:oo,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>_c(e,2,16,i),stringify:e=>Zd(e,16,"0x")};so.int=kC;so.intBin=NC;so.intHex=SC;so.intOct=bC});var tf=C(ef=>{"use strict";var jc=G(),Tc=Xi(),Ic=Zi(),Kr=class e extends Ic.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;jc.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new Tc.Pair(t.key,null):i=new Tc.Pair(t,null),Ic.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let r=Ic.findPair(this.items,t);return!i&&jc.isPair(r)?jc.isScalar(r.key)?r.key.value:r.key:r}set(t,i){if(typeof i!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof i}`);let r=Ic.findPair(this.items,t);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new Tc.Pair(t))}toJSON(t,i){return super.toJSON(t,i,Set)}toString(t,i,r){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),i,r);throw new Error("Set items must all have null values")}static from(t,i,r){let{replacer:n}=r,a=new this(t);if(i&&Symbol.iterator in Object(i))for(let o of i)typeof n=="function"&&(o=n.call(i,o,o)),a.items.push(Tc.createPair(o,null,r));return a}};Kr.tag="tag:yaml.org,2002:set";var EC={collection:"map",identify:e=>e instanceof Set,nodeClass:Kr,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>Kr.from(e,t,i),resolve(e,t){if(jc.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Kr,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};ef.YAMLSet=Kr;ef.set=EC});var nf=C($c=>{"use strict";var PC=jn();function rf(e,t){let i=e[0],r=i==="-"||i==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=r.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return i==="-"?n(-1)*a:a}function gg(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return PC.stringifyNumber(e);let r="";t<0&&(r="-",t*=i(-1));let n=i(60),a=[t%n];return t<60?a.unshift(0):(t=(t-a[0])/n,a.unshift(t%n),t>=60&&(t=(t-a[0])/n,a.unshift(t))),r+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var RC={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:i})=>rf(e,i),stringify:gg},CC={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>rf(e,!1),stringify:gg},wg={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){let t=e.match(wg.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,i,r,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(i,r-1,n,a||0,o||0,s||0,c),u=t[8];if(u&&u!=="Z"){let d=rf(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};$c.floatTime=CC;$c.intTime=RC;$c.timestamp=wg});var bg=C(Ng=>{"use strict";var xC=Tn(),AC=bc(),_C=In(),TC=ro(),IC=Jd(),yg=hg(),af=pg(),Oc=vg(),jC=hc(),$C=Yd(),OC=xc(),HC=tf(),of=nf(),DC=[xC.map,_C.seq,TC.string,AC.nullTag,yg.trueTag,yg.falseTag,Oc.intBin,Oc.intOct,Oc.int,Oc.intHex,af.floatNaN,af.floatExp,af.float,IC.binary,jC.merge,$C.omap,OC.pairs,HC.set,of.intTime,of.floatTime,of.timestamp];Ng.schema=DC});var Tg=C(lf=>{"use strict";var Pg=Tn(),LC=bc(),Rg=In(),MC=ro(),FC=Ld(),sf=Fd(),cf=Vd(),BC=eg(),VC=rg(),Cg=Jd(),co=hc(),xg=Yd(),Ag=xc(),kg=bg(),_g=tf(),Hc=nf(),Sg=new Map([["core",BC.schema],["failsafe",[Pg.map,Rg.seq,MC.string]],["json",VC.schema],["yaml11",kg.schema],["yaml-1.1",kg.schema]]),Eg={binary:Cg.binary,bool:FC.boolTag,float:sf.float,floatExp:sf.floatExp,floatNaN:sf.floatNaN,floatTime:Hc.floatTime,int:cf.int,intHex:cf.intHex,intOct:cf.intOct,intTime:Hc.intTime,map:Pg.map,merge:co.merge,null:LC.nullTag,omap:xg.omap,pairs:Ag.pairs,seq:Rg.seq,set:_g.set,timestamp:Hc.timestamp},qC={"tag:yaml.org,2002:binary":Cg.binary,"tag:yaml.org,2002:merge":co.merge,"tag:yaml.org,2002:omap":xg.omap,"tag:yaml.org,2002:pairs":Ag.pairs,"tag:yaml.org,2002:set":_g.set,"tag:yaml.org,2002:timestamp":Hc.timestamp};function WC(e,t,i){let r=Sg.get(t);if(r&&!e)return i&&!r.includes(co.merge)?r.concat(co.merge):r.slice();let n=r;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(Sg.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${a} or define customTags array`)}if(Array.isArray(e))for(let a of e)n=n.concat(a);else typeof e=="function"&&(n=e(n.slice()));return i&&(n=n.concat(co.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Eg[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Eg).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}lf.coreKnownTags=qC;lf.getTags=WC});var ff=C(Ig=>{"use strict";var uf=G(),zC=Tn(),JC=In(),GC=ro(),Dc=Tg(),UC=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,df=class e{constructor({compat:t,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Dc.getTags(t,"compat"):t?Dc.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Dc.coreKnownTags:{},this.tags=Dc.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,uf.MAP,{value:zC.map}),Object.defineProperty(this,uf.SCALAR,{value:GC.string}),Object.defineProperty(this,uf.SEQ,{value:JC.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?UC:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Ig.Schema=df});var $g=C(jg=>{"use strict";var KC=G(),hf=eo(),lo=Ya();function YC(e,t){let i=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(i.push(c),r=!0):e.directives.docStart&&(r=!0)}r&&i.push("---");let n=hf.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(lo.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(KC.isNode(e.contents)){if(e.contents.spaceBefore&&r&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(lo.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=hf.stringify(e.contents,n,()=>s=null,c);s&&(l+=lo.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(hf.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
58
- `)?(i.push("..."),i.push(lo.indentComment(c,""))):i.push(`... ${c}`)}else i.push("...");else{let c=e.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&i[i.length-1]!==""&&i.push(""),i.push(lo.indentComment(a(c),"")))}return i.join(`
57
+ ${a.comment}`:r.comment}r=n}e.items[i]=Ac.isPair(r)?r:new Qd.Pair(r)}}else t("Expected a sequence for this tag");return e}function sg(e,t,i){let{replacer:r}=i,n=new gC.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof r=="function"&&(o=r.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(Qd.createPair(s,c,i))}return n}var wC={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:og,createNode:sg};_c.createPairs=sg;_c.pairs=wC;_c.resolvePairs=og});var tf=C(ef=>{"use strict";var cg=G(),Zd=Yi(),uo=ir(),yC=rr(),lg=Tc(),Yr=class e extends yC.YAMLSeq{constructor(){super(),this.add=uo.YAMLMap.prototype.add.bind(this),this.delete=uo.YAMLMap.prototype.delete.bind(this),this.get=uo.YAMLMap.prototype.get.bind(this),this.has=uo.YAMLMap.prototype.has.bind(this),this.set=uo.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,i){if(!i)return super.toJSON(t);let r=new Map;i?.onCreate&&i.onCreate(r);for(let n of this.items){let a,o;if(cg.isPair(n)?(a=Zd.toJS(n.key,"",i),o=Zd.toJS(n.value,a,i)):a=Zd.toJS(n,"",i),r.has(a))throw new Error("Ordered maps must not include duplicate keys");r.set(a,o)}return r}static from(t,i,r){let n=lg.createPairs(t,i,r),a=new this;return a.items=n.items,a}};Yr.tag="tag:yaml.org,2002:omap";var NC={collection:"seq",identify:e=>e instanceof Map,nodeClass:Yr,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=lg.resolvePairs(e,t),r=[];for(let{key:n}of i.items)cg.isScalar(n)&&(r.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new Yr,i)},createNode:(e,t,i)=>Yr.from(e,t,i)};ef.YAMLOMap=Yr;ef.omap=NC});var pg=C(rf=>{"use strict";var ug=ke();function dg({value:e,source:t},i){return t&&(e?fg:hg).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var fg={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 ug.Scalar(!0),stringify:dg},hg={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 ug.Scalar(!1),stringify:dg};rf.falseTag=hg;rf.trueTag=fg});var mg=C(Ic=>{"use strict";var bC=ke(),nf=Ln(),kC={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:nf.stringifyNumber},SC={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():nf.stringifyNumber(e)}},EC={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 bC.Scalar(parseFloat(e.replace(/_/g,""))),i=e.indexOf(".");if(i!==-1){let r=e.substring(i+1).replace(/_/g,"");r[r.length-1]==="0"&&(t.minFractionDigits=r.length)}return t},stringify:nf.stringifyNumber};Ic.float=EC;Ic.floatExp=SC;Ic.floatNaN=kC});var gg=C(ho=>{"use strict";var vg=Ln(),fo=e=>typeof e=="bigint"||Number.isInteger(e);function jc(e,t,i,{intAsBigInt:r}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),r){switch(i){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return n==="-"?BigInt(-1)*o:o}let a=parseInt(e,i);return n==="-"?-1*a:a}function af(e,t,i){let{value:r}=e;if(fo(r)){let n=r.toString(t);return r<0?"-"+i+n.substr(1):i+n}return vg.stringifyNumber(e)}var PC={identify:fo,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>jc(e,2,2,i),stringify:e=>af(e,2,"0b")},RC={identify:fo,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>jc(e,1,8,i),stringify:e=>af(e,8,"0")},CC={identify:fo,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>jc(e,0,10,i),stringify:vg.stringifyNumber},xC={identify:fo,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>jc(e,2,16,i),stringify:e=>af(e,16,"0x")};ho.int=CC;ho.intBin=PC;ho.intHex=xC;ho.intOct=RC});var sf=C(of=>{"use strict";var Hc=G(),$c=er(),Oc=ir(),Xr=class e extends Oc.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;Hc.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new $c.Pair(t.key,null):i=new $c.Pair(t,null),Oc.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let r=Oc.findPair(this.items,t);return!i&&Hc.isPair(r)?Hc.isScalar(r.key)?r.key.value:r.key:r}set(t,i){if(typeof i!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof i}`);let r=Oc.findPair(this.items,t);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new $c.Pair(t))}toJSON(t,i){return super.toJSON(t,i,Set)}toString(t,i,r){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),i,r);throw new Error("Set items must all have null values")}static from(t,i,r){let{replacer:n}=r,a=new this(t);if(i&&Symbol.iterator in Object(i))for(let o of i)typeof n=="function"&&(o=n.call(i,o,o)),a.items.push($c.createPair(o,null,r));return a}};Xr.tag="tag:yaml.org,2002:set";var AC={collection:"map",identify:e=>e instanceof Set,nodeClass:Xr,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>Xr.from(e,t,i),resolve(e,t){if(Hc.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Xr,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};of.YAMLSet=Xr;of.set=AC});var lf=C(Dc=>{"use strict";var _C=Ln();function cf(e,t){let i=e[0],r=i==="-"||i==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=r.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return i==="-"?n(-1)*a:a}function wg(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return _C.stringifyNumber(e);let r="";t<0&&(r="-",t*=i(-1));let n=i(60),a=[t%n];return t<60?a.unshift(0):(t=(t-a[0])/n,a.unshift(t%n),t>=60&&(t=(t-a[0])/n,a.unshift(t))),r+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var TC={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:i})=>cf(e,i),stringify:wg},IC={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=>cf(e,!1),stringify:wg},yg={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(yg.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,i,r,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(i,r-1,n,a||0,o||0,s||0,c),u=t[8];if(u&&u!=="Z"){let d=cf(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Dc.floatTime=IC;Dc.intTime=TC;Dc.timestamp=yg});var kg=C(bg=>{"use strict";var jC=Hn(),$C=Ec(),OC=Dn(),HC=co(),DC=Xd(),Ng=pg(),uf=mg(),Lc=gg(),LC=vc(),MC=tf(),FC=Tc(),BC=sf(),df=lf(),VC=[jC.map,OC.seq,HC.string,$C.nullTag,Ng.trueTag,Ng.falseTag,Lc.intBin,Lc.intOct,Lc.int,Lc.intHex,uf.floatNaN,uf.floatExp,uf.float,DC.binary,LC.merge,MC.omap,FC.pairs,BC.set,df.intTime,df.floatTime,df.timestamp];bg.schema=VC});var Ig=C(pf=>{"use strict";var Rg=Hn(),qC=Ec(),Cg=Dn(),WC=co(),zC=qd(),ff=zd(),hf=Gd(),JC=tg(),GC=ng(),xg=Xd(),po=vc(),Ag=tf(),_g=Tc(),Sg=kg(),Tg=sf(),Mc=lf(),Eg=new Map([["core",JC.schema],["failsafe",[Rg.map,Cg.seq,WC.string]],["json",GC.schema],["yaml11",Sg.schema],["yaml-1.1",Sg.schema]]),Pg={binary:xg.binary,bool:zC.boolTag,float:ff.float,floatExp:ff.floatExp,floatNaN:ff.floatNaN,floatTime:Mc.floatTime,int:hf.int,intHex:hf.intHex,intOct:hf.intOct,intTime:Mc.intTime,map:Rg.map,merge:po.merge,null:qC.nullTag,omap:Ag.omap,pairs:_g.pairs,seq:Cg.seq,set:Tg.set,timestamp:Mc.timestamp},UC={"tag:yaml.org,2002:binary":xg.binary,"tag:yaml.org,2002:merge":po.merge,"tag:yaml.org,2002:omap":Ag.omap,"tag:yaml.org,2002:pairs":_g.pairs,"tag:yaml.org,2002:set":Tg.set,"tag:yaml.org,2002:timestamp":Mc.timestamp};function KC(e,t,i){let r=Eg.get(t);if(r&&!e)return i&&!r.includes(po.merge)?r.concat(po.merge):r.slice();let n=r;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(Eg.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${a} or define customTags array`)}if(Array.isArray(e))for(let a of e)n=n.concat(a);else typeof e=="function"&&(n=e(n.slice()));return i&&(n=n.concat(po.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Pg[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Pg).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}pf.coreKnownTags=UC;pf.getTags=KC});var gf=C(jg=>{"use strict";var mf=G(),YC=Hn(),XC=Dn(),QC=co(),Fc=Ig(),ZC=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,vf=class e{constructor({compat:t,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Fc.getTags(t,"compat"):t?Fc.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Fc.coreKnownTags:{},this.tags=Fc.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,mf.MAP,{value:YC.map}),Object.defineProperty(this,mf.SCALAR,{value:QC.string}),Object.defineProperty(this,mf.SEQ,{value:XC.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?ZC:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};jg.Schema=vf});var Og=C($g=>{"use strict";var ex=G(),wf=ao(),mo=to();function tx(e,t){let i=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(i.push(c),r=!0):e.directives.docStart&&(r=!0)}r&&i.push("---");let n=wf.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(mo.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(ex.isNode(e.contents)){if(e.contents.spaceBefore&&r&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(mo.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=wf.stringify(e.contents,n,()=>s=null,c);s&&(l+=mo.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(wf.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
58
+ `)?(i.push("..."),i.push(mo.indentComment(c,""))):i.push(`... ${c}`)}else i.push("...");else{let c=e.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&i[i.length-1]!==""&&i.push(""),i.push(mo.indentComment(a(c),"")))}return i.join(`
59
59
  `)+`
60
- `}jg.stringifyDocument=YC});var uo=C(Og=>{"use strict";var XC=Ua(),$n=rc(),Rt=G(),QC=Xi(),ZC=Gi(),ex=ff(),tx=$g(),pf=Zs(),ix=gd(),rx=Ka(),mf=vd(),vf=class e{constructor(t,i,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Rt.NODE_TYPE,{value:Rt.DOC});let n=null;typeof i=="function"||Array.isArray(i)?n=i:r===void 0&&i&&(r=i,i=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=a;let{version:o}=a;r?._directives?(this.directives=r._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new mf.Directives({version:o}),this.setSchema(o,r),this.contents=t===void 0?null:this.createNode(t,n,r)}clone(){let t=Object.create(e.prototype,{[Rt.NODE_TYPE]:{value:Rt.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=Rt.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){On(this.contents)&&this.contents.add(t)}addIn(t,i){On(this.contents)&&this.contents.addIn(t,i)}createAlias(t,i){if(!t.anchor){let r=pf.anchorNames(this);t.anchor=!i||r.has(i)?pf.findNewAnchor(i||"a",r):i}return new XC.Alias(t.anchor)}createNode(t,i,r){let n;if(typeof i=="function")t=i.call({"":t},"",t),n=i;else if(Array.isArray(i)){let p=g=>typeof g=="number"||g instanceof String||g instanceof Number,b=i.filter(p).map(String);b.length>0&&(i=i.concat(b)),n=i}else r===void 0&&i&&(r=i,i=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:u}=r??{},{onAnchor:d,setAnchors:f,sourceObjects:h}=pf.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:h},m=rx.createNode(t,u,v);return s&&Rt.isCollection(m)&&(m.flow=!0),f(),m}createPair(t,i,r={}){let n=this.createNode(t,null,r),a=this.createNode(i,null,r);return new QC.Pair(n,a)}delete(t){return On(this.contents)?this.contents.delete(t):!1}deleteIn(t){return $n.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):On(this.contents)?this.contents.deleteIn(t):!1}get(t,i){return Rt.isCollection(this.contents)?this.contents.get(t,i):void 0}getIn(t,i){return $n.isEmptyPath(t)?!i&&Rt.isScalar(this.contents)?this.contents.value:this.contents:Rt.isCollection(this.contents)?this.contents.getIn(t,i):void 0}has(t){return Rt.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return $n.isEmptyPath(t)?this.contents!==void 0:Rt.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,i){this.contents==null?this.contents=$n.collectionFromPath(this.schema,[t],i):On(this.contents)&&this.contents.set(t,i)}setIn(t,i){$n.isEmptyPath(t)?this.contents=i:this.contents==null?this.contents=$n.collectionFromPath(this.schema,Array.from(t),i):On(this.contents)&&this.contents.setIn(t,i)}setSchema(t,i={}){typeof t=="number"&&(t=String(t));let r;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new mf.Directives({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new mf.Directives({version:t}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let n=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${n}`)}}if(i.schema instanceof Object)this.schema=i.schema;else if(r)this.schema=new ex.Schema(Object.assign(r,i));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:i,mapAsMap:r,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=ZC.toJS(this.contents,i??"",s);if(typeof a=="function")for(let{count:l,res:u}of s.anchors.values())a(u,l);return typeof o=="function"?ix.applyReviver(o,{"":c},"",c):c}toJSON(t,i){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:i})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let i=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${i}`)}return tx.stringifyDocument(this,t)}};function On(e){if(Rt.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Og.Document=vf});var po=C(ho=>{"use strict";var fo=class extends Error{constructor(t,i,r,n){super(),this.name=t,this.code=r,this.message=n,this.pos=i}},gf=class extends fo{constructor(t,i,r){super("YAMLParseError",t,i,r)}},wf=class extends fo{constructor(t,i,r){super("YAMLWarning",t,i,r)}},nx=(e,t)=>i=>{if(i.pos[0]===-1)return;i.linePos=i.pos.map(s=>t.linePos(s));let{line:r,col:n}=i.linePos[0];i.message+=` at line ${r}, column ${n}`;let a=n-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,"");if(a>=60&&o.length>80){let s=Math.min(a-39,o.length-79);o="…"+o.substring(s),a-=s-1}if(o.length>80&&(o=o.substring(0,79)+"…"),r>1&&/^ *$/.test(o.substring(0,a))){let s=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);s.length>80&&(s=s.substring(0,79)+`…
60
+ `}$g.stringifyDocument=tx});var vo=C(Hg=>{"use strict";var ix=Za(),Mn=oc(),Rt=G(),rx=er(),nx=Yi(),ax=gf(),ox=Og(),yf=ic(),sx=kd(),cx=eo(),Nf=bd(),bf=class e{constructor(t,i,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Rt.NODE_TYPE,{value:Rt.DOC});let n=null;typeof i=="function"||Array.isArray(i)?n=i:r===void 0&&i&&(r=i,i=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=a;let{version:o}=a;r?._directives?(this.directives=r._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new Nf.Directives({version:o}),this.setSchema(o,r),this.contents=t===void 0?null:this.createNode(t,n,r)}clone(){let t=Object.create(e.prototype,{[Rt.NODE_TYPE]:{value:Rt.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=Rt.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){Fn(this.contents)&&this.contents.add(t)}addIn(t,i){Fn(this.contents)&&this.contents.addIn(t,i)}createAlias(t,i){if(!t.anchor){let r=yf.anchorNames(this);t.anchor=!i||r.has(i)?yf.findNewAnchor(i||"a",r):i}return new ix.Alias(t.anchor)}createNode(t,i,r){let n;if(typeof i=="function")t=i.call({"":t},"",t),n=i;else if(Array.isArray(i)){let p=g=>typeof g=="number"||g instanceof String||g instanceof Number,b=i.filter(p).map(String);b.length>0&&(i=i.concat(b)),n=i}else r===void 0&&i&&(r=i,i=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:u}=r??{},{onAnchor:d,setAnchors:f,sourceObjects:h}=yf.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:h},m=cx.createNode(t,u,v);return s&&Rt.isCollection(m)&&(m.flow=!0),f(),m}createPair(t,i,r={}){let n=this.createNode(t,null,r),a=this.createNode(i,null,r);return new rx.Pair(n,a)}delete(t){return Fn(this.contents)?this.contents.delete(t):!1}deleteIn(t){return Mn.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Fn(this.contents)?this.contents.deleteIn(t):!1}get(t,i){return Rt.isCollection(this.contents)?this.contents.get(t,i):void 0}getIn(t,i){return Mn.isEmptyPath(t)?!i&&Rt.isScalar(this.contents)?this.contents.value:this.contents:Rt.isCollection(this.contents)?this.contents.getIn(t,i):void 0}has(t){return Rt.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return Mn.isEmptyPath(t)?this.contents!==void 0:Rt.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,i){this.contents==null?this.contents=Mn.collectionFromPath(this.schema,[t],i):Fn(this.contents)&&this.contents.set(t,i)}setIn(t,i){Mn.isEmptyPath(t)?this.contents=i:this.contents==null?this.contents=Mn.collectionFromPath(this.schema,Array.from(t),i):Fn(this.contents)&&this.contents.setIn(t,i)}setSchema(t,i={}){typeof t=="number"&&(t=String(t));let r;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Nf.Directives({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new Nf.Directives({version:t}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let n=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${n}`)}}if(i.schema instanceof Object)this.schema=i.schema;else if(r)this.schema=new ax.Schema(Object.assign(r,i));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:i,mapAsMap:r,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=nx.toJS(this.contents,i??"",s);if(typeof a=="function")for(let{count:l,res:u}of s.anchors.values())a(u,l);return typeof o=="function"?sx.applyReviver(o,{"":c},"",c):c}toJSON(t,i){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:i})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let i=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${i}`)}return ox.stringifyDocument(this,t)}};function Fn(e){if(Rt.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Hg.Document=bf});var yo=C(wo=>{"use strict";var go=class extends Error{constructor(t,i,r,n){super(),this.name=t,this.code=r,this.message=n,this.pos=i}},kf=class extends go{constructor(t,i,r){super("YAMLParseError",t,i,r)}},Sf=class extends go{constructor(t,i,r){super("YAMLWarning",t,i,r)}},lx=(e,t)=>i=>{if(i.pos[0]===-1)return;i.linePos=i.pos.map(s=>t.linePos(s));let{line:r,col:n}=i.linePos[0];i.message+=` at line ${r}, column ${n}`;let a=n-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,"");if(a>=60&&o.length>80){let s=Math.min(a-39,o.length-79);o="…"+o.substring(s),a-=s-1}if(o.length>80&&(o=o.substring(0,79)+"…"),r>1&&/^ *$/.test(o.substring(0,a))){let s=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);s.length>80&&(s=s.substring(0,79)+`…
61
61
  `),o=s+o}if(/[^ ]/.test(o)){let s=1,c=i.linePos[1];c?.line===r&&c.col>n&&(s=Math.max(1,Math.min(c.col-n,80-a)));let l=" ".repeat(a)+"^".repeat(s);i.message+=`:
62
62
 
63
63
  ${o}
64
64
  ${l}
65
- `}};ho.YAMLError=fo;ho.YAMLParseError=gf;ho.YAMLWarning=wf;ho.prettifyError=nx});var mo=C(Hg=>{"use strict";function ax(e,{flow:t,indicator:i,next:r,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d="",f="",h=!1,v=!1,m=null,p=null,b=null,g=null,y=null,E=null,k=null;for(let N of e)switch(v&&(N.type!=="space"&&N.type!=="newline"&&N.type!=="comma"&&a(N.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),m&&(l&&N.type!=="comment"&&N.type!=="newline"&&a(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),N.type){case"space":!t&&(i!=="doc-start"||r?.type!=="flow-collection")&&N.source.includes(" ")&&(m=N),u=!0;break;case"comment":{u||a(N,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let w=N.source.substring(1)||" ";d?d+=f+w:d=w,f="",l=!1;break}case"newline":l?d?d+=N.source:(!E||i!=="seq-item-ind")&&(c=!0):f+=N.source,l=!0,h=!0,(p||b)&&(g=N),u=!0;break;case"anchor":p&&a(N,"MULTIPLE_ANCHORS","A node can have at most one anchor"),N.source.endsWith(":")&&a(N.offset+N.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),p=N,k??(k=N.offset),l=!1,u=!1,v=!0;break;case"tag":{b&&a(N,"MULTIPLE_TAGS","A node can have at most one tag"),b=N,k??(k=N.offset),l=!1,u=!1,v=!0;break}case i:(p||b)&&a(N,"BAD_PROP_ORDER",`Anchors and tags must be after the ${N.source} indicator`),E&&a(N,"UNEXPECTED_TOKEN",`Unexpected ${N.source} in ${t??"collection"}`),E=N,l=i==="seq-item-ind"||i==="explicit-key-ind",u=!1;break;case"comma":if(t){y&&a(N,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),y=N,l=!1,u=!1;break}default:a(N,"UNEXPECTED_TOKEN",`Unexpected ${N.type} token`),l=!1,u=!1}let S=e[e.length-1],R=S?S.offset+S.source.length:n;return v&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&a(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m&&(l&&m.indent<=o||r?.type==="block-map"||r?.type==="block-seq")&&a(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:y,found:E,spaceBefore:c,comment:d,hasNewline:h,anchor:p,tag:b,newlineAfterProp:g,end:R,start:k??R}}Hg.resolveProps=ax});var Lc=C(Dg=>{"use strict";function yf(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
66
- `))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let i of t.start)if(i.type==="newline")return!0;if(t.sep){for(let i of t.sep)if(i.type==="newline")return!0}if(yf(t.key)||yf(t.value))return!0}return!1;default:return!0}}Dg.containsNewline=yf});var Nf=C(Lg=>{"use strict";var ox=Lc();function sx(e,t,i){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&ox.containsNewline(t)&&i(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Lg.flowIndentCheck=sx});var bf=C(Fg=>{"use strict";var Mg=G();function cx(e,t,i){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let n=typeof r=="function"?r:(a,o)=>a===o||Mg.isScalar(a)&&Mg.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,i))}Fg.mapIncludes=cx});var Jg=C(zg=>{"use strict";var Bg=Xi(),lx=Zi(),Vg=mo(),ux=Lc(),qg=Nf(),dx=bf(),Wg="All mapping items must start at the same column";function fx({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??lx.YAMLMap,s=new o(i.schema);i.atRoot&&(i.atRoot=!1);let c=r.offset,l=null;for(let u of r.items){let{start:d,key:f,sep:h,value:v}=u,m=Vg.resolveProps(d,{indicator:"explicit-key-ind",next:f??h?.[0],offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0}),p=!m.found;if(p){if(f&&(f.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==r.indent&&n(c,"BAD_INDENT",Wg)),!m.anchor&&!m.tag&&!h){l=m.end,m.comment&&(s.comment?s.comment+=`
67
- `+m.comment:s.comment=m.comment);continue}(m.newlineAfterProp||ux.containsNewline(f))&&n(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else m.found?.indent!==r.indent&&n(c,"BAD_INDENT",Wg);i.atKey=!0;let b=m.end,g=f?e(i,f,m,n):t(i,b,d,null,m,n);i.schema.compat&&qg.flowIndentCheck(r.indent,f,n),i.atKey=!1,dx.mapIncludes(i,s.items,g)&&n(b,"DUPLICATE_KEY","Map keys must be unique");let y=Vg.resolveProps(h??[],{indicator:"map-value-ind",next:v,offset:g.range[2],onError:n,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=y.end,y.found){p&&(v?.type==="block-map"&&!y.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&m.start<y.found.offset-1024&&n(g.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let E=v?e(i,v,y,n):t(i,c,h,null,y,n);i.schema.compat&&qg.flowIndentCheck(r.indent,v,n),c=E.range[2];let k=new Bg.Pair(g,E);i.options.keepSourceTokens&&(k.srcToken=u),s.items.push(k)}else{p&&n(g.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),y.comment&&(g.comment?g.comment+=`
68
- `+y.comment:g.comment=y.comment);let E=new Bg.Pair(g);i.options.keepSourceTokens&&(E.srcToken=u),s.items.push(E)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[r.offset,c,l??c],s}zg.resolveBlockMap=fx});var Ug=C(Gg=>{"use strict";var hx=er(),px=mo(),mx=Nf();function vx({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??hx.YAMLSeq,s=new o(i.schema);i.atRoot&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let c=r.offset,l=null;for(let{start:u,value:d}of r.items){let f=px.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||d)d?.type==="block-seq"?n(f.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(s.comment=f.comment);continue}let h=d?e(i,d,f,n):t(i,f.end,u,null,f,n);i.schema.compat&&mx.flowIndentCheck(r.indent,d,n),c=h.range[2],s.items.push(h)}return s.range=[r.offset,c,l??c],s}Gg.resolveBlockSeq=vx});var Hn=C(Kg=>{"use strict";function gx(e,t,i,r){let n="";if(e){let a=!1,o="";for(let s of e){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{i&&!a&&r(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";n?n+=o+u:n=u,o="";break}case"newline":n&&(o+=c),a=!0;break;default:r(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:n,offset:t}}Kg.resolveEnd=gx});var Zg=C(Qg=>{"use strict";var wx=G(),yx=Xi(),Yg=Zi(),Nx=er(),bx=Hn(),Xg=mo(),kx=Lc(),Sx=bf(),kf="Block collections are not allowed within flow collections",Sf=e=>e&&(e.type==="block-map"||e.type==="block-seq");function Ex({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=r.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Yg.YAMLMap:Nx.YAMLSeq),l=new c(i.schema);l.flow=!0;let u=i.atRoot;u&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let d=r.offset+r.start.source.length;for(let p=0;p<r.items.length;++p){let b=r.items[p],{start:g,key:y,sep:E,value:k}=b,S=Xg.resolveProps(g,{flow:s,indicator:"explicit-key-ind",next:y??E?.[0],offset:d,onError:n,parentIndent:r.indent,startOnNewline:!1});if(!S.found){if(!S.anchor&&!S.tag&&!E&&!k){p===0&&S.comma?n(S.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):p<r.items.length-1&&n(S.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),S.comment&&(l.comment?l.comment+=`
69
- `+S.comment:l.comment=S.comment),d=S.end;continue}!o&&i.options.strict&&kx.containsNewline(y)&&n(y,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(p===0)S.comma&&n(S.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(S.comma||n(S.start,"MISSING_CHAR",`Missing , between ${s} items`),S.comment){let R="";e:for(let N of g)switch(N.type){case"comma":case"space":break;case"comment":R=N.source.substring(1);break e;default:break e}if(R){let N=l.items[l.items.length-1];wx.isPair(N)&&(N=N.value??N.key),N.comment?N.comment+=`
70
- `+R:N.comment=R,S.comment=S.comment.substring(R.length+1)}}if(!o&&!E&&!S.found){let R=k?e(i,k,S,n):t(i,S.end,E,null,S,n);l.items.push(R),d=R.range[2],Sf(k)&&n(R.range,"BLOCK_IN_FLOW",kf)}else{i.atKey=!0;let R=S.end,N=y?e(i,y,S,n):t(i,R,g,null,S,n);Sf(y)&&n(N.range,"BLOCK_IN_FLOW",kf),i.atKey=!1;let w=Xg.resolveProps(E??[],{flow:s,indicator:"map-value-ind",next:k,offset:N.range[2],onError:n,parentIndent:r.indent,startOnNewline:!1});if(w.found){if(!o&&!S.found&&i.options.strict){if(E)for(let $ of E){if($===w.found)break;if($.type==="newline"){n($,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}S.start<w.found.offset-1024&&n(w.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else k&&("source"in k&&k.source?.[0]===":"?n(k,"MISSING_CHAR",`Missing space after : in ${s}`):n(w.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let P=k?e(i,k,w,n):w.found?t(i,w.end,E,null,w,n):null;P?Sf(k)&&n(P.range,"BLOCK_IN_FLOW",kf):w.comment&&(N.comment?N.comment+=`
71
- `+w.comment:N.comment=w.comment);let F=new yx.Pair(N,P);if(i.options.keepSourceTokens&&(F.srcToken=b),o){let $=l;Sx.mapIncludes(i,$.items,N)&&n(R,"DUPLICATE_KEY","Map keys must be unique"),$.items.push(F)}else{let $=new Yg.YAMLMap(i.schema);$.flow=!0,$.items.push(F);let Fe=(P??N).range;$.range=[N.range[0],Fe[1],Fe[2]],l.items.push($)}d=P?P.range[2]:w.end}}let f=o?"}":"]",[h,...v]=r.end,m=d;if(h?.source===f)m=h.offset+h.source.length;else{let p=s[0].toUpperCase()+s.substring(1),b=u?`${p} must end with a ${f}`:`${p} in block collection must be sufficiently indented and end with a ${f}`;n(d,u?"MISSING_CHAR":"BAD_INDENT",b),h&&h.source.length!==1&&v.unshift(h)}if(v.length>0){let p=bx.resolveEnd(v,m,i.options.strict,n);p.comment&&(l.comment?l.comment+=`
72
- `+p.comment:l.comment=p.comment),l.range=[r.offset,m,p.offset]}else l.range=[r.offset,m,m];return l}Qg.resolveFlowCollection=Ex});var tw=C(ew=>{"use strict";var Px=G(),Rx=ke(),Cx=Zi(),xx=er(),Ax=Jg(),_x=Ug(),Tx=Zg();function Ef(e,t,i,r,n,a){let o=i.type==="block-map"?Ax.resolveBlockMap(e,t,i,r,a):i.type==="block-seq"?_x.resolveBlockSeq(e,t,i,r,a):Tx.resolveFlowCollection(e,t,i,r,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function Ix(e,t,i,r,n){let a=r.tag,o=a?t.directives.tagName(a.source,f=>n(a,"TAG_RESOLVE_FAILED",f)):null;if(i.type==="block-seq"){let{anchor:f,newlineAfterProp:h}=r,v=f&&a?f.offset>a.offset?f:a:f??a;v&&(!h||h.offset<v.offset)&&n(v,"MISSING_CHAR","Missing newline after block sequence props")}let s=i.type==="block-map"?"map":i.type==="block-seq"?"seq":i.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===Cx.YAMLMap.tagName&&s==="map"||o===xx.YAMLSeq.tagName&&s==="seq")return Ef(e,t,i,n,o);let c=t.schema.tags.find(f=>f.tag===o&&f.collection===s);if(!c){let f=t.schema.knownTags[o];if(f?.collection===s)t.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?n(a,"BAD_COLLECTION_TYPE",`${f.tag} used for ${s} collection, but expects ${f.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Ef(e,t,i,n,o)}let l=Ef(e,t,i,n,o,c),u=c.resolve?.(l,f=>n(a,"TAG_RESOLVE_FAILED",f),t.options)??l,d=Px.isNode(u)?u:new Rx.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}ew.composeCollection=Ix});var Rf=C(iw=>{"use strict";var Pf=ke();function jx(e,t,i){let r=t.offset,n=$x(t,e.options.strict,i);if(!n)return{value:"",type:null,comment:"",range:[r,r,r]};let a=n.mode===">"?Pf.Scalar.BLOCK_FOLDED:Pf.Scalar.BLOCK_LITERAL,o=t.source?Ox(t.source):[],s=o.length;for(let m=o.length-1;m>=0;--m){let p=o[m][1];if(p===""||p==="\r")s=m;else break}if(s===0){let m=n.chomp==="+"&&o.length>0?`
65
+ `}};wo.YAMLError=go;wo.YAMLParseError=kf;wo.YAMLWarning=Sf;wo.prettifyError=lx});var No=C(Dg=>{"use strict";function ux(e,{flow:t,indicator:i,next:r,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d="",f="",h=!1,v=!1,m=null,p=null,b=null,g=null,y=null,E=null,k=null;for(let N of e)switch(v&&(N.type!=="space"&&N.type!=="newline"&&N.type!=="comma"&&a(N.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),m&&(l&&N.type!=="comment"&&N.type!=="newline"&&a(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),N.type){case"space":!t&&(i!=="doc-start"||r?.type!=="flow-collection")&&N.source.includes(" ")&&(m=N),u=!0;break;case"comment":{u||a(N,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let w=N.source.substring(1)||" ";d?d+=f+w:d=w,f="",l=!1;break}case"newline":l?d?d+=N.source:(!E||i!=="seq-item-ind")&&(c=!0):f+=N.source,l=!0,h=!0,(p||b)&&(g=N),u=!0;break;case"anchor":p&&a(N,"MULTIPLE_ANCHORS","A node can have at most one anchor"),N.source.endsWith(":")&&a(N.offset+N.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),p=N,k??(k=N.offset),l=!1,u=!1,v=!0;break;case"tag":{b&&a(N,"MULTIPLE_TAGS","A node can have at most one tag"),b=N,k??(k=N.offset),l=!1,u=!1,v=!0;break}case i:(p||b)&&a(N,"BAD_PROP_ORDER",`Anchors and tags must be after the ${N.source} indicator`),E&&a(N,"UNEXPECTED_TOKEN",`Unexpected ${N.source} in ${t??"collection"}`),E=N,l=i==="seq-item-ind"||i==="explicit-key-ind",u=!1;break;case"comma":if(t){y&&a(N,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),y=N,l=!1,u=!1;break}default:a(N,"UNEXPECTED_TOKEN",`Unexpected ${N.type} token`),l=!1,u=!1}let S=e[e.length-1],R=S?S.offset+S.source.length:n;return v&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&a(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m&&(l&&m.indent<=o||r?.type==="block-map"||r?.type==="block-seq")&&a(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:y,found:E,spaceBefore:c,comment:d,hasNewline:h,anchor:p,tag:b,newlineAfterProp:g,end:R,start:k??R}}Dg.resolveProps=ux});var Bc=C(Lg=>{"use strict";function Ef(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
66
+ `))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let i of t.start)if(i.type==="newline")return!0;if(t.sep){for(let i of t.sep)if(i.type==="newline")return!0}if(Ef(t.key)||Ef(t.value))return!0}return!1;default:return!0}}Lg.containsNewline=Ef});var Pf=C(Mg=>{"use strict";var dx=Bc();function fx(e,t,i){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&dx.containsNewline(t)&&i(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Mg.flowIndentCheck=fx});var Rf=C(Bg=>{"use strict";var Fg=G();function hx(e,t,i){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let n=typeof r=="function"?r:(a,o)=>a===o||Fg.isScalar(a)&&Fg.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,i))}Bg.mapIncludes=hx});var Gg=C(Jg=>{"use strict";var Vg=er(),px=ir(),qg=No(),mx=Bc(),Wg=Pf(),vx=Rf(),zg="All mapping items must start at the same column";function gx({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??px.YAMLMap,s=new o(i.schema);i.atRoot&&(i.atRoot=!1);let c=r.offset,l=null;for(let u of r.items){let{start:d,key:f,sep:h,value:v}=u,m=qg.resolveProps(d,{indicator:"explicit-key-ind",next:f??h?.[0],offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0}),p=!m.found;if(p){if(f&&(f.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==r.indent&&n(c,"BAD_INDENT",zg)),!m.anchor&&!m.tag&&!h){l=m.end,m.comment&&(s.comment?s.comment+=`
67
+ `+m.comment:s.comment=m.comment);continue}(m.newlineAfterProp||mx.containsNewline(f))&&n(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else m.found?.indent!==r.indent&&n(c,"BAD_INDENT",zg);i.atKey=!0;let b=m.end,g=f?e(i,f,m,n):t(i,b,d,null,m,n);i.schema.compat&&Wg.flowIndentCheck(r.indent,f,n),i.atKey=!1,vx.mapIncludes(i,s.items,g)&&n(b,"DUPLICATE_KEY","Map keys must be unique");let y=qg.resolveProps(h??[],{indicator:"map-value-ind",next:v,offset:g.range[2],onError:n,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=y.end,y.found){p&&(v?.type==="block-map"&&!y.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&m.start<y.found.offset-1024&&n(g.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let E=v?e(i,v,y,n):t(i,c,h,null,y,n);i.schema.compat&&Wg.flowIndentCheck(r.indent,v,n),c=E.range[2];let k=new Vg.Pair(g,E);i.options.keepSourceTokens&&(k.srcToken=u),s.items.push(k)}else{p&&n(g.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),y.comment&&(g.comment?g.comment+=`
68
+ `+y.comment:g.comment=y.comment);let E=new Vg.Pair(g);i.options.keepSourceTokens&&(E.srcToken=u),s.items.push(E)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[r.offset,c,l??c],s}Jg.resolveBlockMap=gx});var Kg=C(Ug=>{"use strict";var wx=rr(),yx=No(),Nx=Pf();function bx({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??wx.YAMLSeq,s=new o(i.schema);i.atRoot&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let c=r.offset,l=null;for(let{start:u,value:d}of r.items){let f=yx.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||d)d?.type==="block-seq"?n(f.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(s.comment=f.comment);continue}let h=d?e(i,d,f,n):t(i,f.end,u,null,f,n);i.schema.compat&&Nx.flowIndentCheck(r.indent,d,n),c=h.range[2],s.items.push(h)}return s.range=[r.offset,c,l??c],s}Ug.resolveBlockSeq=bx});var Bn=C(Yg=>{"use strict";function kx(e,t,i,r){let n="";if(e){let a=!1,o="";for(let s of e){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{i&&!a&&r(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";n?n+=o+u:n=u,o="";break}case"newline":n&&(o+=c),a=!0;break;default:r(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:n,offset:t}}Yg.resolveEnd=kx});var ew=C(Zg=>{"use strict";var Sx=G(),Ex=er(),Xg=ir(),Px=rr(),Rx=Bn(),Qg=No(),Cx=Bc(),xx=Rf(),Cf="Block collections are not allowed within flow collections",xf=e=>e&&(e.type==="block-map"||e.type==="block-seq");function Ax({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=r.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Xg.YAMLMap:Px.YAMLSeq),l=new c(i.schema);l.flow=!0;let u=i.atRoot;u&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let d=r.offset+r.start.source.length;for(let p=0;p<r.items.length;++p){let b=r.items[p],{start:g,key:y,sep:E,value:k}=b,S=Qg.resolveProps(g,{flow:s,indicator:"explicit-key-ind",next:y??E?.[0],offset:d,onError:n,parentIndent:r.indent,startOnNewline:!1});if(!S.found){if(!S.anchor&&!S.tag&&!E&&!k){p===0&&S.comma?n(S.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):p<r.items.length-1&&n(S.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),S.comment&&(l.comment?l.comment+=`
69
+ `+S.comment:l.comment=S.comment),d=S.end;continue}!o&&i.options.strict&&Cx.containsNewline(y)&&n(y,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(p===0)S.comma&&n(S.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(S.comma||n(S.start,"MISSING_CHAR",`Missing , between ${s} items`),S.comment){let R="";e:for(let N of g)switch(N.type){case"comma":case"space":break;case"comment":R=N.source.substring(1);break e;default:break e}if(R){let N=l.items[l.items.length-1];Sx.isPair(N)&&(N=N.value??N.key),N.comment?N.comment+=`
70
+ `+R:N.comment=R,S.comment=S.comment.substring(R.length+1)}}if(!o&&!E&&!S.found){let R=k?e(i,k,S,n):t(i,S.end,E,null,S,n);l.items.push(R),d=R.range[2],xf(k)&&n(R.range,"BLOCK_IN_FLOW",Cf)}else{i.atKey=!0;let R=S.end,N=y?e(i,y,S,n):t(i,R,g,null,S,n);xf(y)&&n(N.range,"BLOCK_IN_FLOW",Cf),i.atKey=!1;let w=Qg.resolveProps(E??[],{flow:s,indicator:"map-value-ind",next:k,offset:N.range[2],onError:n,parentIndent:r.indent,startOnNewline:!1});if(w.found){if(!o&&!S.found&&i.options.strict){if(E)for(let $ of E){if($===w.found)break;if($.type==="newline"){n($,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}S.start<w.found.offset-1024&&n(w.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else k&&("source"in k&&k.source?.[0]===":"?n(k,"MISSING_CHAR",`Missing space after : in ${s}`):n(w.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let P=k?e(i,k,w,n):w.found?t(i,w.end,E,null,w,n):null;P?xf(k)&&n(P.range,"BLOCK_IN_FLOW",Cf):w.comment&&(N.comment?N.comment+=`
71
+ `+w.comment:N.comment=w.comment);let F=new Ex.Pair(N,P);if(i.options.keepSourceTokens&&(F.srcToken=b),o){let $=l;xx.mapIncludes(i,$.items,N)&&n(R,"DUPLICATE_KEY","Map keys must be unique"),$.items.push(F)}else{let $=new Xg.YAMLMap(i.schema);$.flow=!0,$.items.push(F);let Be=(P??N).range;$.range=[N.range[0],Be[1],Be[2]],l.items.push($)}d=P?P.range[2]:w.end}}let f=o?"}":"]",[h,...v]=r.end,m=d;if(h?.source===f)m=h.offset+h.source.length;else{let p=s[0].toUpperCase()+s.substring(1),b=u?`${p} must end with a ${f}`:`${p} in block collection must be sufficiently indented and end with a ${f}`;n(d,u?"MISSING_CHAR":"BAD_INDENT",b),h&&h.source.length!==1&&v.unshift(h)}if(v.length>0){let p=Rx.resolveEnd(v,m,i.options.strict,n);p.comment&&(l.comment?l.comment+=`
72
+ `+p.comment:l.comment=p.comment),l.range=[r.offset,m,p.offset]}else l.range=[r.offset,m,m];return l}Zg.resolveFlowCollection=Ax});var iw=C(tw=>{"use strict";var _x=G(),Tx=ke(),Ix=ir(),jx=rr(),$x=Gg(),Ox=Kg(),Hx=ew();function Af(e,t,i,r,n,a){let o=i.type==="block-map"?$x.resolveBlockMap(e,t,i,r,a):i.type==="block-seq"?Ox.resolveBlockSeq(e,t,i,r,a):Hx.resolveFlowCollection(e,t,i,r,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function Dx(e,t,i,r,n){let a=r.tag,o=a?t.directives.tagName(a.source,f=>n(a,"TAG_RESOLVE_FAILED",f)):null;if(i.type==="block-seq"){let{anchor:f,newlineAfterProp:h}=r,v=f&&a?f.offset>a.offset?f:a:f??a;v&&(!h||h.offset<v.offset)&&n(v,"MISSING_CHAR","Missing newline after block sequence props")}let s=i.type==="block-map"?"map":i.type==="block-seq"?"seq":i.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===Ix.YAMLMap.tagName&&s==="map"||o===jx.YAMLSeq.tagName&&s==="seq")return Af(e,t,i,n,o);let c=t.schema.tags.find(f=>f.tag===o&&f.collection===s);if(!c){let f=t.schema.knownTags[o];if(f?.collection===s)t.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?n(a,"BAD_COLLECTION_TYPE",`${f.tag} used for ${s} collection, but expects ${f.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Af(e,t,i,n,o)}let l=Af(e,t,i,n,o,c),u=c.resolve?.(l,f=>n(a,"TAG_RESOLVE_FAILED",f),t.options)??l,d=_x.isNode(u)?u:new Tx.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}tw.composeCollection=Dx});var Tf=C(rw=>{"use strict";var _f=ke();function Lx(e,t,i){let r=t.offset,n=Mx(t,e.options.strict,i);if(!n)return{value:"",type:null,comment:"",range:[r,r,r]};let a=n.mode===">"?_f.Scalar.BLOCK_FOLDED:_f.Scalar.BLOCK_LITERAL,o=t.source?Fx(t.source):[],s=o.length;for(let m=o.length-1;m>=0;--m){let p=o[m][1];if(p===""||p==="\r")s=m;else break}if(s===0){let m=n.chomp==="+"&&o.length>0?`
73
73
  `.repeat(Math.max(1,o.length-1)):"",p=r+n.length;return t.source&&(p+=t.source.length),{value:m,type:a,comment:n.comment,range:[r,p,p]}}let c=t.indent+n.indent,l=t.offset+n.length,u=0;for(let m=0;m<s;++m){let[p,b]=o[m];if(b===""||b==="\r")n.indent===0&&p.length>c&&(c=p.length);else{p.length<c&&i(l+p.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(c=p.length),u=m,c===0&&!e.atRoot&&i(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=p.length+b.length+1}for(let m=o.length-1;m>=s;--m)o[m][0].length>c&&(s=m+1);let d="",f="",h=!1;for(let m=0;m<u;++m)d+=o[m][0].slice(c)+`
74
- `;for(let m=u;m<s;++m){let[p,b]=o[m];l+=p.length+b.length+1;let g=b[b.length-1]==="\r";if(g&&(b=b.slice(0,-1)),b&&p.length<c){let E=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;i(l-b.length-(g?2:1),"BAD_INDENT",E),p=""}a===Pf.Scalar.BLOCK_LITERAL?(d+=f+p.slice(c)+b,f=`
74
+ `;for(let m=u;m<s;++m){let[p,b]=o[m];l+=p.length+b.length+1;let g=b[b.length-1]==="\r";if(g&&(b=b.slice(0,-1)),b&&p.length<c){let E=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;i(l-b.length-(g?2:1),"BAD_INDENT",E),p=""}a===_f.Scalar.BLOCK_LITERAL?(d+=f+p.slice(c)+b,f=`
75
75
  `):p.length>c||b[0]===" "?(f===" "?f=`
76
76
  `:!h&&f===`
77
77
  `&&(f=`
@@ -84,65 +84,65 @@ ${l}
84
84
  `+o[m][0].slice(c);d[d.length-1]!==`
85
85
  `&&(d+=`
86
86
  `);break;default:d+=`
87
- `}let v=r+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[r,v,v]}}function $x({offset:e,props:t},i,r){if(t[0].type!=="block-scalar-header")return r(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",c=-1;for(let f=1;f<n.length;++f){let h=n[f];if(!s&&(h==="-"||h==="+"))s=h;else{let v=Number(h);!o&&v?o=v:c===-1&&(c=e+f)}}c!==-1&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,u="",d=n.length;for(let f=1;f<t.length;++f){let h=t[f];switch(h.type){case"space":l=!0;case"newline":d+=h.source.length;break;case"comment":i&&!l&&r(h,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=h.source.length,u=h.source.substring(1);break;case"error":r(h,"UNEXPECTED_TOKEN",h.message),d+=h.source.length;break;default:{let v=`Unexpected token in block scalar header: ${h.type}`;r(h,"UNEXPECTED_TOKEN",v);let m=h.source;m&&typeof m=="string"&&(d+=m.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function Ox(e){let t=e.split(/\n( *)/),i=t[0],r=i.match(/^( *)/),a=[r?.[1]?[r[1],i.slice(r[1].length)]:["",i]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}iw.resolveBlockScalar=jx});var xf=C(nw=>{"use strict";var Cf=ke(),Hx=Hn();function Dx(e,t,i){let{offset:r,type:n,source:a,end:o}=e,s,c,l=(f,h,v)=>i(r+f,h,v);switch(n){case"scalar":s=Cf.Scalar.PLAIN,c=Lx(a,l);break;case"single-quoted-scalar":s=Cf.Scalar.QUOTE_SINGLE,c=Mx(a,l);break;case"double-quoted-scalar":s=Cf.Scalar.QUOTE_DOUBLE,c=Fx(a,l);break;default:return i(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[r,r+a.length,r+a.length]}}let u=r+a.length,d=Hx.resolveEnd(o,u,t,i);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function Lx(e,t){let i="";switch(e[0]){case" ":i="a tab character";break;case",":i="flow indicator character ,";break;case"%":i="directive indicator character %";break;case"|":case">":{i=`block scalar indicator ${e[0]}`;break}case"@":case"`":{i=`reserved character ${e[0]}`;break}}return i&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${i}`),rw(e)}function Mx(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),rw(e.slice(1,-1)).replace(/''/g,"'")}function rw(e){let t,i;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
87
+ `}let v=r+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[r,v,v]}}function Mx({offset:e,props:t},i,r){if(t[0].type!=="block-scalar-header")return r(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",c=-1;for(let f=1;f<n.length;++f){let h=n[f];if(!s&&(h==="-"||h==="+"))s=h;else{let v=Number(h);!o&&v?o=v:c===-1&&(c=e+f)}}c!==-1&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,u="",d=n.length;for(let f=1;f<t.length;++f){let h=t[f];switch(h.type){case"space":l=!0;case"newline":d+=h.source.length;break;case"comment":i&&!l&&r(h,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=h.source.length,u=h.source.substring(1);break;case"error":r(h,"UNEXPECTED_TOKEN",h.message),d+=h.source.length;break;default:{let v=`Unexpected token in block scalar header: ${h.type}`;r(h,"UNEXPECTED_TOKEN",v);let m=h.source;m&&typeof m=="string"&&(d+=m.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function Fx(e){let t=e.split(/\n( *)/),i=t[0],r=i.match(/^( *)/),a=[r?.[1]?[r[1],i.slice(r[1].length)]:["",i]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}rw.resolveBlockScalar=Lx});var jf=C(aw=>{"use strict";var If=ke(),Bx=Bn();function Vx(e,t,i){let{offset:r,type:n,source:a,end:o}=e,s,c,l=(f,h,v)=>i(r+f,h,v);switch(n){case"scalar":s=If.Scalar.PLAIN,c=qx(a,l);break;case"single-quoted-scalar":s=If.Scalar.QUOTE_SINGLE,c=Wx(a,l);break;case"double-quoted-scalar":s=If.Scalar.QUOTE_DOUBLE,c=zx(a,l);break;default:return i(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[r,r+a.length,r+a.length]}}let u=r+a.length,d=Bx.resolveEnd(o,u,t,i);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function qx(e,t){let i="";switch(e[0]){case" ":i="a tab character";break;case",":i="flow indicator character ,";break;case"%":i="directive indicator character %";break;case"|":case">":{i=`block scalar indicator ${e[0]}`;break}case"@":case"`":{i=`reserved character ${e[0]}`;break}}return i&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${i}`),nw(e)}function Wx(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),nw(e.slice(1,-1)).replace(/''/g,"'")}function nw(e){let t,i;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
88
88
  `,"sy"),i=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
89
89
  `,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,i=/[ \t]*(.*?)[ \t]*\r?\n/sy}let r=t.exec(e);if(!r)return e;let n=r[1],a=" ",o=t.lastIndex;for(i.lastIndex=o;r=i.exec(e);)r[1]===""?a===`
90
90
  `?n+=a:a=`
91
- `:(n+=a+r[1],a=" "),o=i.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,r=s.exec(e),n+a+(r?.[1]??"")}function Fx(e,t){let i="";for(let r=1;r<e.length-1;++r){let n=e[r];if(!(n==="\r"&&e[r+1]===`
91
+ `:(n+=a+r[1],a=" "),o=i.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,r=s.exec(e),n+a+(r?.[1]??"")}function zx(e,t){let i="";for(let r=1;r<e.length-1;++r){let n=e[r];if(!(n==="\r"&&e[r+1]===`
92
92
  `))if(n===`
93
- `){let{fold:a,offset:o}=Bx(e,r);i+=a,r=o}else if(n==="\\"){let a=e[++r],o=Vx[a];if(o)i+=o;else if(a===`
93
+ `){let{fold:a,offset:o}=Jx(e,r);i+=a,r=o}else if(n==="\\"){let a=e[++r],o=Gx[a];if(o)i+=o;else if(a===`
94
94
  `)for(a=e[r+1];a===" "||a===" ";)a=e[++r+1];else if(a==="\r"&&e[r+1]===`
95
- `)for(a=e[++r+1];a===" "||a===" ";)a=e[++r+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;i+=qx(e,r+1,s,t),r+=s}else{let s=e.substr(r-1,2);t(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),i+=s}}else if(n===" "||n===" "){let a=r,o=e[r+1];for(;o===" "||o===" ";)o=e[++r+1];o!==`
95
+ `)for(a=e[++r+1];a===" "||a===" ";)a=e[++r+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;i+=Ux(e,r+1,s,t),r+=s}else{let s=e.substr(r-1,2);t(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),i+=s}}else if(n===" "||n===" "){let a=r,o=e[r+1];for(;o===" "||o===" ";)o=e[++r+1];o!==`
96
96
  `&&!(o==="\r"&&e[r+2]===`
97
- `)&&(i+=r>a?e.slice(a,r+1):n)}else i+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),i}function Bx(e,t){let i="",r=e[t+1];for(;(r===" "||r===" "||r===`
97
+ `)&&(i+=r>a?e.slice(a,r+1):n)}else i+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),i}function Jx(e,t){let i="",r=e[t+1];for(;(r===" "||r===" "||r===`
98
98
  `||r==="\r")&&!(r==="\r"&&e[t+2]!==`
99
99
  `);)r===`
100
100
  `&&(i+=`
101
- `),t+=1,r=e[t+1];return i||(i=" "),{fold:i,offset:t}}var Vx={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
102
- `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function qx(e,t,i,r){let n=e.substr(t,i),o=n.length===i&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,i+2);return r(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}nw.resolveFlowScalar=Dx});var sw=C(ow=>{"use strict";var Yr=G(),aw=ke(),Wx=Rf(),zx=xf();function Jx(e,t,i,r){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?Wx.resolveBlockScalar(e,t,r):zx.resolveFlowScalar(t,e.options.strict,r),c=i?e.directives.tagName(i.source,d=>r(i,"TAG_RESOLVE_FAILED",d)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[Yr.SCALAR]:c?l=Gx(e.schema,n,c,i,r):t.type==="scalar"?l=Ux(e,n,t,r):l=e.schema[Yr.SCALAR];let u;try{let d=l.resolve(n,f=>r(i??t,"TAG_RESOLVE_FAILED",f),e.options);u=Yr.isScalar(d)?d:new aw.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);r(i??t,"TAG_RESOLVE_FAILED",f),u=new aw.Scalar(n)}return u.range=s,u.source=n,a&&(u.type=a),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function Gx(e,t,i,r,n){if(i==="!")return e[Yr.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===i)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(t))return s;let o=e.knownTags[i];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,i!=="tag:yaml.org,2002:str"),e[Yr.SCALAR])}function Ux({atKey:e,directives:t,schema:i},r,n,a){let o=i.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(r))||i[Yr.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(r))??i[Yr.SCALAR];if(o.tag!==s.tag){let c=t.tagString(o.tag),l=t.tagString(s.tag),u=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",u,!0)}}return o}ow.composeScalar=Jx});var lw=C(cw=>{"use strict";function Kx(e,t,i){if(t){i??(i=t.length);for(let r=i-1;r>=0;--r){let n=t[r];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}for(n=t[++r];n?.type==="space";)e+=n.source.length,n=t[++r];break}}return e}cw.emptyScalarPosition=Kx});var fw=C(_f=>{"use strict";var Yx=Ua(),Xx=G(),Qx=tw(),uw=sw(),Zx=Hn(),eA=lw(),tA={composeNode:dw,composeEmptyNode:Af};function dw(e,t,i,r){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=i,l,u=!0;switch(t.type){case"alias":l=iA(e,t,r),(s||c)&&r(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=uw.composeScalar(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Qx.composeCollection(tA,e,t,i,r),s&&(l.anchor=s.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);r(t,"RESOURCE_EXHAUSTION",f)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;r(t,"UNEXPECTED_TOKEN",d),u=!1}}return l??(l=Af(e,t.offset,void 0,null,i,r)),s&&l.anchor===""&&r(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&e.options.stringKeys&&(!Xx.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&r(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function Af(e,t,i,r,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:eA.emptyScalarPosition(t,i,r),indent:-1,source:""},d=uw.composeScalar(e,u,s,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(d.spaceBefore=!0),a&&(d.comment=a,d.range[2]=c),d}function iA({options:e},{offset:t,source:i,end:r},n){let a=new Yx.Alias(i.substring(1));a.source===""&&n(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(t+i.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+i.length,s=Zx.resolveEnd(r,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}_f.composeEmptyNode=Af;_f.composeNode=dw});var mw=C(pw=>{"use strict";var rA=uo(),hw=fw(),nA=Hn(),aA=mo();function oA(e,t,{offset:i,start:r,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new rA.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=aA.resolveProps(r,{indicator:"doc-start",next:n??a?.[0],offset:i,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?hw.composeNode(l,n,u,o):hw.composeEmptyNode(l,u.end,r,null,u,o);let d=c.contents.range[2],f=nA.resolveEnd(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[i,d,f.offset],c}pw.composeDoc=oA});var If=C(ww=>{"use strict";var sA=Js("process"),cA=vd(),lA=uo(),vo=po(),vw=G(),uA=mw(),dA=Hn();function go(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:i}=e;return[t,t+(typeof i=="string"?i.length:1)]}function gw(e){let t="",i=!1,r=!1;for(let n=0;n<e.length;++n){let a=e[n];switch(a[0]){case"#":t+=(t===""?"":r?`
101
+ `),t+=1,r=e[t+1];return i||(i=" "),{fold:i,offset:t}}var Gx={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
102
+ `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Ux(e,t,i,r){let n=e.substr(t,i),o=n.length===i&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,i+2);return r(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}aw.resolveFlowScalar=Vx});var cw=C(sw=>{"use strict";var Qr=G(),ow=ke(),Kx=Tf(),Yx=jf();function Xx(e,t,i,r){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?Kx.resolveBlockScalar(e,t,r):Yx.resolveFlowScalar(t,e.options.strict,r),c=i?e.directives.tagName(i.source,d=>r(i,"TAG_RESOLVE_FAILED",d)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[Qr.SCALAR]:c?l=Qx(e.schema,n,c,i,r):t.type==="scalar"?l=Zx(e,n,t,r):l=e.schema[Qr.SCALAR];let u;try{let d=l.resolve(n,f=>r(i??t,"TAG_RESOLVE_FAILED",f),e.options);u=Qr.isScalar(d)?d:new ow.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);r(i??t,"TAG_RESOLVE_FAILED",f),u=new ow.Scalar(n)}return u.range=s,u.source=n,a&&(u.type=a),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function Qx(e,t,i,r,n){if(i==="!")return e[Qr.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===i)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(t))return s;let o=e.knownTags[i];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,i!=="tag:yaml.org,2002:str"),e[Qr.SCALAR])}function Zx({atKey:e,directives:t,schema:i},r,n,a){let o=i.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(r))||i[Qr.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(r))??i[Qr.SCALAR];if(o.tag!==s.tag){let c=t.tagString(o.tag),l=t.tagString(s.tag),u=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",u,!0)}}return o}sw.composeScalar=Xx});var uw=C(lw=>{"use strict";function eA(e,t,i){if(t){i??(i=t.length);for(let r=i-1;r>=0;--r){let n=t[r];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}for(n=t[++r];n?.type==="space";)e+=n.source.length,n=t[++r];break}}return e}lw.emptyScalarPosition=eA});var hw=C(Of=>{"use strict";var tA=Za(),iA=G(),rA=iw(),dw=cw(),nA=Bn(),aA=uw(),oA={composeNode:fw,composeEmptyNode:$f};function fw(e,t,i,r){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=i,l,u=!0;switch(t.type){case"alias":l=sA(e,t,r),(s||c)&&r(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=dw.composeScalar(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=rA.composeCollection(oA,e,t,i,r),s&&(l.anchor=s.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);r(t,"RESOURCE_EXHAUSTION",f)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;r(t,"UNEXPECTED_TOKEN",d),u=!1}}return l??(l=$f(e,t.offset,void 0,null,i,r)),s&&l.anchor===""&&r(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&e.options.stringKeys&&(!iA.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&r(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function $f(e,t,i,r,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:aA.emptyScalarPosition(t,i,r),indent:-1,source:""},d=dw.composeScalar(e,u,s,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(d.spaceBefore=!0),a&&(d.comment=a,d.range[2]=c),d}function sA({options:e},{offset:t,source:i,end:r},n){let a=new tA.Alias(i.substring(1));a.source===""&&n(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(t+i.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+i.length,s=nA.resolveEnd(r,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}Of.composeEmptyNode=$f;Of.composeNode=fw});var vw=C(mw=>{"use strict";var cA=vo(),pw=hw(),lA=Bn(),uA=No();function dA(e,t,{offset:i,start:r,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new cA.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=uA.resolveProps(r,{indicator:"doc-start",next:n??a?.[0],offset:i,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?pw.composeNode(l,n,u,o):pw.composeEmptyNode(l,u.end,r,null,u,o);let d=c.contents.range[2],f=lA.resolveEnd(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[i,d,f.offset],c}mw.composeDoc=dA});var Df=C(yw=>{"use strict";var fA=Ks("process"),hA=bd(),pA=vo(),bo=yo(),gw=G(),mA=vw(),vA=Bn();function ko(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:i}=e;return[t,t+(typeof i=="string"?i.length:1)]}function ww(e){let t="",i=!1,r=!1;for(let n=0;n<e.length;++n){let a=e[n];switch(a[0]){case"#":t+=(t===""?"":r?`
103
103
 
104
104
  `:`
105
- `)+(a.substring(1)||" "),i=!0,r=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),i=!1;break;default:i||(r=!0),i=!1}}return{comment:t,afterEmptyLine:r}}var Tf=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,r,n,a)=>{let o=go(i);a?this.warnings.push(new vo.YAMLWarning(o,r,n)):this.errors.push(new vo.YAMLParseError(o,r,n))},this.directives=new cA.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,i){let{comment:r,afterEmptyLine:n}=gw(this.prelude);if(r){let a=t.contents;if(i)t.comment=t.comment?`${t.comment}
106
- ${r}`:r;else if(n||t.directives.docStart||!a)t.commentBefore=r;else if(vw.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];vw.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${r}
105
+ `)+(a.substring(1)||" "),i=!0,r=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),i=!1;break;default:i||(r=!0),i=!1}}return{comment:t,afterEmptyLine:r}}var Hf=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,r,n,a)=>{let o=ko(i);a?this.warnings.push(new bo.YAMLWarning(o,r,n)):this.errors.push(new bo.YAMLParseError(o,r,n))},this.directives=new hA.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,i){let{comment:r,afterEmptyLine:n}=ww(this.prelude);if(r){let a=t.contents;if(i)t.comment=t.comment?`${t.comment}
106
+ ${r}`:r;else if(n||t.directives.docStart||!a)t.commentBefore=r;else if(gw.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];gw.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${r}
107
107
  ${s}`:r}else{let o=a.commentBefore;a.commentBefore=o?`${r}
108
- ${o}`:r}}if(i){for(let a=0;a<this.errors.length;++a)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:gw(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,i=!1,r=-1){for(let n of t)yield*this.next(n);yield*this.end(i,r)}*next(t){switch(sA.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(i,r,n)=>{let a=go(t);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",r,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let i=uA.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!i.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(i,!1),this.doc&&(yield this.doc),this.doc=i,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let i=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,r=new vo.YAMLParseError(go(t),"UNEXPECTED_TOKEN",i);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){let r="Unexpected doc-end without preceding document";this.errors.push(new vo.YAMLParseError(go(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let i=dA.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),i.comment){let r=this.doc.comment;this.doc.comment=r?`${r}
109
- ${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new vo.YAMLParseError(go(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,i=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let r=Object.assign({_directives:this.directives},this.options),n=new lA.Document(void 0,r);this.atDirectives&&this.onError(i,"MISSING_CHAR","Missing directives-end indicator line"),n.range=[0,i,i],this.decorate(n,!1),yield n}}};ww.Composer=Tf});var bw=C(Mc=>{"use strict";var fA=Rf(),hA=xf(),pA=po(),yw=Za();function mA(e,t=!0,i){if(e){let r=(n,a,o)=>{let s=typeof n=="number"?n:Array.isArray(n)?n[0]:n.offset;if(i)i(s,a,o);else throw new pA.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return hA.resolveFlowScalar(e,t,r);case"block-scalar":return fA.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function vA(e,t){let{implicitKey:i=!1,indent:r,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=yw.stringifyString({type:o,value:e},{implicitKey:i,indent:r>0?" ".repeat(r):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:r,source:`
108
+ ${o}`:r}}if(i){for(let a=0;a<this.errors.length;++a)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:ww(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,i=!1,r=-1){for(let n of t)yield*this.next(n);yield*this.end(i,r)}*next(t){switch(fA.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(i,r,n)=>{let a=ko(t);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",r,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let i=mA.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!i.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(i,!1),this.doc&&(yield this.doc),this.doc=i,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let i=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,r=new bo.YAMLParseError(ko(t),"UNEXPECTED_TOKEN",i);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){let r="Unexpected doc-end without preceding document";this.errors.push(new bo.YAMLParseError(ko(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let i=vA.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),i.comment){let r=this.doc.comment;this.doc.comment=r?`${r}
109
+ ${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new bo.YAMLParseError(ko(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,i=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let r=Object.assign({_directives:this.directives},this.options),n=new pA.Document(void 0,r);this.atDirectives&&this.onError(i,"MISSING_CHAR","Missing directives-end indicator line"),n.range=[0,i,i],this.decorate(n,!1),yield n}}};yw.Composer=Hf});var kw=C(Vc=>{"use strict";var gA=Tf(),wA=jf(),yA=yo(),Nw=no();function NA(e,t=!0,i){if(e){let r=(n,a,o)=>{let s=typeof n=="number"?n:Array.isArray(n)?n[0]:n.offset;if(i)i(s,a,o);else throw new yA.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return wA.resolveFlowScalar(e,t,r);case"block-scalar":return gA.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function bA(e,t){let{implicitKey:i=!1,indent:r,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=Nw.stringifyString({type:o,value:e},{implicitKey:i,indent:r>0?" ".repeat(r):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:r,source:`
110
110
  `}];switch(s[0]){case"|":case">":{let l=s.indexOf(`
111
111
  `),u=s.substring(0,l),d=s.substring(l+1)+`
112
- `,f=[{type:"block-scalar-header",offset:a,indent:r,source:u}];return Nw(f,c)||f.push({type:"newline",offset:-1,indent:r,source:`
113
- `}),{type:"block-scalar",offset:a,indent:r,props:f,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:r,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:r,source:s,end:c};default:return{type:"scalar",offset:a,indent:r,source:s,end:c}}}function gA(e,t,i={}){let{afterKey:r=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=i,s="indent"in e?e.indent:null;if(r&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=yw.stringifyString({type:o,value:t},{implicitKey:n||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":wA(e,c);break;case'"':jf(e,c,"double-quoted-scalar");break;case"'":jf(e,c,"single-quoted-scalar");break;default:jf(e,c,"scalar")}}function wA(e,t){let i=t.indexOf(`
112
+ `,f=[{type:"block-scalar-header",offset:a,indent:r,source:u}];return bw(f,c)||f.push({type:"newline",offset:-1,indent:r,source:`
113
+ `}),{type:"block-scalar",offset:a,indent:r,props:f,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:r,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:r,source:s,end:c};default:return{type:"scalar",offset:a,indent:r,source:s,end:c}}}function kA(e,t,i={}){let{afterKey:r=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=i,s="indent"in e?e.indent:null;if(r&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=Nw.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">":SA(e,c);break;case'"':Lf(e,c,"double-quoted-scalar");break;case"'":Lf(e,c,"single-quoted-scalar");break;default:Lf(e,c,"scalar")}}function SA(e,t){let i=t.indexOf(`
114
114
  `),r=t.substring(0,i),n=t.substring(i+1)+`
115
- `;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=r,e.source=n}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:r}];Nw(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
116
- `});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function Nw(e,t){if(t)for(let i of t)switch(i.type){case"space":case"comment":e.push(i);break;case"newline":return e.push(i),!0}return!1}function jf(e,t,i){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=i,e.source=t;break;case"block-scalar":{let r=e.props.slice(1),n=t.length;e.props[0].type==="block-scalar-header"&&(n-=e.props[0].source.length);for(let a of r)a.offset+=n;delete e.props,Object.assign(e,{type:i,source:t,end:r});break}case"block-map":case"block-seq":{let n={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
117
- `};delete e.items,Object.assign(e,{type:i,source:t,end:[n]});break}default:{let r="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:i,indent:r,source:t,end:n})}}}Mc.createScalarToken=vA;Mc.resolveAsScalar=mA;Mc.setScalarValue=gA});var Sw=C(kw=>{"use strict";var yA=e=>"type"in e?Bc(e):Fc(e);function Bc(e){switch(e.type){case"block-scalar":{let t="";for(let i of e.props)t+=Bc(i);return t+e.source}case"block-map":case"block-seq":{let t="";for(let i of e.items)t+=Fc(i);return t}case"flow-collection":{let t=e.start.source;for(let i of e.items)t+=Fc(i);for(let i of e.end)t+=i.source;return t}case"document":{let t=Fc(e);if(e.end)for(let i of e.end)t+=i.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let i of e.end)t+=i.source;return t}}}function Fc({start:e,key:t,sep:i,value:r}){let n="";for(let a of e)n+=a.source;if(t&&(n+=Bc(t)),i)for(let a of i)n+=a.source;return r&&(n+=Bc(r)),n}kw.stringify=yA});var Cw=C(Rw=>{"use strict";var $f=Symbol("break visit"),NA=Symbol("skip children"),Ew=Symbol("remove item");function Xr(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Pw(Object.freeze([]),e,t)}Xr.BREAK=$f;Xr.SKIP=NA;Xr.REMOVE=Ew;Xr.itemAtPath=(e,t)=>{let i=e;for(let[r,n]of t){let a=i?.[r];if(a&&"items"in a)i=a.items[n];else return}return i};Xr.parentCollection=(e,t)=>{let i=Xr.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],n=i?.[r];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function Pw(e,t,i){let r=i(t,e);if(typeof r=="symbol")return r;for(let n of["key","value"]){let a=t[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=Pw(Object.freeze(e.concat([[n,o]])),a.items[o],i);if(typeof s=="number")o=s-1;else{if(s===$f)return $f;s===Ew&&(a.items.splice(o,1),o-=1)}}typeof r=="function"&&n==="key"&&(r=r(t,e))}}return typeof r=="function"?r(t,e):r}Rw.visit=Xr});var Vc=C(st=>{"use strict";var Of=bw(),bA=Sw(),kA=Cw(),Hf="\uFEFF",Df="",Lf="",Mf="",SA=e=>!!e&&"items"in e,EA=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function PA(e){switch(e){case Hf:return"<BOM>";case Df:return"<DOC>";case Lf:return"<FLOW_END>";case Mf:return"<SCALAR>";default:return JSON.stringify(e)}}function RA(e){switch(e){case Hf:return"byte-order-mark";case Df:return"doc-mode";case Lf:return"flow-error-end";case Mf:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
115
+ `;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=r,e.source=n}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:r}];bw(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 bw(e,t){if(t)for(let i of t)switch(i.type){case"space":case"comment":e.push(i);break;case"newline":return e.push(i),!0}return!1}function Lf(e,t,i){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=i,e.source=t;break;case"block-scalar":{let r=e.props.slice(1),n=t.length;e.props[0].type==="block-scalar-header"&&(n-=e.props[0].source.length);for(let a of r)a.offset+=n;delete e.props,Object.assign(e,{type:i,source:t,end:r});break}case"block-map":case"block-seq":{let n={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
117
+ `};delete e.items,Object.assign(e,{type:i,source:t,end:[n]});break}default:{let r="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:i,indent:r,source:t,end:n})}}}Vc.createScalarToken=bA;Vc.resolveAsScalar=NA;Vc.setScalarValue=kA});var Ew=C(Sw=>{"use strict";var EA=e=>"type"in e?Wc(e):qc(e);function Wc(e){switch(e.type){case"block-scalar":{let t="";for(let i of e.props)t+=Wc(i);return t+e.source}case"block-map":case"block-seq":{let t="";for(let i of e.items)t+=qc(i);return t}case"flow-collection":{let t=e.start.source;for(let i of e.items)t+=qc(i);for(let i of e.end)t+=i.source;return t}case"document":{let t=qc(e);if(e.end)for(let i of e.end)t+=i.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let i of e.end)t+=i.source;return t}}}function qc({start:e,key:t,sep:i,value:r}){let n="";for(let a of e)n+=a.source;if(t&&(n+=Wc(t)),i)for(let a of i)n+=a.source;return r&&(n+=Wc(r)),n}Sw.stringify=EA});var xw=C(Cw=>{"use strict";var Mf=Symbol("break visit"),PA=Symbol("skip children"),Pw=Symbol("remove item");function Zr(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Rw(Object.freeze([]),e,t)}Zr.BREAK=Mf;Zr.SKIP=PA;Zr.REMOVE=Pw;Zr.itemAtPath=(e,t)=>{let i=e;for(let[r,n]of t){let a=i?.[r];if(a&&"items"in a)i=a.items[n];else return}return i};Zr.parentCollection=(e,t)=>{let i=Zr.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],n=i?.[r];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function Rw(e,t,i){let r=i(t,e);if(typeof r=="symbol")return r;for(let n of["key","value"]){let a=t[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=Rw(Object.freeze(e.concat([[n,o]])),a.items[o],i);if(typeof s=="number")o=s-1;else{if(s===Mf)return Mf;s===Pw&&(a.items.splice(o,1),o-=1)}}typeof r=="function"&&n==="key"&&(r=r(t,e))}}return typeof r=="function"?r(t,e):r}Cw.visit=Zr});var zc=C(st=>{"use strict";var Ff=kw(),RA=Ew(),CA=xw(),Bf="\uFEFF",Vf="",qf="",Wf="",xA=e=>!!e&&"items"in e,AA=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function _A(e){switch(e){case Bf:return"<BOM>";case Vf:return"<DOC>";case qf:return"<FLOW_END>";case Wf:return"<SCALAR>";default:return JSON.stringify(e)}}function TA(e){switch(e){case Bf:return"byte-order-mark";case Vf:return"doc-mode";case qf:return"flow-error-end";case Wf:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
118
118
  `:case`\r
119
- `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}st.createScalarToken=Of.createScalarToken;st.resolveAsScalar=Of.resolveAsScalar;st.setScalarValue=Of.setScalarValue;st.stringify=bA.stringify;st.visit=kA.visit;st.BOM=Hf;st.DOCUMENT=Df;st.FLOW_END=Lf;st.SCALAR=Mf;st.isCollection=SA;st.isScalar=EA;st.prettyToken=PA;st.tokenType=RA});var Vf=C(Aw=>{"use strict";var wo=Vc();function zt(e){switch(e){case void 0:case" ":case`
120
- `:case"\r":case" ":return!0;default:return!1}}var xw=new Set("0123456789ABCDEFabcdef"),CA=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),qc=new Set(",[]{}"),xA=new Set(` ,[]{}
121
- \r `),Ff=e=>!e||xA.has(e),Bf=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,i=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!i;let r=this.next??"stream";for(;r&&(i||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let t=this.pos,i=this.buffer[t];for(;i===" "||i===" ";)i=this.buffer[++t];return!i||i==="#"||i===`
119
+ `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}st.createScalarToken=Ff.createScalarToken;st.resolveAsScalar=Ff.resolveAsScalar;st.setScalarValue=Ff.setScalarValue;st.stringify=RA.stringify;st.visit=CA.visit;st.BOM=Bf;st.DOCUMENT=Vf;st.FLOW_END=qf;st.SCALAR=Wf;st.isCollection=xA;st.isScalar=AA;st.prettyToken=_A;st.tokenType=TA});var Gf=C(_w=>{"use strict";var So=zc();function zt(e){switch(e){case void 0:case" ":case`
120
+ `:case"\r":case" ":return!0;default:return!1}}var Aw=new Set("0123456789ABCDEFabcdef"),IA=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Jc=new Set(",[]{}"),jA=new Set(` ,[]{}
121
+ \r `),zf=e=>!e||jA.has(e),Jf=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,i=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!i;let r=this.next??"stream";for(;r&&(i||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let t=this.pos,i=this.buffer[t];for(;i===" "||i===" ";)i=this.buffer[++t];return!i||i==="#"||i===`
122
122
  `?!0:i==="\r"?this.buffer[t+1]===`
123
123
  `:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let i=this.buffer[t];if(this.indentNext>0){let r=0;for(;i===" ";)i=this.buffer[++r+t];if(i==="\r"){let n=this.buffer[r+t+1];if(n===`
124
124
  `||!n&&!this.atEnd)return t+r+1}return i===`
125
125
  `||r>=this.indentNext||!i&&!this.atEnd?t+r:-1}if(i==="-"||i==="."){let r=this.buffer.substr(t,3);if((r==="---"||r==="...")&&zt(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
126
- `,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===wo.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let i=t.length,r=t.indexOf("#");for(;r!==-1;){let a=t[r-1];if(a===" "||a===" "){i=r-1;break}else r=t.indexOf("#",r+1)}for(;;){let a=t[i-1];if(a===" "||a===" ")i-=1;else break}let n=(yield*this.pushCount(i))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let i=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-i),yield*this.pushNewline(),"stream"}return yield wo.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let i=this.peek(3);if((i==="---"||i==="...")&&zt(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,i==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!zt(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,i]=this.peek(2);if(!i&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&zt(i)){let r=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=r,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let i=yield*this.pushIndicators();switch(t[i]){case"#":yield*this.pushCount(t.length-i);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Ff),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return i+=yield*this.parseBlockScalarHeader(),i+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-i),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,i,r=-1;do t=yield*this.pushNewline(),t>0?(i=yield*this.pushSpaces(!1),this.indentValue=r=i):i=0,i+=yield*this.pushSpaces(!0);while(t+i>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((r!==-1&&r<this.indentNext&&n[0]!=="#"||r===0&&(n.startsWith("---")||n.startsWith("..."))&&zt(n[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield wo.FLOW_END,yield*this.parseLineStart();let a=0;for(;n[a]===",";)a+=yield*this.pushCount(1),a+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(a+=yield*this.pushIndicators(),n[a]){case void 0:return"flow";case"#":return yield*this.pushCount(n.length-a),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(Ff),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||zt(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),i=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;i!==-1&&this.buffer[i+1]==="'";)i=this.buffer.indexOf("'",i+2);else for(;i!==-1;){let a=0;for(;this.buffer[i-1-a]==="\\";)a+=1;if(a%2===0)break;i=this.buffer.indexOf('"',i+1)}let r=this.buffer.substring(0,i),n=r.indexOf(`
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]===So.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let i=t.length,r=t.indexOf("#");for(;r!==-1;){let a=t[r-1];if(a===" "||a===" "){i=r-1;break}else r=t.indexOf("#",r+1)}for(;;){let a=t[i-1];if(a===" "||a===" ")i-=1;else break}let n=(yield*this.pushCount(i))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let i=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-i),yield*this.pushNewline(),"stream"}return yield So.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let i=this.peek(3);if((i==="---"||i==="...")&&zt(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,i==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!zt(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,i]=this.peek(2);if(!i&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&zt(i)){let r=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=r,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let i=yield*this.pushIndicators();switch(t[i]){case"#":yield*this.pushCount(t.length-i);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(zf),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return i+=yield*this.parseBlockScalarHeader(),i+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-i),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,i,r=-1;do t=yield*this.pushNewline(),t>0?(i=yield*this.pushSpaces(!1),this.indentValue=r=i):i=0,i+=yield*this.pushSpaces(!0);while(t+i>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((r!==-1&&r<this.indentNext&&n[0]!=="#"||r===0&&(n.startsWith("---")||n.startsWith("..."))&&zt(n[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield So.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(zf),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||zt(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),i=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;i!==-1&&this.buffer[i+1]==="'";)i=this.buffer.indexOf("'",i+2);else for(;i!==-1;){let a=0;for(;this.buffer[i-1-a]==="\\";)a+=1;if(a%2===0)break;i=this.buffer.indexOf('"',i+1)}let r=this.buffer.substring(0,i),n=r.indexOf(`
127
127
  `,this.pos);if(n!==-1){for(;n!==-1;){let a=this.continueScalar(n+1);if(a===-1)break;n=r.indexOf(`
128
128
  `,a)}n!==-1&&(i=n-(r[n-1]==="\r"?2:1))}if(i===-1){if(!this.atEnd)return this.setNext("quoted-scalar");i=this.buffer.length}return yield*this.pushToIndex(i+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let i=this.buffer[++t];if(i==="+")this.blockScalarKeep=!0;else if(i>"0"&&i<="9")this.blockScalarIndent=Number(i)-1;else if(i!=="-")break}return yield*this.pushUntil(i=>zt(i)||i==="#")}*parseBlockScalar(){let t=this.pos-1,i=0,r;e:for(let a=this.pos;r=this.buffer[a];++a)switch(r){case" ":i+=1;break;case`
129
129
  `:t=a,i=0;break;case"\r":{let o=this.buffer[a+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
130
130
  `)break}default:break e}if(!r&&!this.atEnd)return this.setNext("block-scalar");if(i>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=i:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let a=this.continueScalar(t+1);if(a===-1)break;t=this.buffer.indexOf(`
131
131
  `,a)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let n=t+1;for(r=this.buffer[n];r===" ";)r=this.buffer[++n];if(r===" "){for(;r===" "||r===" "||r==="\r"||r===`
132
132
  `;)r=this.buffer[++n];t=n-1}else if(!this.blockScalarKeep)do{let a=t-1,o=this.buffer[a];o==="\r"&&(o=this.buffer[--a]);let s=a;for(;o===" ";)o=this.buffer[--a];if(o===`
133
- `&&a>=this.pos&&a+1+i>s)t=a;else break}while(!0);return yield wo.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,i=this.pos-1,r=this.pos-1,n;for(;n=this.buffer[++r];)if(n===":"){let a=this.buffer[r+1];if(zt(a)||t&&qc.has(a))break;i=r}else if(zt(n)){let a=this.buffer[r+1];if(n==="\r"&&(a===`
133
+ `&&a>=this.pos&&a+1+i>s)t=a;else break}while(!0);return yield So.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,i=this.pos-1,r=this.pos-1,n;for(;n=this.buffer[++r];)if(n===":"){let a=this.buffer[r+1];if(zt(a)||t&&Jc.has(a))break;i=r}else if(zt(n)){let a=this.buffer[r+1];if(n==="\r"&&(a===`
134
134
  `?(r+=1,n=`
135
- `,a=this.buffer[r+1]):i=r),a==="#"||t&&qc.has(a))break;if(n===`
136
- `){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(t&&qc.has(n))break;i=r}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield wo.SCALAR,yield*this.pushToIndex(i+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,i){let r=this.buffer.slice(this.pos,t);return r?(yield r,this.pos+=r.length,r.length):(i&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(Ff),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,r=this.charAt(1);if(zt(r)||i&&qc.has(r)){i?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,i=this.buffer[t];for(;!zt(i)&&i!==">";)i=this.buffer[++t];return yield*this.pushToIndex(i===">"?t+1:t,!1)}else{let t=this.pos+1,i=this.buffer[t];for(;i;)if(CA.has(i))i=this.buffer[++t];else if(i==="%"&&xw.has(this.buffer[t+1])&&xw.has(this.buffer[t+2]))i=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
135
+ `,a=this.buffer[r+1]):i=r),a==="#"||t&&Jc.has(a))break;if(n===`
136
+ `){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(t&&Jc.has(n))break;i=r}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield So.SCALAR,yield*this.pushToIndex(i+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,i){let r=this.buffer.slice(this.pos,t);return r?(yield r,this.pos+=r.length,r.length):(i&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(zf),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,r=this.charAt(1);if(zt(r)||i&&Jc.has(r)){i?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,i=this.buffer[t];for(;!zt(i)&&i!==">";)i=this.buffer[++t];return yield*this.pushToIndex(i===">"?t+1:t,!1)}else{let t=this.pos+1,i=this.buffer[t];for(;i;)if(IA.has(i))i=this.buffer[++t];else if(i==="%"&&Aw.has(this.buffer[t+1])&&Aw.has(this.buffer[t+2]))i=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
137
137
  `?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
138
- `?yield*this.pushCount(2):0}*pushSpaces(t){let i=this.pos-1,r;do r=this.buffer[++i];while(r===" "||t&&r===" ");let n=i-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=i),n}*pushUntil(t){let i=this.pos,r=this.buffer[i];for(;!t(r);)r=this.buffer[++i];return yield*this.pushToIndex(i,!1)}};Aw.Lexer=Bf});var Wf=C(_w=>{"use strict";var qf=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let i=0,r=this.lineStarts.length;for(;i<r;){let a=i+r>>1;this.lineStarts[a]<t?i=a+1:r=a}if(this.lineStarts[i]===t)return{line:i+1,col:1};if(i===0)return{line:0,col:t};let n=this.lineStarts[i-1];return{line:i,col:t-n+1}}}};_w.LineCounter=qf});var Jf=C(Ow=>{"use strict";var AA=Js("process"),Tw=Vc(),_A=Vf();function tr(e,t){for(let i=0;i<e.length;++i)if(e[i].type===t)return!0;return!1}function Iw(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function $w(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function Wc(e){switch(e.type){case"document":return e.start;case"block-map":{let t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function Dn(e){if(e.length===0)return[];let t=e.length;e:for(;--t>=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function zc(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let i=0;i<t.length;++i)e.push(t[i])}function jw(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!tr(t.start,"explicit-key-ind")&&!tr(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,$w(t.value)?t.value.end?zc(t.value.end,t.sep):t.value.end=t.sep:zc(t.start,t.sep),delete t.sep)}var zf=class{constructor(t){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new _A.Lexer,this.onNewLine=t}*parse(t,i=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(t,i))yield*this.next(r);i||(yield*this.end())}*next(t){if(this.source=t,AA.env.LOG_TOKENS&&console.log("|",Tw.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let i=Tw.tokenType(t);if(i)if(i==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=i,yield*this.step(),i){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let r=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:r,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let i=t??this.stack.pop();if(!i)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield i;else{let r=this.peek(1);switch(i.type==="block-scalar"?i.indent="indent"in r?r.indent:0:i.type==="flow-collection"&&r.type==="document"&&(i.indent=0),i.type==="flow-collection"&&jw(i),r.type){case"document":r.value=i;break;case"block-scalar":r.props.push(i);break;case"block-map":{let n=r.items[r.items.length-1];if(n.value){r.items.push({start:[],key:i,sep:[]}),this.onKeyLine=!0;return}else if(n.sep)n.value=i;else{Object.assign(n,{key:i,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case"block-seq":{let n=r.items[r.items.length-1];n.value?r.items.push({start:[],value:i}):n.value=i;break}case"flow-collection":{let n=r.items[r.items.length-1];!n||n.value?r.items.push({start:[],key:i,sep:[]}):n.sep?n.value=i:Object.assign(n,{key:i,sep:[]});return}default:yield*this.pop(),yield*this.pop(i)}if((r.type==="document"||r.type==="block-map"||r.type==="block-seq")&&(i.type==="block-map"||i.type==="block-seq")){let n=i.items[i.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&Iw(n.start)===-1&&(i.indent===0||n.start.every(a=>a.type!=="comment"||a.indent<i.indent))&&(r.type==="document"?r.end=n.start:r.items.push({start:n.start}),i.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{Iw(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let i=this.startBlockValue(t);i?this.stack.push(i):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let i=Wc(this.peek(2)),r=Dn(i),n;t.end?(n=t.end,n.push(this.sourceToken),delete t.end):n=[this.sourceToken];let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:r,key:t,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let i=this.source.indexOf(`
138
+ `?yield*this.pushCount(2):0}*pushSpaces(t){let i=this.pos-1,r;do r=this.buffer[++i];while(r===" "||t&&r===" ");let n=i-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=i),n}*pushUntil(t){let i=this.pos,r=this.buffer[i];for(;!t(r);)r=this.buffer[++i];return yield*this.pushToIndex(i,!1)}};_w.Lexer=Jf});var Kf=C(Tw=>{"use strict";var Uf=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let i=0,r=this.lineStarts.length;for(;i<r;){let a=i+r>>1;this.lineStarts[a]<t?i=a+1:r=a}if(this.lineStarts[i]===t)return{line:i+1,col:1};if(i===0)return{line:0,col:t};let n=this.lineStarts[i-1];return{line:i,col:t-n+1}}}};Tw.LineCounter=Uf});var Xf=C(Hw=>{"use strict";var $A=Ks("process"),Iw=zc(),OA=Gf();function nr(e,t){for(let i=0;i<e.length;++i)if(e[i].type===t)return!0;return!1}function jw(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 Ow(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 Gc(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 Vn(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 Uc(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let i=0;i<t.length;++i)e.push(t[i])}function $w(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!nr(t.start,"explicit-key-ind")&&!nr(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Ow(t.value)?t.value.end?Uc(t.value.end,t.sep):t.value.end=t.sep:Uc(t.start,t.sep),delete t.sep)}var Yf=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 OA.Lexer,this.onNewLine=t}*parse(t,i=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(t,i))yield*this.next(r);i||(yield*this.end())}*next(t){if(this.source=t,$A.env.LOG_TOKENS&&console.log("|",Iw.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let i=Iw.tokenType(t);if(i)if(i==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=i,yield*this.step(),i){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let r=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:r,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let i=t??this.stack.pop();if(!i)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield i;else{let r=this.peek(1);switch(i.type==="block-scalar"?i.indent="indent"in r?r.indent:0:i.type==="flow-collection"&&r.type==="document"&&(i.indent=0),i.type==="flow-collection"&&$w(i),r.type){case"document":r.value=i;break;case"block-scalar":r.props.push(i);break;case"block-map":{let n=r.items[r.items.length-1];if(n.value){r.items.push({start:[],key:i,sep:[]}),this.onKeyLine=!0;return}else if(n.sep)n.value=i;else{Object.assign(n,{key:i,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case"block-seq":{let n=r.items[r.items.length-1];n.value?r.items.push({start:[],value:i}):n.value=i;break}case"flow-collection":{let n=r.items[r.items.length-1];!n||n.value?r.items.push({start:[],key:i,sep:[]}):n.sep?n.value=i:Object.assign(n,{key:i,sep:[]});return}default:yield*this.pop(),yield*this.pop(i)}if((r.type==="document"||r.type==="block-map"||r.type==="block-seq")&&(i.type==="block-map"||i.type==="block-seq")){let n=i.items[i.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&jw(n.start)===-1&&(i.indent===0||n.start.every(a=>a.type!=="comment"||a.indent<i.indent))&&(r.type==="document"?r.end=n.start:r.items.push({start:n.start}),i.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{jw(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let i=this.startBlockValue(t);i?this.stack.push(i):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let i=Gc(this.peek(2)),r=Vn(i),n;t.end?(n=t.end,n.push(this.sourceToken),delete t.end):n=[this.sourceToken];let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:r,key:t,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let i=this.source.indexOf(`
139
139
  `)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(`
140
- `,i)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,i.value){let r="end"in i.value?i.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else if(i.sep)i.sep.push(this.sourceToken);else{if(this.atIndentedComment(i.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){zc(n,i.start),n.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let r=!this.onKeyLine&&this.indent===t.indent,n=r&&(i.sep||i.explicitKey)&&this.type!=="seq-item-ind",a=[];if(n&&i.sep&&!i.value){let o=[];for(let s=0;s<i.sep.length;++s){let c=i.sep[s];switch(c.type){case"newline":o.push(s);break;case"space":break;case"comment":c.indent>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=i.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":n||i.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"explicit-key-ind":!i.sep&&!i.explicitKey?(i.start.push(this.sourceToken),i.explicitKey=!0):n||i.value?(a.push(this.sourceToken),t.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(i.explicitKey)if(i.sep)if(i.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(tr(i.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]});else if($w(i.key)&&!tr(i.sep,"newline")){let o=Dn(i.start),s=i.key,c=i.sep;c.push(this.sourceToken),delete i.key,delete i.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?i.sep=i.sep.concat(a,this.sourceToken):i.sep.push(this.sourceToken);else if(tr(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=Dn(i.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else i.sep?i.value||n?t.items.push({start:a,key:null,sep:[this.sourceToken]}):tr(i.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);n||i.value?(t.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):i.sep?this.stack.push(o):(Object.assign(i,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!i.explicitKey&&i.sep&&!tr(i.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else r&&t.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(i.value){let r="end"in i.value?i.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(i.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){zc(n,i.start),n.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return;case"anchor":case"tag":if(i.value||this.indent<=t.indent)break;i.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;i.value||tr(i.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return}if(this.indent>t.indent){let r=this.startBlockValue(t);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let i=t.items[t.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!i||i.sep?t.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return;case"map-value-ind":!i||i.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!i||i.value?t.items.push({start:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let n=this.flowScalar(this.type);!i||i.value?t.items.push({start:[],key:n,sep:[]}):i.sep?this.stack.push(n):Object.assign(i,{key:n,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===t.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let n=Wc(r),a=Dn(n);jw(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let i=this.source.indexOf(`
140
+ `,i)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,i.value){let r="end"in i.value?i.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else if(i.sep)i.sep.push(this.sourceToken);else{if(this.atIndentedComment(i.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){Uc(n,i.start),n.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let r=!this.onKeyLine&&this.indent===t.indent,n=r&&(i.sep||i.explicitKey)&&this.type!=="seq-item-ind",a=[];if(n&&i.sep&&!i.value){let o=[];for(let s=0;s<i.sep.length;++s){let c=i.sep[s];switch(c.type){case"newline":o.push(s);break;case"space":break;case"comment":c.indent>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=i.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":n||i.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"explicit-key-ind":!i.sep&&!i.explicitKey?(i.start.push(this.sourceToken),i.explicitKey=!0):n||i.value?(a.push(this.sourceToken),t.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(i.explicitKey)if(i.sep)if(i.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(nr(i.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]});else if(Ow(i.key)&&!nr(i.sep,"newline")){let o=Vn(i.start),s=i.key,c=i.sep;c.push(this.sourceToken),delete i.key,delete i.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?i.sep=i.sep.concat(a,this.sourceToken):i.sep.push(this.sourceToken);else if(nr(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=Vn(i.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else i.sep?i.value||n?t.items.push({start:a,key:null,sep:[this.sourceToken]}):nr(i.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);n||i.value?(t.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):i.sep?this.stack.push(o):(Object.assign(i,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!i.explicitKey&&i.sep&&!nr(i.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else r&&t.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(i.value){let r="end"in i.value?i.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(i.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){Uc(n,i.start),n.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return;case"anchor":case"tag":if(i.value||this.indent<=t.indent)break;i.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;i.value||nr(i.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return}if(this.indent>t.indent){let r=this.startBlockValue(t);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let i=t.items[t.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!i||i.sep?t.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return;case"map-value-ind":!i||i.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!i||i.value?t.items.push({start:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let n=this.flowScalar(this.type);!i||i.value?t.items.push({start:[],key:n,sep:[]}):i.sep?this.stack.push(n):Object.assign(i,{key:n,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===t.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let n=Gc(r),a=Vn(n);$w(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let i=this.source.indexOf(`
141
141
  `)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(`
142
- `,i)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=Wc(t),r=Dn(i);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let i=Wc(t),r=Dn(i);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,i){return this.type!=="comment"||this.indent<=i?!1:t.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Ow.Parser=zf});var Fw=C(No=>{"use strict";var Hw=If(),TA=uo(),yo=po(),IA=Ad(),jA=G(),$A=Wf(),Dw=Jf();function Lw(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new $A.LineCounter||null,prettyErrors:t}}function OA(e,t={}){let{lineCounter:i,prettyErrors:r}=Lw(t),n=new Dw.Parser(i?.addNewLine),a=new Hw.Composer(t),o=Array.from(a.compose(n.parse(e)));if(r&&i)for(let s of o)s.errors.forEach(yo.prettifyError(e,i)),s.warnings.forEach(yo.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Mw(e,t={}){let{lineCounter:i,prettyErrors:r}=Lw(t),n=new Dw.Parser(i?.addNewLine),a=new Hw.Composer(t),o=null;for(let s of a.compose(n.parse(e),!0,e.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new yo.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&i&&(o.errors.forEach(yo.prettifyError(e,i)),o.warnings.forEach(yo.prettifyError(e,i))),o}function HA(e,t,i){let r;typeof t=="function"?r=t:i===void 0&&t&&typeof t=="object"&&(i=t);let n=Mw(e,i);if(!n)return null;if(n.warnings.forEach(a=>IA.warn(n.options.logLevel,a)),n.errors.length>0){if(n.options.logLevel!=="silent")throw n.errors[0];n.errors=[]}return n.toJS(Object.assign({reviver:r},i))}function DA(e,t,i){let r=null;if(typeof t=="function"||Array.isArray(t)?r=t:i===void 0&&t&&(i=t),typeof i=="string"&&(i=i.length),typeof i=="number"){let n=Math.round(i);i=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=i??t??{};if(!n)return}return jA.isDocument(e)&&!r?e.toString(i):new TA.Document(e,r,i).toString(i)}No.parse=HA;No.parseAllDocuments=OA;No.parseDocument=Mw;No.stringify=DA});var Qr=C(X=>{"use strict";var LA=If(),MA=uo(),FA=ff(),Gf=po(),BA=Ua(),ir=G(),VA=Xi(),qA=ke(),WA=Zi(),zA=er(),JA=Vc(),GA=Vf(),UA=Wf(),KA=Jf(),Jc=Fw(),Bw=Wa();X.Composer=LA.Composer;X.Document=MA.Document;X.Schema=FA.Schema;X.YAMLError=Gf.YAMLError;X.YAMLParseError=Gf.YAMLParseError;X.YAMLWarning=Gf.YAMLWarning;X.Alias=BA.Alias;X.isAlias=ir.isAlias;X.isCollection=ir.isCollection;X.isDocument=ir.isDocument;X.isMap=ir.isMap;X.isNode=ir.isNode;X.isPair=ir.isPair;X.isScalar=ir.isScalar;X.isSeq=ir.isSeq;X.Pair=VA.Pair;X.Scalar=qA.Scalar;X.YAMLMap=WA.YAMLMap;X.YAMLSeq=zA.YAMLSeq;X.CST=JA;X.Lexer=GA.Lexer;X.LineCounter=UA.LineCounter;X.Parser=KA.Parser;X.parse=Jc.parse;X.parseAllDocuments=Jc.parseAllDocuments;X.parseDocument=Jc.parseDocument;X.stringify=Jc.stringify;X.visit=Bw.visit;X.visitAsync=Bw.visitAsync});import{promises as uP}from"node:fs";import od from"node:path";import{promises as Qu}from"fs";import Ie from"path";import{promises as JS}from"fs";import Oa from"path";import{isDeepStrictEqual as ZD}from"util";import{createHash as yP}from"crypto";function zm(e,t,i,r){return t.iteration>=i.maxIterations?{allowed:!1,reason:`Iteration budget exhausted: ${i.maxIterations}`}:e.type==="invoke_skill"&&!i.allowedSkills.includes(e.ref??"")?{allowed:!1,reason:`Skill is not allowed: ${e.ref??"(missing)"}`}:e.type==="call_tool"&&!i.allowedTools.includes(e.ref??"")?{allowed:!1,reason:`Tool is not allowed: ${e.ref??"(missing)"}`}:e.type==="handoff"&&!i.allowedAgents.includes(e.ref??"")?{allowed:!1,reason:`Agent is not allowed: ${e.ref??"(missing)"}`}:e.ref&&i.confirmationRequiredFor.includes(e.ref)&&!r.has(e.ref)?{allowed:!1,reason:`User confirmation required for: ${e.ref}`}:(t.retries[e.id]??0)>i.maxRetriesPerAction?{allowed:!1,reason:`Retry budget exhausted for action: ${e.id}`}:{allowed:!0}}function Jm(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Reflect.ownKeys(e))Jm(e[t]);return Object.freeze(e)}function Ji(e){return Jm(structuredClone(e))}function cd(e,t,i,r){return e.resolveStep({pkg:Ji(t),state:Ji(i),context:Ji(r)})}function Gm(e,t,i,r,n,a){return e.resolveNext({pkg:Ji(t),state:Ji(i),step:Ji(r),outcome:Ji(n),context:Ji(a)})}function NP(e,t,i){return yP("sha256").update(`${e}:${t}:${i??"adaptive"}`).digest("hex").slice(0,16)}function ld(e,t){return e.definition.orchestration.steps?.find(i=>i.id===t)}function Um(e,t,i,r,n){if(t.status!=="running")return{state:t,action:null,reason:`Run is ${t.status}`};if(t.pending)return{state:t,action:null,reason:`Action already pending: ${t.pending}`};if(t.orchestration==="adaptive")return{state:t,action:null,reason:"Adaptive orchestration requires an Agent candidate"};let a=cd(r,e,t,n);if(!a&&t.currentStep===null)return{state:{...t,status:"completed"},action:null};if(!a)return{state:{...t,status:"failed"},action:null,reason:`Unknown current step: ${t.currentStep}`};let o=ld(e,a.id);if(!o)return{state:{...t,status:"failed"},action:null,reason:`Resolver returned unknown current step: ${a.id}`};let s=t.currentStep===o.id?t:{...t,currentStep:o.id},c={...o.action,id:NP(s.runId,s.iteration,o.id),stepId:o.id};return bP(e,s,c,i)}function bP(e,t,i,r){let n=zm(i,t,e.guardrails,r);return n.allowed?{state:{...t,pending:i.id,status:"waiting"},action:i}:{state:t,action:null,reason:n.reason}}function Km(e,t,i,r,n){if(!t.pending||t.pending!==i.actionId)throw new Error(`Outcome does not match pending action: ${i.actionId}`);let a=t.orchestration==="deterministic"?cd(r,e,t,n):void 0,o=a?ld(e,a.id):void 0;if(t.orchestration==="deterministic"&&!a)throw new Error(`Unknown current step: ${t.currentStep??"(missing)"}`);if(t.orchestration==="deterministic"&&!o)throw new Error(`Resolver returned unknown current step: ${a.id}`);if(i.status==="failed"){let c={...t.retries,[i.actionId]:(t.retries[i.actionId]??0)+1};return{...t,pending:null,status:"running",retries:c}}let s=t.orchestration==="deterministic"?Gm(r,e,t,o,i,n):t.currentStep;if(s!==null&&t.orchestration==="deterministic"&&!ld(e,s))throw new Error(`Resolver returned unknown next step: ${s}`);return{...t,currentStep:s,iteration:t.iteration+1,pending:null,status:s===null&&t.orchestration==="deterministic"?"completed":"running"}}import{promises as ep}from"fs";import fb from"path";var ud={en:{outcome:"Outcome",scope:"Scope",nonGoals:"Non-goals",acceptanceExamples:"Acceptance examples",constraints:"Constraints and invariants",decisions:"Decisions",openQuestions:"Open questions",verificationExpectations:"Verification expectations"},"zh-CN":{outcome:"目标",scope:"范围",nonGoals:"非目标",acceptanceExamples:"验收示例",constraints:"约束与不变量",decisions:"决策",openQuestions:"待解决问题",verificationExpectations:"验证预期"}},Ym={en:{verification:"Verification",currentResult:"Current result",acceptance:"Acceptance",checks:"Checks",blockers:"Blockers",risks:"Risks and skipped work",previousIterations:"Previous iterations",conclusion:"Conclusion"},"zh-CN":{verification:"验证",currentResult:"当前结果",acceptance:"验收",checks:"检查",blockers:"阻塞项",risks:"风险与跳过的工作",previousIterations:"之前的迭代",conclusion:"结论"}},Xm={en:{acceptanceEvidence:"Acceptance evidence",commandsAndResults:"Commands and results",skippedChecks:"Skipped checks",specConsistency:"Spec consistency",knownLimitationsAndRisks:"Known limitations and risks",conclusion:"Conclusion"},"zh-CN":{acceptanceEvidence:"验收证据",commandsAndResults:"命令与结果",skippedChecks:"跳过的检查",specConsistency:"规格一致性",knownLimitationsAndRisks:"已知限制与风险",conclusion:"结论"}},Qm=new Map,dd=new Map;for(let e of Object.keys(ud)){for(let[t,i]of Object.entries(ud[e]))Qm.set(i.toLocaleLowerCase("en-US"),t);for(let[t,i]of Object.entries(Ym[e]))dd.set(i.toLocaleLowerCase("en-US"),t);for(let[t,i]of Object.entries(Xm[e]))dd.set(i.toLocaleLowerCase("en-US"),t)}function kP(e,t){return ud[e][t]}function fd(e,t){return Ym[e][t]??Xm[e][t]}function Gs(e){return Qm.get(e.trim().toLocaleLowerCase("en-US"))??null}function Zm(e){return dd.get(e.trim().toLocaleLowerCase("en-US"))??null}function Us(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(i=>`# ${kP(e,i)}
142
+ `,i)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=Gc(t),r=Vn(i);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let i=Gc(t),r=Vn(i);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,i){return this.type!=="comment"||this.indent<=i?!1:t.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Hw.Parser=Yf});var Bw=C(Po=>{"use strict";var Dw=Df(),HA=vo(),Eo=yo(),DA=$d(),LA=G(),MA=Kf(),Lw=Xf();function Mw(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new MA.LineCounter||null,prettyErrors:t}}function FA(e,t={}){let{lineCounter:i,prettyErrors:r}=Mw(t),n=new Lw.Parser(i?.addNewLine),a=new Dw.Composer(t),o=Array.from(a.compose(n.parse(e)));if(r&&i)for(let s of o)s.errors.forEach(Eo.prettifyError(e,i)),s.warnings.forEach(Eo.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Fw(e,t={}){let{lineCounter:i,prettyErrors:r}=Mw(t),n=new Lw.Parser(i?.addNewLine),a=new Dw.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 Eo.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&i&&(o.errors.forEach(Eo.prettifyError(e,i)),o.warnings.forEach(Eo.prettifyError(e,i))),o}function BA(e,t,i){let r;typeof t=="function"?r=t:i===void 0&&t&&typeof t=="object"&&(i=t);let n=Fw(e,i);if(!n)return null;if(n.warnings.forEach(a=>DA.warn(n.options.logLevel,a)),n.errors.length>0){if(n.options.logLevel!=="silent")throw n.errors[0];n.errors=[]}return n.toJS(Object.assign({reviver:r},i))}function VA(e,t,i){let r=null;if(typeof t=="function"||Array.isArray(t)?r=t:i===void 0&&t&&(i=t),typeof i=="string"&&(i=i.length),typeof i=="number"){let n=Math.round(i);i=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=i??t??{};if(!n)return}return LA.isDocument(e)&&!r?e.toString(i):new HA.Document(e,r,i).toString(i)}Po.parse=BA;Po.parseAllDocuments=FA;Po.parseDocument=Fw;Po.stringify=VA});var en=C(X=>{"use strict";var qA=Df(),WA=vo(),zA=gf(),Qf=yo(),JA=Za(),ar=G(),GA=er(),UA=ke(),KA=ir(),YA=rr(),XA=zc(),QA=Gf(),ZA=Kf(),e_=Xf(),Kc=Bw(),Vw=Ka();X.Composer=qA.Composer;X.Document=WA.Document;X.Schema=zA.Schema;X.YAMLError=Qf.YAMLError;X.YAMLParseError=Qf.YAMLParseError;X.YAMLWarning=Qf.YAMLWarning;X.Alias=JA.Alias;X.isAlias=ar.isAlias;X.isCollection=ar.isCollection;X.isDocument=ar.isDocument;X.isMap=ar.isMap;X.isNode=ar.isNode;X.isPair=ar.isPair;X.isScalar=ar.isScalar;X.isSeq=ar.isSeq;X.Pair=GA.Pair;X.Scalar=UA.Scalar;X.YAMLMap=KA.YAMLMap;X.YAMLSeq=YA.YAMLSeq;X.CST=XA;X.Lexer=QA.Lexer;X.LineCounter=ZA.LineCounter;X.Parser=e_.Parser;X.parse=Kc.parse;X.parseAllDocuments=Kc.parseAllDocuments;X.parseDocument=Kc.parseDocument;X.stringify=Kc.stringify;X.visit=Vw.visit;X.visitAsync=Vw.visitAsync});import{promises as mP}from"node:fs";import dd from"node:path";import{promises as nd}from"fs";import je from"path";import{promises as YS}from"fs";import Fa from"path";import{isDeepStrictEqual as aL}from"util";import{createHash as EP}from"crypto";function Jm(e,t,i,r){return t.iteration>=i.maxIterations?{allowed:!1,reason:`Iteration budget exhausted: ${i.maxIterations}`}:e.type==="invoke_skill"&&!i.allowedSkills.includes(e.ref??"")?{allowed:!1,reason:`Skill is not allowed: ${e.ref??"(missing)"}`}:e.type==="call_tool"&&!i.allowedTools.includes(e.ref??"")?{allowed:!1,reason:`Tool is not allowed: ${e.ref??"(missing)"}`}:e.type==="handoff"&&!i.allowedAgents.includes(e.ref??"")?{allowed:!1,reason:`Agent is not allowed: ${e.ref??"(missing)"}`}:e.ref&&i.confirmationRequiredFor.includes(e.ref)&&!r.has(e.ref)?{allowed:!1,reason:`User confirmation required for: ${e.ref}`}:(t.retries[e.id]??0)>i.maxRetriesPerAction?{allowed:!1,reason:`Retry budget exhausted for action: ${e.id}`}:{allowed:!0}}function Gm(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Reflect.ownKeys(e))Gm(e[t]);return Object.freeze(e)}function Ki(e){return Gm(structuredClone(e))}function hd(e,t,i,r){return e.resolveStep({pkg:Ki(t),state:Ki(i),context:Ki(r)})}function Um(e,t,i,r,n,a){return e.resolveNext({pkg:Ki(t),state:Ki(i),step:Ki(r),outcome:Ki(n),context:Ki(a)})}function PP(e,t,i){return EP("sha256").update(`${e}:${t}:${i??"adaptive"}`).digest("hex").slice(0,16)}function pd(e,t){return e.definition.orchestration.steps?.find(i=>i.id===t)}function Km(e,t,i,r,n){if(t.status!=="running")return{state:t,action:null,reason:`Run is ${t.status}`};if(t.pending)return{state:t,action:null,reason:`Action already pending: ${t.pending}`};if(t.orchestration==="adaptive")return{state:t,action:null,reason:"Adaptive orchestration requires an Agent candidate"};let a=hd(r,e,t,n);if(!a&&t.currentStep===null)return{state:{...t,status:"completed"},action:null};if(!a)return{state:{...t,status:"failed"},action:null,reason:`Unknown current step: ${t.currentStep}`};let o=pd(e,a.id);if(!o)return{state:{...t,status:"failed"},action:null,reason:`Resolver returned unknown current step: ${a.id}`};let s=t.currentStep===o.id?t:{...t,currentStep:o.id},c={...o.action,id:PP(s.runId,s.iteration,o.id),stepId:o.id};return RP(e,s,c,i)}function RP(e,t,i,r){let n=Jm(i,t,e.guardrails,r);return n.allowed?{state:{...t,pending:i.id,status:"waiting"},action:i}:{state:t,action:null,reason:n.reason}}function Ym(e,t,i,r,n){if(!t.pending||t.pending!==i.actionId)throw new Error(`Outcome does not match pending action: ${i.actionId}`);let a=t.orchestration==="deterministic"?hd(r,e,t,n):void 0,o=a?pd(e,a.id):void 0;if(t.orchestration==="deterministic"&&!a)throw new Error(`Unknown current step: ${t.currentStep??"(missing)"}`);if(t.orchestration==="deterministic"&&!o)throw new Error(`Resolver returned unknown current step: ${a.id}`);if(i.status==="failed"){let c={...t.retries,[i.actionId]:(t.retries[i.actionId]??0)+1};return{...t,pending:null,status:"running",retries:c}}let s=t.orchestration==="deterministic"?Um(r,e,t,o,i,n):t.currentStep;if(s!==null&&t.orchestration==="deterministic"&&!pd(e,s))throw new Error(`Resolver returned unknown next step: ${s}`);return{...t,currentStep:s,iteration:t.iteration+1,pending:null,status:s===null&&t.orchestration==="deterministic"?"completed":"running"}}import{promises as ip}from"fs";import hb from"path";var md={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:"验证预期"}},Xm={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:"结论"}},Qm={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:"结论"}},Zm=new Map,vd=new Map;for(let e of Object.keys(md)){for(let[t,i]of Object.entries(md[e]))Zm.set(i.toLocaleLowerCase("en-US"),t);for(let[t,i]of Object.entries(Xm[e]))vd.set(i.toLocaleLowerCase("en-US"),t);for(let[t,i]of Object.entries(Qm[e]))vd.set(i.toLocaleLowerCase("en-US"),t)}function CP(e,t){return md[e][t]}function gd(e,t){return Xm[e][t]??Qm[e][t]}function Ys(e){return Zm.get(e.trim().toLocaleLowerCase("en-US"))??null}function ev(e){return vd.get(e.trim().toLocaleLowerCase("en-US"))??null}function Xs(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(i=>`# ${CP(e,i)}
143
143
  `).join(`
144
- `)}function qt(e,t,i){return e==="zh-CN"?i:t}var Gl=Rn(Qr(),1);import{promises as ib}from"fs";import mi from"path";import{execFileSync as YA}from"child_process";import bo from"path";function rr(e,t){return YA("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function XA(e,t){let i=bo.normalize(e),r=bo.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function fe(e){try{let t=bo.resolve(rr(e,["rev-parse","--show-toplevel"])),r=rr(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=r?bo.resolve(r.slice(9)):t,a=null;try{a=rr(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!XA(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function Vw(e){try{rr(e,["rev-parse","--is-inside-work-tree"]);let t=rr(e,["worktree","list","--porcelain"]).split(/\r?\n/u),i=[],r=null;for(let n of t)n.startsWith("worktree ")?(r&&i.push(r),r={root:bo.resolve(n.slice(9)),branch:null,detached:!1}):r&&n.startsWith("branch refs/heads/")?r.branch=n.slice(18):r&&n==="detached"&&(r.detached=!0);return r&&i.push(r),i}catch{return[]}}function Jt(e){return Vw(e).map(t=>t.root)}function ko(e,t){try{return rr(e,["check-ref-format","--branch",t]),rr(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function xi(e,t){try{let i=rr(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(i)?i:null}catch{return null}}import{createHash as t_}from"node:crypto";import{promises as Gt}from"node:fs";import Ct from"node:path";import{TextDecoder as i_}from"node:util";import Uf from"path";var QA=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),ZA=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function e_(e){return e.toLowerCase().startsWith(".env")}function ci(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>e_(r))?"environment-file":i.some(r=>ZA.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>QA.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function Kf(e,t){let i=ci(t);if(i)return i;let r=Uf.resolve(e.projectRoot,...t.split("/")),n=Uf.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||r===Uf.resolve(e.configFile)?"native-runtime":null}function nr(e){return e!==0&&e!==0n&&e!=="0"}function vt(e,t){return nr(e.dev)&&nr(t.dev)&&nr(e.ino)&&nr(t.ino)}function z(e,t){let i=nr(e.dev)&&nr(t.dev);if(i&&e.dev!==t.dev)return!1;let r=nr(e.ino)&&nr(t.ino);return r&&e.ino!==t.ino?!1:i&&r?!0:e.birthtime===t.birthtime}var So=1024*1024;function Yf(e,t){let i=Ct.relative(e,t);return i===""||!Ct.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ct.sep}`)}function r_(e){let t=Ct.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||Ct.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let i=e.toLowerCase(),r=ci(e);if(r||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${r??"native-runtime"}): ${e}`);return e}function n_(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function a_(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Gc(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return vt(i,r)?z(i,r):z(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function qw(e){let t=await Gt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Gt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function o_(e,t){let i=Ct.resolve(e),r=Ct.resolve(t);if(!Yf(i,r))throw new Error("Native artifact path is outside its root");let n=[await qw(i)],a=i;for(let o of Ct.relative(i,r).split(Ct.sep).filter(Boolean)){a=Ct.join(a,o);let s=await qw(a);if(!Yf(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function Ww(e){for(let t of e){let i=await Gt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!a_(t,i)||await Gt.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function Z(e){let t=r_(e.ref),i=e.maxBytes===null?null:n_(e.maxBytes??So),r=Ct.resolve(e.root,...t.split("/")),n=await o_(e.root,Ct.dirname(r));await e.hooks?.afterParentChainCaptured?.();let a=await Gt.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(i!==null&&a.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);let o=await Gt.realpath(r);if(!Yf(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Gt.open(r,"r");try{let[c,l,u]=await Promise.all([s.stat(),Gt.lstat(r),Gt.realpath(r)]);if(await Ww(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!Gc(a,c)||!Gc(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,h=Buffer.allocUnsafe(i===null?64*1024:Math.min(64*1024,i+1));for(;;){let y=i===null?h.length:i+1-f,E=await s.read(h,0,Math.min(h.length,y),null);if(E.bytesRead===0)break;if(f+=E.bytesRead,i!==null&&f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);d.push(Buffer.from(h.subarray(0,E.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,m,p]=await Promise.all([s.stat(),Gt.lstat(r),Gt.realpath(r)]);if(await Ww(n),!m.isFile()||m.isSymbolicLink()||p!==o||!Gc(c,v)||!Gc(c,m))throw new Error(`Native artifact changed while reading: ${t}`);let b=Buffer.concat(d,f),g;try{g=new i_("utf-8",{fatal:!0}).decode(b)}catch(y){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:y})}return{ref:t,size:f,hash:e.includeHash===!1?null:t_("sha256").update(b).digest("hex"),text:g}}finally{await s.close()}}import{randomUUID as s_}from"crypto";import{promises as Ve}from"fs";import Ut from"path";function Xf(e,t){let i=Ut.relative(e,t);return i===""||!Ut.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ut.sep}`)}function c_(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Qf(e,t){return z({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function l_(e,t){return Qf(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function zw(e){let t=await Ve.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await Ve.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Eo(e){for(let t of e){let i=await Ve.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!c_(t,i)||await Ve.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function u_(e,t){let i=Ut.resolve(e),r=Ut.resolve(t);if(!Xf(i,r))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await zw(i)],a=Ut.relative(i,r).split(Ut.sep).filter(Boolean),o=i;for(let s of a){await Eo(n),o=Ut.join(o,s);try{await Ve.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await zw(o);if(!Xf(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Eo(n),n}async function d_(e){let t;try{t=await Ve.open(e,"r"),await t.sync()}catch(i){let r=i.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(r??""))throw i}finally{await t?.close()}}async function Jw(e,t,i={}){let r=Ut.dirname(e),n=i.containedRoot?await u_(i.containedRoot,r):null;n||await Ve.mkdir(r,{recursive:!0});let a=Ut.join(r,`.${Ut.basename(e)}.${s_()}.tmp`),o,s,c;try{if(await i.beforeTemporaryOpen?.(),o=await Ve.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([Ve.lstat(a),Ve.realpath(a)]);if(await Eo(n),!l.isFile()||l.isSymbolicLink()||!Qf(s,l)||!Xf(n[0].realPath,u))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),c=await o.stat(),!Qf(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await i.beforeCommit?.(),n){await Eo(n);let l=await Ve.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!l_(l,c))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await Ve.link(a,e),await Ve.unlink(a)):await Ve.rename(a,e),await d_(r)}catch(l){if(await o?.close(),!n)await Ve.rm(a,{force:!0});else try{await Eo(n),await Ve.rm(a,{force:!0})}catch{}throw l}}async function he(e,t,i={}){await Jw(e,t,i)}async function Gw(e,t,i={}){await Jw(e,t,i)}async function ee(e,t,i={}){await he(e,JSON.stringify(t,null,2)+`
145
- `,i)}import V_ from"path";var Po=Rn(Qr(),1);import ar from"path";var Ro=64*1024,Kc=1024,Yc=64,Uw=1024,Kw=64,Qw=5,Uc={learning:!0,retrieval:!0},Zw={provider:"local"},f_=12e4,Yw=6e5,h_=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".workbuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".dsh/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".grok/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".omp/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],p_=["**/.idea/**","**/.vscode/**",".codex/skills/**","**/node_modules/**","**/.next/**","**/.nuxt/**","**/.output/**","**/.svelte-kit/**","**/.vite/**","**/.parcel-cache/**","**/.turbo/**","**/.nx/cache/**","**/dist/**","**/build/**","**/out/**","**/coverage/**","**/.nyc_output/**","**/target/**","**/.gradle/**","**/.cxx/**","**/.externalNativeBuild/**","**/captures/**","**/__pycache__/**","**/.pytest_cache/**","**/.mypy_cache/**","**/.ruff_cache/**","**/.tox/**","**/.nox/**","**/.venv/**","**/venv/**","**/obj/**","**/CMakeFiles/**","**/cmake-build-*/**","**/.cache/**","**/tmp/**","**/temp/**","**/logs/**","**/*.tsbuildinfo","**/*.log","**/.DS_Store","**/Thumbs.db"],m_=[...h_,...p_].sort((e,t)=>e.localeCompare(t,"en"));var Kt={include:["**/*"],exclude:[...m_],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},Ln={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it.
144
+ `)}function qt(e,t,i){return e==="zh-CN"?i:t}var Ql=Tn(en(),1);import{promises as rb}from"fs";import mi from"path";import{execFileSync as t_}from"child_process";import Ro from"path";function or(e,t){return t_("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function i_(e,t){let i=Ro.normalize(e),r=Ro.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function fe(e){try{let t=Ro.resolve(or(e,["rev-parse","--show-toplevel"])),r=or(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=r?Ro.resolve(r.slice(9)):t,a=null;try{a=or(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!i_(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function qw(e){try{or(e,["rev-parse","--is-inside-work-tree"]);let t=or(e,["worktree","list","--porcelain"]).split(/\r?\n/u),i=[],r=null;for(let n of t)n.startsWith("worktree ")?(r&&i.push(r),r={root:Ro.resolve(n.slice(9)),branch:null,detached:!1}):r&&n.startsWith("branch refs/heads/")?r.branch=n.slice(18):r&&n==="detached"&&(r.detached=!0);return r&&i.push(r),i}catch{return[]}}function Jt(e){return qw(e).map(t=>t.root)}function Co(e,t){try{return or(e,["check-ref-format","--branch",t]),or(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function Ai(e,t){try{let i=or(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(i)?i:null}catch{return null}}import{createHash as o_}from"node:crypto";import{promises as Gt}from"node:fs";import Ct from"node:path";import{TextDecoder as s_}from"node:util";import Zf from"path";var r_=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),n_=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function a_(e){return e.toLowerCase().startsWith(".env")}function li(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>a_(r))?"environment-file":i.some(r=>n_.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>r_.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function eh(e,t){let i=li(t);if(i)return i;let r=Zf.resolve(e.projectRoot,...t.split("/")),n=Zf.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||r===Zf.resolve(e.configFile)?"native-runtime":null}function sr(e){return e!==0&&e!==0n&&e!=="0"}function vt(e,t){return sr(e.dev)&&sr(t.dev)&&sr(e.ino)&&sr(t.ino)}function z(e,t){let i=sr(e.dev)&&sr(t.dev);if(i&&e.dev!==t.dev)return!1;let r=sr(e.ino)&&sr(t.ino);return r&&e.ino!==t.ino?!1:i&&r?!0:e.birthtime===t.birthtime}var xo=1024*1024;function th(e,t){let i=Ct.relative(e,t);return i===""||!Ct.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ct.sep}`)}function c_(e){let t=Ct.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||Ct.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let i=e.toLowerCase(),r=li(e);if(r||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${r??"native-runtime"}): ${e}`);return e}function l_(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function u_(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Yc(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return vt(i,r)?z(i,r):z(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Ww(e){let t=await Gt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Gt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function d_(e,t){let i=Ct.resolve(e),r=Ct.resolve(t);if(!th(i,r))throw new Error("Native artifact path is outside its root");let n=[await Ww(i)],a=i;for(let o of Ct.relative(i,r).split(Ct.sep).filter(Boolean)){a=Ct.join(a,o);let s=await Ww(a);if(!th(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function zw(e){for(let t of e){let i=await Gt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!u_(t,i)||await Gt.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function Z(e){let t=c_(e.ref),i=e.maxBytes===null?null:l_(e.maxBytes??xo),r=Ct.resolve(e.root,...t.split("/")),n=await d_(e.root,Ct.dirname(r));await e.hooks?.afterParentChainCaptured?.();let a=await Gt.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(i!==null&&a.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);let o=await Gt.realpath(r);if(!th(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Gt.open(r,"r");try{let[c,l,u]=await Promise.all([s.stat(),Gt.lstat(r),Gt.realpath(r)]);if(await zw(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!Yc(a,c)||!Yc(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,h=Buffer.allocUnsafe(i===null?64*1024:Math.min(64*1024,i+1));for(;;){let y=i===null?h.length:i+1-f,E=await s.read(h,0,Math.min(h.length,y),null);if(E.bytesRead===0)break;if(f+=E.bytesRead,i!==null&&f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);d.push(Buffer.from(h.subarray(0,E.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,m,p]=await Promise.all([s.stat(),Gt.lstat(r),Gt.realpath(r)]);if(await zw(n),!m.isFile()||m.isSymbolicLink()||p!==o||!Yc(c,v)||!Yc(c,m))throw new Error(`Native artifact changed while reading: ${t}`);let b=Buffer.concat(d,f),g;try{g=new s_("utf-8",{fatal:!0}).decode(b)}catch(y){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:y})}return{ref:t,size:f,hash:e.includeHash===!1?null:o_("sha256").update(b).digest("hex"),text:g}}finally{await s.close()}}import{randomUUID as f_}from"crypto";import{promises as _e}from"fs";import Ut from"path";function Xc(e,t){let i=Ut.relative(e,t);return i===""||!Ut.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ut.sep}`)}function h_(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Qc(e,t){return z({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function p_(e,t){return Qc(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Jw(e){let t=await _e.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await _e.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function qn(e){for(let t of e){let i=await _e.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!h_(t,i)||await _e.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function m_(e,t,i){let[r,n]=await Promise.all([_e.lstat(e),_e.realpath(e),i?qn(i):Promise.resolve()]);if(!r.isFile()||r.isSymbolicLink()||!Qc(r,t)||i&&!Xc(i[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return r}async function v_(e,t){let i=Ut.resolve(e),r=Ut.resolve(t);if(!Xc(i,r))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await Jw(i)],a=Ut.relative(i,r).split(Ut.sep).filter(Boolean),o=i;for(let s of a){await qn(n),o=Ut.join(o,s);try{await _e.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Jw(o);if(!Xc(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await qn(n),n}async function g_(e){let t;try{t=await _e.open(e,"r"),await t.sync()}catch(i){let r=i.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(r??""))throw i}finally{await t?.close()}}async function Gw(e,t,i={}){let r=Ut.dirname(e),n=i.containedRoot?await v_(i.containedRoot,r):null;n||await _e.mkdir(r,{recursive:!0});let a=Ut.join(r,`.${Ut.basename(e)}.${f_()}.tmp`),o,s,c;try{if(await i.beforeTemporaryOpen?.(),o=await _e.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([_e.lstat(a),_e.realpath(a)]);if(await qn(n),!l.isFile()||l.isSymbolicLink()||!Qc(s,l)||!Xc(n[0].realPath,u))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),c=await o.stat(),!Qc(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await i.afterTemporaryClose?.(),!c)throw new Error("Native atomic write temporary file was not written");if(c=await m_(a,c,n),await i.beforeCommit?.(),n){await qn(n);let l=await _e.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!p_(l,c))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await _e.link(a,e),await _e.unlink(a)):await _e.rename(a,e),await g_(r)}catch(l){if(await o?.close(),!n)await _e.rm(a,{force:!0});else try{await qn(n),await _e.rm(a,{force:!0})}catch{}throw l}}async function he(e,t,i={}){await Gw(e,t,i)}async function Uw(e,t,i={}){await Gw(e,t,i)}async function ee(e,t,i={}){await he(e,JSON.stringify(t,null,2)+`
145
+ `,i)}import U_ from"path";var Ao=Tn(en(),1);import cr from"path";var _o=64*1024,el=1024,tl=64,Kw=1024,Yw=64,Zw=5,Zc={learning:!0,retrieval:!0},ey={provider:"local"},w_=12e4,Xw=6e5,y_=[".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/**"],N_=["**/.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"],b_=[...y_,...N_].sort((e,t)=>e.localeCompare(t,"en"));var Kt={include:["**/*"],exclude:[...b_],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},Wn={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it.
146
146
  # ambient_resume: true | false`,memory:"# Project policy for automatic personal-memory learning and retrieval.","memory.learning":`# Allows workflow events in this project to form new personal memories automatically.
147
147
  # learning: true | false`,"memory.retrieval":`# Allows personal memories to be injected into Agent context for this project.
148
148
  # retrieval: true | false`,knowledge:"# Project knowledge retrieval provider used by ordinary Comet tasks.","knowledge.provider":`# Provider for project knowledge.
@@ -166,48 +166,48 @@ ${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.pus
166
166
  # 可选值:en | zh-CN`,"classic.context_compression":`# 新建 Classic change 是否启用 beta 上下文压缩。
167
167
  # 可选值:off | beta`,"classic.review_mode":`# 新建 Classic change 默认使用的审查深度。
168
168
  # 可选值:off | standard | thorough`,"classic.auto_transition":`# Classic 阶段通过后是否自动进入下一阶段。
169
- # 可选值:true | false`}};function ey(e,t){return Ln[t][e]}function v_(e,t,i,r){let n=/^(\s*)([a-z_]+):/u.exec(e);if(!n)return null;let a=n[1].length,o=n[2];if(a===0&&o in Ln.en)return o;if(a===2&&t){let s=`${t}.${o}`;if(s in Ln.en)return s}if(a===4&&t==="knowledge"&&r==="remote"){let s=`knowledge.remote.${o}`;if(s in Ln.en)return s}if(a===4&&t==="knowledge"&&r==="local"){let s=`knowledge.local.${o}`;if(s in Ln.en)return s}if(a===2&&t===null&&o==="hook")return"hook";if(a===2&&t==="hook"&&o==="allow_paths")return"hook.allow_paths";if(a===4&&t==="native"&&i==="snapshot"){let s=`native.snapshot.${o}`;if(s in Ln.en)return s}return null}function Co(e,t){let i=[],r=null,n=null,a=null;for(let o of(0,Po.stringify)(e).trimEnd().split(`
170
- `)){let s=v_(o,r,n,a);if(s){let c=o.match(/^\s*/u)?.[0]??"";for(let l of ey(s,t).split(`
169
+ # 可选值:true | false`}};function ty(e,t){return Wn[t][e]}function k_(e,t,i,r){let n=/^(\s*)([a-z_]+):/u.exec(e);if(!n)return null;let a=n[1].length,o=n[2];if(a===0&&o in Wn.en)return o;if(a===2&&t){let s=`${t}.${o}`;if(s in Wn.en)return s}if(a===4&&t==="knowledge"&&r==="remote"){let s=`knowledge.remote.${o}`;if(s in Wn.en)return s}if(a===4&&t==="knowledge"&&r==="local"){let s=`knowledge.local.${o}`;if(s in Wn.en)return s}if(a===2&&t===null&&o==="hook")return"hook";if(a===2&&t==="hook"&&o==="allow_paths")return"hook.allow_paths";if(a===4&&t==="native"&&i==="snapshot"){let s=`native.snapshot.${o}`;if(s in Wn.en)return s}return null}function To(e,t){let i=[],r=null,n=null,a=null;for(let o of(0,Ao.stringify)(e).trimEnd().split(`
170
+ `)){let s=k_(o,r,n,a);if(s){let c=o.match(/^\s*/u)?.[0]??"";for(let l of ty(s,t).split(`
171
171
  `))i.push(`${c}${l}`)}i.push(o),/^[a-z_]+:/u.test(o)?(o.startsWith("native:")?r="native":o.startsWith("classic:")?r="classic":o.startsWith("hook:")?r="hook":o.startsWith("memory:")?r="memory":o.startsWith("knowledge:")?r="knowledge":r=null,n=null,a=null):/^ {2}[a-z_]+:/u.test(o)&&(r==="native"&&(n=o.startsWith(" snapshot:")?"snapshot":null),r==="knowledge"&&(a=o.startsWith(" local:")?"local":o.startsWith(" remote:")?"remote":null))}return i.push(""),i.join(`
172
- `)}function g_(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||ar.posix.isAbsolute(i)||ar.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be a project-relative path`);if(i===".")return[];let r=i.replaceAll("\\","/").split("/");if(r.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(r.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return r}function Mn(e){let t=g_(e,"native.artifact_root");return t.length===0?".":t.join("/")}function ty(e,t="docs"){let i=e??t;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function Xc(e,t,i=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim().replaceAll("\\","/");if(r.length===0||ar.posix.isAbsolute(r)||ar.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be relative to its declared path base`);let n=r.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(r))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function Ai(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function iy(e,t,i){let r=e??t;if(r!=="en"&&r!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return r}function Qc(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.startsWith("/")||e.split("/").includes(".."))throw new Error(`${t} contains an unsafe pattern`);if(e.length>Kc)throw new Error(`${t} exceeds ${Kc} characters`);let i=0;for(let r=0;r<e.length;r+=1)e[r]==="?"?i+=1:e[r]==="*"&&(i+=1,e[r+1]==="*"&&(r+=1));if(i>Yc)throw new Error(`${t} contains more than ${Yc} wildcard tokens`);return e}function Xw(e,t,i){if(e===void 0)return[...i];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(r=>Qc(r,t)))].sort((r,n)=>r.localeCompare(n,"en"))}function Zf(e,t,i){let r=e??t;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${i} must be a positive integer`);return r}function w_(e){if(e===void 0)return{...Kt,include:[...Kt.include],exclude:[...Kt.exclude]};let t=Ai(e,"native.snapshot");return{include:Xw(t.include,"native.snapshot.include",Kt.include),exclude:Xw(t.exclude,"native.snapshot.exclude",Kt.exclude),max_files:Zf(t.max_files,Kt.max_files,"native.snapshot.max_files"),max_total_bytes:Zf(t.max_total_bytes,Kt.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Zf(t.max_duration_ms,Kt.max_duration_ms,"native.snapshot.max_duration_ms")}}function y_(e){if(e===void 0)return;let t=Ai(e,"native.pending_root_move"),i=t.id,r=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof i!="string"||!/^[a-f0-9-]{8,}$/u.test(i))throw new Error("native.pending_root_move.id is invalid");if(typeof r!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=Ai(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:i,fromArtifactRoot:Mn(r),toArtifactRoot:Mn(n),stage:a,...o?{cleanup:o}:{}}}function N_(e){if(e===void 0)return;let t=Ai(e,"native.finish");if(t.pull_request===void 0)return{};let i=Ai(t.pull_request,"native.finish.pull_request");if(i.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(i.command)||i.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(i.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let r=i.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(ar.posix.isAbsolute(r[0])||ar.win32.isAbsolute(r[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=i.timeout_ms??f_;if(!Number.isSafeInteger(n)||n<1||n>Yw)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Yw}`);return{pull_request:{provider:"repository-command",command:r,timeout_ms:n}}}function b_(e,t={}){let i=Ai(e,"native"),r=i.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof r!="string")throw new Error("native.artifact_root must be a string");let n=i.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=i.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=i.max_verify_failures??Qw;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=y_(i.pending_root_move),c=N_(i.finish);return{artifact_root:Mn(r),language:iy(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:w_(i.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function k_(e){let t=Ai(e,"classic"),i=t.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let r=t.review_mode??"standard";if(r!=="off"&&r!=="standard"&&r!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:ty(t.artifact_layout),language:iy(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function S_(e){let i=Ai(e,"hook").allow_paths??[];if(!Array.isArray(i))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(i.map((r,n)=>Xc(r,`hook.allow_paths[${n}]`)))]}}function E_(e){if(e===void 0)return{...Uc};let t=Ai(e,"memory"),i=t.learning??Uc.learning,r=t.retrieval??Uc.retrieval;if(typeof i!="boolean")throw new Error("memory.learning must be true or false");if(typeof r!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:i,retrieval:r}}function eh(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function P_(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||i.includes("\\")||i.includes("\0")||ar.posix.isAbsolute(i)||ar.win32.isAbsolute(i)||i.startsWith("~")||i.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!i.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(i.length>Uw)throw new Error(`${t} exceeds ${Uw} characters`);let r=0;for(let n=0;n<i.length;n+=1)i[n]==="?"?r+=1:i[n]==="*"&&(r+=1,i[n+1]==="*"&&(n+=1));if(r>Kw)throw new Error(`${t} contains more than ${Kw} wildcard tokens`);return i}function R_(e){let i=eh(e,"knowledge.local").include??[];if(!Array.isArray(i))throw new Error("knowledge.local.include must be an array");return{include:[...new Set(i.map((r,n)=>P_(r,`knowledge.local.include[${n}]`)))]}}function C_(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let i=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),r=i==="localhost"||i==="127.0.0.1"||i==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&r))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function x_(e){let t=eh(e,"knowledge.remote"),i=C_(t.endpoint),r=t.token_env;if(r!==void 0&&(typeof r!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(r)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:i,...r===void 0?{}:{token_env:r},...n===void 0?{}:{scope:n},timeout_ms:a}}function A_(e){if(e===void 0)return{...Zw};let t=eh(e,"knowledge"),i=t.provider??"local";if(i!=="local"&&i!=="remote")throw new Error("knowledge.provider must be local or remote");let r=t.local===void 0?void 0:R_(t.local);if(i==="local")return{provider:i,...r?{local:r}:{}};let n=t.remote===void 0?void 0:x_(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:i,...r?{local:r}:{},remote:n}}function __(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function T_(e,t,i,r,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let u=e.workflows??[e.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(f=>f!=="native"&&f!=="classic"))throw new Error("workflows must contain native and/or classic");let d=[...new Set(u)];if(!d.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(d.includes("native")&&!n)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:d,ambient_resume:o,...t?{hook:t}:{},memory:i,knowledge:r,...n?{native:n}:{},...a?{classic:a}:{}}}function Fn(e,t={}){let i=(0,Po.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${i.errors[0].message}`);let r=i.toJS();if(r==null)return{value:{},config:null,ambient_resume:!0};if(typeof r!="object"||Array.isArray(r))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=r,a=__(n.ambient_resume),o=n.hook===void 0?void 0:S_(n.hook),s=E_(n.memory),c=A_(n.knowledge),l=n.native===void 0?void 0:b_(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:k_(n.classic),d=T_(n,o,s,c,l,u,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...u?{classic:u}:{}}}function ry(e){return{id:e.id,from_artifact_root:e.fromArtifactRoot,to_artifact_root:e.toArtifactRoot,stage:e.stage,...e.cleanup?{cleanup:{kind:e.cleanup.kind,state:e.cleanup.state,manifest_hash:e.cleanup.manifestHash}}:{}}}function ny(e){let t=e.knowledge??{...Zw};return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,memory:e.memory??{...Uc},knowledge:{provider:t.provider,...t.local&&t.local.include.length>0?{local:{include:[...t.local.include]}}:{},...t.remote?{remote:{endpoint:t.remote.endpoint,timeout_ms:t.remote.timeout_ms,...t.remote.token_env===void 0?{}:{token_env:t.remote.token_env},...t.remote.scope===void 0?{}:{scope:t.remote.scope}}}:{}},...e.hook?{hook:{allow_paths:[...e.hook.allow_paths]}}:{},...e.native?{native:{artifact_root:e.native.artifact_root,language:e.native.language,clarification_mode:e.native.clarification_mode,archive_confirmation:e.native.archive_confirmation,max_verify_failures:e.native.max_verify_failures,...e.native.finish?.pull_request?{finish:{pull_request:{provider:e.native.finish.pull_request.provider,command:[...e.native.finish.pull_request.command],timeout_ms:e.native.finish.pull_request.timeout_ms}}}:{},...e.native.pending_root_move?{pending_root_move:ry(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition}}:{}}}function gt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function xo(e,t){let i=ny(t),r=Fn((0,Po.stringify)(i)).config;if(!r)throw new Error("Unsupported Comet project schema");let n={...e,schema:r.schema,default_workflow:r.default_workflow,workflows:r.workflows,ambient_resume:r.ambient_resume};if(r.hook&&(n.hook={...gt(e.hook),allow_paths:[...r.hook.allow_paths]}),r.memory){let a=gt(e.memory);n.memory={...a,learning:r.memory.learning,retrieval:r.memory.retrieval}}if(r.knowledge){let a=gt(e.knowledge),o={...a,provider:r.knowledge.provider};if(r.knowledge.local&&r.knowledge.local.include.length>0?o.local={...gt(a.local),include:[...r.knowledge.local.include]}:delete o.local,r.knowledge.remote){let c={...gt(a.remote),endpoint:r.knowledge.remote.endpoint,timeout_ms:r.knowledge.remote.timeout_ms,...r.knowledge.remote.token_env===void 0?{}:{token_env:r.knowledge.remote.token_env},...r.knowledge.remote.scope===void 0?{}:{scope:r.knowledge.remote.scope}};r.knowledge.remote.token_env===void 0&&delete c.token_env,r.knowledge.remote.scope===void 0&&delete c.scope,o.remote=c}else delete o.remote;n.knowledge=o}if(r.native){let a=gt(e.native),o={...a,artifact_root:r.native.artifact_root,language:r.native.language,clarification_mode:r.native.clarification_mode,archive_confirmation:r.native.archive_confirmation,max_verify_failures:r.native.max_verify_failures};if(r.native.finish?.pull_request){let s=gt(a.finish);o.finish={...s,pull_request:{...gt(s.pull_request),provider:r.native.finish.pull_request.provider,command:[...r.native.finish.pull_request.command],timeout_ms:r.native.finish.pull_request.timeout_ms}}}else{let s={...gt(a.finish)};delete s.pull_request,Object.keys(s).length>0?o.finish=s:delete o.finish}if(delete o.snapshot,r.native.pending_root_move){let s=gt(a.pending_root_move),c=ry(r.native.pending_root_move),l=gt(s.cleanup),u=gt(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...u}}:{}}}else delete o.pending_root_move;n.native=o}return r.classic&&(n.classic={...gt(e.classic),artifact_layout:r.classic.artifact_layout,language:r.classic.language,context_compression:r.classic.context_compression,review_mode:r.classic.review_mode,auto_transition:r.classic.auto_transition}),n}import{createHash as j_}from"crypto";import{promises as tl}from"fs";import or from"path";import{constants as Zc,promises as Zr}from"fs";var Yt=class extends Error{reason;constructor(t,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=t}};function th(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function ay(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function Ao(e){return{dev:e.dev,ino:e.ino,birthtime:th(e)}}function el(e,t){let i=Ao(e),r=Ao(t);return vt(i,r)?z(i,r):z(i,r)&&th(e)===th(t)&&ay(e)===ay(t)&&e.size===t.size}async function en(e,t,i={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let r=i.label??"file",n=i.bigint===!0,a=await Zr.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Yt("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Yt("too-large",`${r} exceeds ${t} bytes`);let o=await Zr.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:Ao(a)});let s=process.platform==="win32"?Zc.O_RDONLY:Zc.O_RDONLY|Zc.O_NOFOLLOW|Zc.O_NONBLOCK,c;try{c=await Zr.open(e,s)}catch(l){throw l.code==="ELOOP"?new Yt("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),Zr.lstat(e,{bigint:n}),Zr.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!el(a,l)||!el(a,u))throw new Yt("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:Ao(l)}),await i.hooks?.afterOpen?.();let f=[],h=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let g=t+1-h,{bytesRead:y}=await c.read(v,0,Math.min(v.length,g),null);if(y===0)break;if(h+=y,h>t)throw new Yt("too-large",`${r} exceeds ${t} bytes`);f.push(Buffer.from(v.subarray(0,y)))}await i.hooks?.beforeFinalCheck?.();let[m,p,b]=await Promise.all([c.stat({bigint:n}),Zr.lstat(e,{bigint:n}),Zr.realpath(e)]);if(!p.isFile()||p.isSymbolicLink()||b!==o||!el(a,m)||!el(a,p))throw new Yt("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:b,identity:Ao(m)}),{bytes:Buffer.concat(f,h),stat:m,realPath:b}}finally{await c.close()}}function I_(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function ih(e,t){let i=or.relative(e,t);return i===""||!or.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${or.sep}`)}async function oy(e,t){let i=or.resolve(e),r=await tl.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return tl.realpath(i)}async function sy(e,t,i,r){let n=e;for(let a=0;a<i.length;a++){n=or.join(n,i[a]);let o;try{o=await tl.lstat(n)}catch(u){if(I_(u))return{exists:!1,kind:"missing"};throw u}let s=or.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${r.label} crosses a symbolic link or junction at ${s}`);let c=a===i.length-1;if(!c&&!o.isDirectory())throw new Error(`${r.label} ancestor ${s} must be a real directory`);if(c&&(r.expected==="file"&&!o.isFile()||r.expected==="directory"&&!o.isDirectory()||r.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${r.label} must be a real ${r.expected}`);let l=await tl.realpath(n);if(!ih(t,l))throw new Error(`${r.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function Bn(e,t,i){let r=Xc(t,i.label),n=or.resolve(e),a=await oy(n,i.label),o=r.split("/"),s=or.resolve(n,...o);if(!ih(n,s))throw new Error(`${i.label} must stay inside the project root`);let c=await sy(n,a,o,i);return{projectRoot:n,target:s,relative:r,exists:c.exists,kind:c.kind}}async function sr(e,t,i,r){let n=await Bn(e,t,{label:r.label,expected:"file"});if(!n.exists){let o=new Error(`${r.label} does not exist`);throw o.code="ENOENT",o}let a=await oy(n.projectRoot,r.label);return en(n.target,i,{...r,verify:async(o,s)=>{if(!ih(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await sy(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var _o=".comet/config.yaml";function rh(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function $_(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function il(e,t={}){return(await To(e,t)).document}async function cy(e){try{return(await sr(e,_o,Ro,{label:_o})).bytes}catch(t){if($_(t))return null;throw t}}function ly(e){return e?{exists:!0,sha256:j_("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function rl(e){return ly(await cy(e))}async function To(e,t={}){let i=await cy(e);return{document:i?Fn(i.toString("utf8"),t):null,identity:ly(i)}}async function nh(e){return(await il(e))?.config??null}var qV=16*1024;async function ah(e,t){if(!t)return;let i=await rl(e);if(!rh(i,t))throw new Error("Project config changed before commit; rerun the operation")}import{existsSync as uy,promises as cr}from"fs";import K from"path";import L_ from"os";var nl=".comet/config.yaml",M_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function oh(e){try{return await cr.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function F_(e){try{let t=await cr.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function qn(e,t){let i=K.relative(e,t);return i===""||!K.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${K.sep}`)}async function Vn(e){let t=[],i=e;for(;!await oh(i);){let n=K.dirname(i);if(n===i)break;t.push(K.basename(i)),i=n}let r=await cr.realpath(i);return K.resolve(r,...t.reverse())}async function sh(e){try{return(await cr.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function ch(e){let t=K.resolve(e);try{(await cr.stat(t)).isDirectory()||(t=K.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let i=t,r=K.resolve(L_.homedir());for(;;){if(!(t===r&&i!==r)){let o=K.join(t,...nl.split("/")),s=t===i||await F_(o);if(await oh(o)&&s)return t}if(await oh(K.join(t,".git")))return t;let a=K.dirname(t);if(a===t)return i;t=a}}function al(e){return Mn(e)}async function B_(e,t){let i=al(t),r=K.resolve(e,...i.split("/")),n=await cr.realpath(e),a=await Vn(r);if(!qn(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function qe(e,t){let i=al(t),r=await B_(e,i),n=K.join(r,"comet");if(await sh(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Vn(r),Vn(n)]);if(!qn(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=K.resolve(e),c=K.join(s,".comet","runtime","native");if(await sh(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([cr.realpath(s),Vn(c)]);if(!qn(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:K.join(e,...nl.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:K.join(n,"specs"),changesDir:K.join(n,"changes"),archiveDir:K.join(n,"archive"),runtimeDir:c,changesRuntimeDir:K.join(c,"changes"),locksDir:K.join(c,"locks"),transactionsDir:K.join(c,"transactions")}}function fy(e){if(!M_.test(e))throw new Error(`Invalid Native change name: ${e}`)}function We(e,t){fy(t);let i=K.join(e.changesRuntimeDir,t);if(!O(e.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function tn(e,t){fy(t);let i=K.join(e.changesDir,t,"runtime");if(!O(e.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function H(e,t){let i=We(e,t);if(uy(i))return i;let r=tn(e,t);return uy(r)?r:i}async function dy(e){try{let t=await cr.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function jo(e,t){let i=We(e,t),r=tn(e,t),[n,a]=await Promise.all([dy(i),dy(r)]);return n==="invalid"?{status:"invalid",layout:"project-local",path:i,message:"Native Runtime path must be a real directory"}:a==="invalid"?{status:"invalid",layout:"legacy",path:r,message:"Legacy Native Runtime path must be a real directory"}:n==="directory"&&a==="directory"?{status:"invalid",layout:"project-local",path:i,message:"Both project-local and legacy Native Runtime directories exist"}:n==="directory"?{status:"available",layout:"project-local",path:i}:a==="directory"?{status:"available",layout:"legacy",path:r}:{status:"missing",layout:"missing",path:i}}function lr(e,t){if(!t.startsWith("runtime/")||K.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let i=K.resolve(e,...t.slice(8).split("/"));if(!O(e,i))throw new Error(`Native Runtime ref escaped: ${t}`);return i}function j(e,t){let i=K.resolve(t);if(O(e.runtimeDir,i))return e.runtimeDir;if(O(e.nativeRoot,i))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function O(e,t){return qn(K.resolve(e),K.resolve(t))}async function T(e,t){let i=K.resolve(e),r=K.resolve(t);if(!qn(i,r))throw new Error(`Path is outside the Native root: ${t}`);if(await sh(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Vn(i),Vn(r)]);if(!qn(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return r}var lh=Kt;var ol=Qc;async function ye(e){let t=(await il(e))?.config??null;return t?.native?t:null}async function Wn(e){let t=await ye(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function ur(e,t,i={}){let r=await To(e,{allowPartialProject:!0}),n=xo(r.document?.value??{},t),a=V_.join(e,...nl.split("/"));await he(a,Co(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await i.beforeCommit?.(),await ah(e,r.identity)}})}import{promises as MI}from"fs";import FI from"path";import{AsyncLocalStorage as q_}from"async_hooks";import{randomUUID as vy}from"crypto";import{promises as xt}from"fs";import gy from"os";import pe from"path";var py=16*1024,uh=".coordinator",W_=5e3,my=new q_,sl=new Map;function z_(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function J_(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let i=e;if(typeof i.id!="string"||i.id.length===0||typeof i.pid!="number"||!Number.isSafeInteger(i.pid)||i.pid<1||typeof i.hostname!="string"||i.hostname.length===0||typeof i.createdAt!="string"||i.createdAt.length===0||typeof i.operation!="string"||i.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return i}function wy(e){return{device:e.dev.toString(),inode:e.ino.toString(),size:e.size.toString(),birthtimeNs:e.birthtimeNs.toString(),ctimeNs:e.ctimeNs.toString(),mtimeNs:e.mtimeNs.toString()}}function dh(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},r={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return vt(i,r)?z(i,r):z(i,r)&&e.size===t.size}function cl(e,t){return dh(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function G_(e,t){return e.status!==t.status?!1:!e.owner||!e.identity||!t.owner||!t.identity?e.owner===t.owner&&e.identity===t.identity:e.owner.id===t.owner.id&&cl(e.identity,t.identity)}async function li(e){let t,i;try{let r=await en(e,py,{bigint:!0,label:"Native lock"});t=r.bytes,i=r.stat}catch(r){if(r.code==="ENOENT")return null;throw r instanceof Yt?r.reason==="too-large"?new Error(`Native lock metadata exceeds ${py} bytes: ${e}`,{cause:r}):r.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:r}):new Error(`Native lock changed while reading: ${e}`,{cause:r}):r}return{file:e,owner:J_(JSON.parse(t.toString("utf8")),e),identity:wy(i)}}async function U_(e){return(await li(e))?.owner??null}function fh(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==gy.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=eT(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function K_(e,t){try{await xt.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await xt.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function ll(e,t){let i=await li(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!cl(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await xt.mkdir(t,{recursive:!0});let r=pe.join(t,`${pe.basename(e.file)}.${e.owner.id}.${vy()}.removed`);try{await xt.rename(e.file,r)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await li(r);if(!n||n.owner.id!==e.owner.id||!dh(n.identity,e.identity))throw await K_(r,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await xt.rm(r,{force:!0}),"removed"}function yy(e){return{id:vy(),pid:process.pid,hostname:gy.hostname(),createdAt:new Date().toISOString(),operation:e}}async function Ny(e,t){let i;try{i=await xt.open(e,"wx")}catch(r){if(r.code==="EEXIST"){let n=await U_(e);throw new Error(`Native lock is already held: ${e}${n?` by pid ${n.pid} for ${n.operation}`:""}`,{cause:r})}throw r}try{return await i.writeFile(JSON.stringify(t,null,2)+`
173
- `,"utf8"),await i.sync(),wy(await i.stat({bigint:!0}))}finally{await i.close()}}async function Y_(e,t){let i=await T(e.runtimeDir,e.locksDir);await xt.mkdir(i,{recursive:!0});let r=await T(e.runtimeDir,pe.join(i,uh));await xt.mkdir(r,{recursive:!0});let n=yy(t),a=pe.join(r,`.${n.id}.tmp`),o=pe.join(r,`${n.id}.claim`);try{let s=await Ny(a,n);await xt.rename(a,o);let c=await li(o);if(!c||!dh(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:i,owner:n,identity:c.identity}}finally{await xt.rm(a,{force:!0})}}async function X_(e){let t=pe.dirname(e.file),i=!1,r=pe.basename(e.file);for(let n of await xt.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=pe.join(t,n.name);if(pe.resolve(a)!==pe.resolve(e.file))try{let o=await li(a),s=fh(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await ll(o,t);continue}n.name<r&&(i=!0)}catch{n.name<r&&(i=!0)}}return i}async function by(e){let t=await li(e.file);if(t){if(t.owner.id!==e.owner.id||!cl(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await ll(t,pe.dirname(e.file))}}async function Q_(e,t){let i=Date.now()+W_;for(;;){let r=await Y_(e,t);if(!await X_(r))return r;if(await by(r),Date.now()>=i)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function Z_(e){let t=sl.get(e)??Promise.resolve(),i,r=new Promise(a=>{i=a}),n=t.then(()=>r);return sl.set(e,n),await t,()=>{i(),sl.get(e)===n&&sl.delete(e)}}async function ul(e,t,i){let r=pe.resolve(e.locksDir),n=my.getStore();if(n?.has(r))return i();let a=await Z_(r);try{let o=await Q_(e,t),s=new Map(n??[]);return s.set(r,o),await my.run(s,async()=>{try{return await i()}finally{await by(o)}})}finally{a()}}async function zn(e,t,i){let r=[...new Map(e.map(a=>[pe.resolve(a.locksDir),a])).values()].sort((a,o)=>pe.resolve(a.locksDir).localeCompare(pe.resolve(o.locksDir))),n=async a=>{let o=r[a];return o?ul(o,t,()=>n(a+1)):i()};return n(0)}async function dr(e,t,i){return ul(e,`acquire ${t}`,async()=>{let r=await T(e.runtimeDir,e.locksDir);await xt.mkdir(r,{recursive:!0});let n=await T(e.runtimeDir,pe.join(r,z_(t))),a=yy(i),o=await Ny(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:r,owner:a,identity:o}})}async function fr(e){await li(e.file)&&await ul({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${pe.basename(e.file)}`,async()=>{let t=await li(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!cl(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=pe.join(e.locksDir,uh);await ll(t,i)})}function eT(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function $o(e){return fh(await li(e))}async function hh(e,t,i){return ul(e,`take over ${pe.basename(t)}`,async()=>{let r=await T(e.runtimeDir,e.locksDir),n=await T(e.runtimeDir,t);if(pe.resolve(pe.dirname(n))!==pe.resolve(r))throw new Error(`Native lock takeover target is outside the lock directory: ${t}`);let a=await li(n),o=fh(a);if(o.status==="missing")return{status:"missing"};if(i&&!G_(i,o))return{status:"changed",diagnosis:o};if(o.status!=="stale"||!a)return{status:"changed",diagnosis:o};let s=pe.join(r,uh);return await ll(a,s)==="removed"?{status:"removed",owner:a.owner}:{status:"missing"}})}import{promises as oI}from"node:fs";import Eh from"node:path";import zT from"node:path";import Iy from"node:path";import ky from"node:path";import{createHash as tT}from"crypto";function Xt(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function iT(e,t){t.has(e)&&Xt("cyclic structures are not supported"),t.add(e);try{let i=Object.keys(e);for(let r=0;r<e.length;r+=1)Object.prototype.hasOwnProperty.call(e,r)||Xt("sparse arrays are not supported");return(i.length!==e.length||i.some((r,n)=>r!==String(n)))&&Xt("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&Xt("symbol properties are not supported"),`[${e.map(r=>ph(r,t)).join(",")}]`}finally{t.delete(e)}}function rT(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&Xt("only plain objects are supported"),t.has(e)&&Xt("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&Xt("symbol properties are not supported"),t.add(e);try{let r=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=r[o];return(!s||!("value"in s))&&Xt("accessor properties are not supported"),`${JSON.stringify(o)}:${ph(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function ph(e,t){if(e===null)return"null";switch(typeof e){case"boolean":return e?"true":"false";case"string":return JSON.stringify(e);case"number":return Number.isFinite(e)||Xt("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?iT(e,t):rT(e,t);case"bigint":case"function":case"symbol":case"undefined":return Xt(`${typeof e} values are not supported`)}return Xt("unsupported value type")}function Oo(e){return ph(e,new Set)}function D(e,t){if(e.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(e))throw new TypeError("Canonical hash tag must not contain a line break");return tT("sha256").update(`${e}
174
- ${Oo(t)}`).digest("hex")}var nT="comet.native.acceptance.v1",aT=/^acceptance-[a-f0-9]{64}$/u,oT=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),sT=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,cT=/^[a-f0-9]{64}$/u,lT=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function uT(e,t){return e<t?-1:e>t?1:0}var _i=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Do=Object.freeze({maxCriteria:1024}),Sy="<!-- comet-native:acceptance-evidence:start -->",Ey="<!-- comet-native:acceptance-evidence:end -->";function Py(e,t){if(Buffer.byteLength(e,"utf8")<=t)return{value:e,truncated:!1};let i="",r=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(r+a>t)break;i+=n,r+=a}return{value:i,truncated:!0}}function Ry(e,t){let i=t.toString(36),r=D("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${i}.${r}`}function dT(e){if(!cT.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=lT.exec(e.cursor);if(!t)throw new Error("Native acceptance cursor is invalid");if(t[1]!==e.acceptanceHash)throw new Error("Native acceptance cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native acceptance cursor offset is invalid");if(t[3]!==D("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:i}))throw new Error("Native acceptance cursor integrity check failed");return i}function fT(e,t){let i=Py(e.text,_i.maxTextBytes),r=e.context.slice(0,_i.maxContextItems).map(n=>Py(n,_i.maxContextItemBytes));return{id:e.id,kind:e.kind,source:e.source,context:r.map(n=>n.value),text:i.value,contextTruncated:e.context.length>r.length||r.some(n=>n.truncated),textTruncated:i.truncated,verificationStatus:t}}function xy(e){let t=dT({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),i=[],r=[...new Set(e.failedCheckIds??[])].sort(uT),n=r.slice(0,_i.maxFailedCheckIds),a=e.criteria.slice(t,t+_i.maxItems);for(let c of a){let l=[...i,fT(c,e.verificationStatuses?.get(c.id)??"unverified")],u=t+l.length,d={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:l,failedAcceptanceIds:l.filter(f=>f.verificationStatus==="failed").map(f=>f.id),missingAcceptanceIds:l.filter(f=>f.verificationStatus==="missing").map(f=>f.id),failedCheckIds:n,failedCheckIdsTruncated:r.length>n.length,nextCursor:u<e.criteria.length?Ry(e.acceptanceHash,u):null,limits:{..._i}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>_i.maxSerializedBytes){if(i.length===0)throw new Error("Native acceptance criterion exceeds the page serialization budget");break}i.push(l.at(-1))}if(e.criteria.length>0&&i.length===0)throw new Error("Native acceptance page could not project its next criterion");let o=t+i.length,s={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:i,failedAcceptanceIds:i.filter(c=>c.verificationStatus==="failed").map(c=>c.id),missingAcceptanceIds:i.filter(c=>c.verificationStatus==="missing").map(c=>c.id),failedCheckIds:n,failedCheckIdsTruncated:r.length>n.length,nextCursor:o<e.criteria.length?Ry(e.acceptanceHash,o):null,limits:{..._i}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>_i.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function vh(e){let t=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(e);return t?{level:t[1].length,text:t[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function mh(e,t){let i=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!i)return t;let r=i[1][0];return t===null?{marker:r,length:i[1].length}:r===t.marker&&i[1].length>=t.length&&i[2].trim().length===0?null:t}function Cy(e){return e.includes("-->")||e.includes("--!>")}function*Jn(e){let t=null,i=!1,r=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
172
+ `)}function S_(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||cr.posix.isAbsolute(i)||cr.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be a project-relative path`);if(i===".")return[];let r=i.replaceAll("\\","/").split("/");if(r.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(r.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return r}function zn(e){let t=S_(e,"native.artifact_root");return t.length===0?".":t.join("/")}function iy(e,t="docs"){let i=e??t;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function il(e,t,i=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim().replaceAll("\\","/");if(r.length===0||cr.posix.isAbsolute(r)||cr.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be relative to its declared path base`);let n=r.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(r))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function _i(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function ry(e,t,i){let r=e??t;if(r!=="en"&&r!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return r}function rl(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>el)throw new Error(`${t} exceeds ${el} characters`);let i=0;for(let r=0;r<e.length;r+=1)e[r]==="?"?i+=1:e[r]==="*"&&(i+=1,e[r+1]==="*"&&(r+=1));if(i>tl)throw new Error(`${t} contains more than ${tl} wildcard tokens`);return e}function Qw(e,t,i){if(e===void 0)return[...i];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(r=>rl(r,t)))].sort((r,n)=>r.localeCompare(n,"en"))}function ih(e,t,i){let r=e??t;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${i} must be a positive integer`);return r}function E_(e){if(e===void 0)return{...Kt,include:[...Kt.include],exclude:[...Kt.exclude]};let t=_i(e,"native.snapshot");return{include:Qw(t.include,"native.snapshot.include",Kt.include),exclude:Qw(t.exclude,"native.snapshot.exclude",Kt.exclude),max_files:ih(t.max_files,Kt.max_files,"native.snapshot.max_files"),max_total_bytes:ih(t.max_total_bytes,Kt.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:ih(t.max_duration_ms,Kt.max_duration_ms,"native.snapshot.max_duration_ms")}}function P_(e){if(e===void 0)return;let t=_i(e,"native.pending_root_move"),i=t.id,r=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof i!="string"||!/^[a-f0-9-]{8,}$/u.test(i))throw new Error("native.pending_root_move.id is invalid");if(typeof r!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=_i(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:i,fromArtifactRoot:zn(r),toArtifactRoot:zn(n),stage:a,...o?{cleanup:o}:{}}}function R_(e){if(e===void 0)return;let t=_i(e,"native.finish");if(t.pull_request===void 0)return{};let i=_i(t.pull_request,"native.finish.pull_request");if(i.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(i.command)||i.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(i.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let r=i.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(cr.posix.isAbsolute(r[0])||cr.win32.isAbsolute(r[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=i.timeout_ms??w_;if(!Number.isSafeInteger(n)||n<1||n>Xw)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Xw}`);return{pull_request:{provider:"repository-command",command:r,timeout_ms:n}}}function C_(e,t={}){let i=_i(e,"native"),r=i.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof r!="string")throw new Error("native.artifact_root must be a string");let n=i.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=i.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=i.max_verify_failures??Zw;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=P_(i.pending_root_move),c=R_(i.finish);return{artifact_root:zn(r),language:ry(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:E_(i.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function x_(e){let t=_i(e,"classic"),i=t.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let r=t.review_mode??"standard";if(r!=="off"&&r!=="standard"&&r!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:iy(t.artifact_layout),language:ry(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function A_(e){let i=_i(e,"hook").allow_paths??[];if(!Array.isArray(i))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(i.map((r,n)=>il(r,`hook.allow_paths[${n}]`)))]}}function __(e){if(e===void 0)return{...Zc};let t=_i(e,"memory"),i=t.learning??Zc.learning,r=t.retrieval??Zc.retrieval;if(typeof i!="boolean")throw new Error("memory.learning must be true or false");if(typeof r!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:i,retrieval:r}}function rh(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function T_(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||i.includes("\\")||i.includes("\0")||cr.posix.isAbsolute(i)||cr.win32.isAbsolute(i)||i.startsWith("~")||i.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!i.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(i.length>Kw)throw new Error(`${t} exceeds ${Kw} characters`);let r=0;for(let n=0;n<i.length;n+=1)i[n]==="?"?r+=1:i[n]==="*"&&(r+=1,i[n+1]==="*"&&(n+=1));if(r>Yw)throw new Error(`${t} contains more than ${Yw} wildcard tokens`);return i}function I_(e){let i=rh(e,"knowledge.local").include??[];if(!Array.isArray(i))throw new Error("knowledge.local.include must be an array");return{include:[...new Set(i.map((r,n)=>T_(r,`knowledge.local.include[${n}]`)))]}}function j_(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let i=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),r=i==="localhost"||i==="127.0.0.1"||i==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&r))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function $_(e){let t=rh(e,"knowledge.remote"),i=j_(t.endpoint),r=t.token_env;if(r!==void 0&&(typeof r!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(r)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:i,...r===void 0?{}:{token_env:r},...n===void 0?{}:{scope:n},timeout_ms:a}}function O_(e){if(e===void 0)return{...ey};let t=rh(e,"knowledge"),i=t.provider??"local";if(i!=="local"&&i!=="remote")throw new Error("knowledge.provider must be local or remote");let r=t.local===void 0?void 0:I_(t.local);if(i==="local")return{provider:i,...r?{local:r}:{}};let n=t.remote===void 0?void 0:$_(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:i,...r?{local:r}:{},remote:n}}function H_(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function D_(e,t,i,r,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let u=e.workflows??[e.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(f=>f!=="native"&&f!=="classic"))throw new Error("workflows must contain native and/or classic");let d=[...new Set(u)];if(!d.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(d.includes("native")&&!n)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:d,ambient_resume:o,...t?{hook:t}:{},memory:i,knowledge:r,...n?{native:n}:{},...a?{classic:a}:{}}}function Jn(e,t={}){let i=(0,Ao.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${i.errors[0].message}`);let r=i.toJS();if(r==null)return{value:{},config:null,ambient_resume:!0};if(typeof r!="object"||Array.isArray(r))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=r,a=H_(n.ambient_resume),o=n.hook===void 0?void 0:A_(n.hook),s=__(n.memory),c=O_(n.knowledge),l=n.native===void 0?void 0:C_(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:x_(n.classic),d=D_(n,o,s,c,l,u,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...u?{classic:u}:{}}}function ny(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 ay(e){let t=e.knowledge??{...ey};return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,memory:e.memory??{...Zc},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:ny(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition}}:{}}}function gt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Io(e,t){let i=ay(t),r=Jn((0,Ao.stringify)(i)).config;if(!r)throw new Error("Unsupported Comet project schema");let n={...e,schema:r.schema,default_workflow:r.default_workflow,workflows:r.workflows,ambient_resume:r.ambient_resume};if(r.hook&&(n.hook={...gt(e.hook),allow_paths:[...r.hook.allow_paths]}),r.memory){let a=gt(e.memory);n.memory={...a,learning:r.memory.learning,retrieval:r.memory.retrieval}}if(r.knowledge){let a=gt(e.knowledge),o={...a,provider:r.knowledge.provider};if(r.knowledge.local&&r.knowledge.local.include.length>0?o.local={...gt(a.local),include:[...r.knowledge.local.include]}:delete o.local,r.knowledge.remote){let c={...gt(a.remote),endpoint:r.knowledge.remote.endpoint,timeout_ms:r.knowledge.remote.timeout_ms,...r.knowledge.remote.token_env===void 0?{}:{token_env:r.knowledge.remote.token_env},...r.knowledge.remote.scope===void 0?{}:{scope:r.knowledge.remote.scope}};r.knowledge.remote.token_env===void 0&&delete c.token_env,r.knowledge.remote.scope===void 0&&delete c.scope,o.remote=c}else delete o.remote;n.knowledge=o}if(r.native){let a=gt(e.native),o={...a,artifact_root:r.native.artifact_root,language:r.native.language,clarification_mode:r.native.clarification_mode,archive_confirmation:r.native.archive_confirmation,max_verify_failures:r.native.max_verify_failures};if(r.native.finish?.pull_request){let s=gt(a.finish);o.finish={...s,pull_request:{...gt(s.pull_request),provider:r.native.finish.pull_request.provider,command:[...r.native.finish.pull_request.command],timeout_ms:r.native.finish.pull_request.timeout_ms}}}else{let s={...gt(a.finish)};delete s.pull_request,Object.keys(s).length>0?o.finish=s:delete o.finish}if(delete o.snapshot,r.native.pending_root_move){let s=gt(a.pending_root_move),c=ny(r.native.pending_root_move),l=gt(s.cleanup),u=gt(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...u}}:{}}}else delete o.pending_root_move;n.native=o}return r.classic&&(n.classic={...gt(e.classic),artifact_layout:r.classic.artifact_layout,language:r.classic.language,context_compression:r.classic.context_compression,review_mode:r.classic.review_mode,auto_transition:r.classic.auto_transition}),n}import{createHash as M_}from"crypto";import{promises as ol}from"fs";import lr from"path";import{constants as nl,promises as tn}from"fs";var Yt=class extends Error{reason;constructor(t,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=t}};function nh(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function oy(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function jo(e){return{dev:e.dev,ino:e.ino,birthtime:nh(e)}}function al(e,t){let i=jo(e),r=jo(t);return vt(i,r)?z(i,r):z(i,r)&&nh(e)===nh(t)&&oy(e)===oy(t)&&e.size===t.size}async function rn(e,t,i={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let r=i.label??"file",n=i.bigint===!0,a=await tn.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Yt("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Yt("too-large",`${r} exceeds ${t} bytes`);let o=await tn.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:jo(a)});let s=process.platform==="win32"?nl.O_RDONLY:nl.O_RDONLY|nl.O_NOFOLLOW|nl.O_NONBLOCK,c;try{c=await tn.open(e,s)}catch(l){throw l.code==="ELOOP"?new Yt("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),tn.lstat(e,{bigint:n}),tn.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!al(a,l)||!al(a,u))throw new Yt("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:jo(l)}),await i.hooks?.afterOpen?.();let f=[],h=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let g=t+1-h,{bytesRead:y}=await c.read(v,0,Math.min(v.length,g),null);if(y===0)break;if(h+=y,h>t)throw new Yt("too-large",`${r} exceeds ${t} bytes`);f.push(Buffer.from(v.subarray(0,y)))}await i.hooks?.beforeFinalCheck?.();let[m,p,b]=await Promise.all([c.stat({bigint:n}),tn.lstat(e,{bigint:n}),tn.realpath(e)]);if(!p.isFile()||p.isSymbolicLink()||b!==o||!al(a,m)||!al(a,p))throw new Yt("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:b,identity:jo(m)}),{bytes:Buffer.concat(f,h),stat:m,realPath:b}}finally{await c.close()}}function L_(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function ah(e,t){let i=lr.relative(e,t);return i===""||!lr.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${lr.sep}`)}async function sy(e,t){let i=lr.resolve(e),r=await ol.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return ol.realpath(i)}async function cy(e,t,i,r){let n=e;for(let a=0;a<i.length;a++){n=lr.join(n,i[a]);let o;try{o=await ol.lstat(n)}catch(u){if(L_(u))return{exists:!1,kind:"missing"};throw u}let s=lr.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${r.label} crosses a symbolic link or junction at ${s}`);let c=a===i.length-1;if(!c&&!o.isDirectory())throw new Error(`${r.label} ancestor ${s} must be a real directory`);if(c&&(r.expected==="file"&&!o.isFile()||r.expected==="directory"&&!o.isDirectory()||r.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${r.label} must be a real ${r.expected}`);let l=await ol.realpath(n);if(!ah(t,l))throw new Error(`${r.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function Gn(e,t,i){let r=il(t,i.label),n=lr.resolve(e),a=await sy(n,i.label),o=r.split("/"),s=lr.resolve(n,...o);if(!ah(n,s))throw new Error(`${i.label} must stay inside the project root`);let c=await cy(n,a,o,i);return{projectRoot:n,target:s,relative:r,exists:c.exists,kind:c.kind}}async function ur(e,t,i,r){let n=await Gn(e,t,{label:r.label,expected:"file"});if(!n.exists){let o=new Error(`${r.label} does not exist`);throw o.code="ENOENT",o}let a=await sy(n.projectRoot,r.label);return rn(n.target,i,{...r,verify:async(o,s)=>{if(!ah(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await cy(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var $o=".comet/config.yaml";function oh(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function F_(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function sl(e,t={}){return(await Oo(e,t)).document}async function ly(e){try{return(await ur(e,$o,_o,{label:$o})).bytes}catch(t){if(F_(t))return null;throw t}}function uy(e){return e?{exists:!0,sha256:M_("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function cl(e){return uy(await ly(e))}async function Oo(e,t={}){let i=await ly(e);return{document:i?Jn(i.toString("utf8"),t):null,identity:uy(i)}}async function sh(e){return(await sl(e))?.config??null}var KV=16*1024;async function ch(e,t){if(!t)return;let i=await cl(e);if(!oh(i,t))throw new Error("Project config changed before commit; rerun the operation")}import{existsSync as dy,promises as dr}from"fs";import K from"path";import W_ from"os";var ll=".comet/config.yaml",z_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function lh(e){try{return await dr.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function J_(e){try{let t=await dr.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Kn(e,t){let i=K.relative(e,t);return i===""||!K.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${K.sep}`)}async function Un(e){let t=[],i=e;for(;!await lh(i);){let n=K.dirname(i);if(n===i)break;t.push(K.basename(i)),i=n}let r=await dr.realpath(i);return K.resolve(r,...t.reverse())}async function uh(e){try{return(await dr.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function dh(e){let t=K.resolve(e);try{(await dr.stat(t)).isDirectory()||(t=K.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let i=t,r=K.resolve(W_.homedir());for(;;){if(!(t===r&&i!==r)){let o=K.join(t,...ll.split("/")),s=t===i||await J_(o);if(await lh(o)&&s)return t}if(await lh(K.join(t,".git")))return t;let a=K.dirname(t);if(a===t)return i;t=a}}function ul(e){return zn(e)}async function G_(e,t){let i=ul(t),r=K.resolve(e,...i.split("/")),n=await dr.realpath(e),a=await Un(r);if(!Kn(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function qe(e,t){let i=ul(t),r=await G_(e,i),n=K.join(r,"comet");if(await uh(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Un(r),Un(n)]);if(!Kn(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=K.resolve(e),c=K.join(s,".comet","runtime","native");if(await uh(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([dr.realpath(s),Un(c)]);if(!Kn(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:K.join(e,...ll.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:K.join(n,"specs"),changesDir:K.join(n,"changes"),archiveDir:K.join(n,"archive"),runtimeDir:c,changesRuntimeDir:K.join(c,"changes"),locksDir:K.join(c,"locks"),transactionsDir:K.join(c,"transactions")}}function hy(e){if(!z_.test(e))throw new Error(`Invalid Native change name: ${e}`)}function We(e,t){hy(t);let i=K.join(e.changesRuntimeDir,t);if(!O(e.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function nn(e,t){hy(t);let i=K.join(e.changesDir,t,"runtime");if(!O(e.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function H(e,t){let i=We(e,t);if(dy(i))return i;let r=nn(e,t);return dy(r)?r:i}async function fy(e){try{let t=await dr.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function Do(e,t){let i=We(e,t),r=nn(e,t),[n,a]=await Promise.all([fy(i),fy(r)]);return n==="invalid"?{status:"invalid",layout:"project-local",path:i,message:"Native Runtime path must be a real directory"}:a==="invalid"?{status:"invalid",layout:"legacy",path:r,message:"Legacy Native Runtime path must be a real directory"}:n==="directory"&&a==="directory"?{status:"invalid",layout:"project-local",path:i,message:"Both project-local and legacy Native Runtime directories exist"}:n==="directory"?{status:"available",layout:"project-local",path:i}:a==="directory"?{status:"available",layout:"legacy",path:r}:{status:"missing",layout:"missing",path:i}}function fr(e,t){if(!t.startsWith("runtime/")||K.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let i=K.resolve(e,...t.slice(8).split("/"));if(!O(e,i))throw new Error(`Native Runtime ref escaped: ${t}`);return i}function j(e,t){let i=K.resolve(t);if(O(e.runtimeDir,i))return e.runtimeDir;if(O(e.nativeRoot,i))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function O(e,t){return Kn(K.resolve(e),K.resolve(t))}async function T(e,t){let i=K.resolve(e),r=K.resolve(t);if(!Kn(i,r))throw new Error(`Path is outside the Native root: ${t}`);if(await uh(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Un(i),Un(r)]);if(!Kn(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return r}var fh=Kt;var dl=rl;async function ye(e){let t=(await sl(e))?.config??null;return t?.native?t:null}async function Yn(e){let t=await ye(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function hr(e,t,i={}){let r=await Oo(e,{allowPartialProject:!0}),n=Io(r.document?.value??{},t),a=U_.join(e,...ll.split("/"));await he(a,To(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await i.beforeCommit?.(),await ch(e,r.identity)}})}import{promises as zI}from"fs";import JI from"path";import{AsyncLocalStorage as K_}from"async_hooks";import{randomUUID as gy}from"crypto";import{promises as xt}from"fs";import wy from"os";import pe from"path";var my=16*1024,hh=".coordinator",Y_=5e3,vy=new K_,fl=new Map;function X_(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function Q_(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let i=e;if(typeof i.id!="string"||i.id.length===0||typeof i.pid!="number"||!Number.isSafeInteger(i.pid)||i.pid<1||typeof i.hostname!="string"||i.hostname.length===0||typeof i.createdAt!="string"||i.createdAt.length===0||typeof i.operation!="string"||i.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return i}function yy(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 hl(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},r={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return vt(i,r)?z(i,r):z(i,r)&&e.size===t.size}function pl(e,t){return hl(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function Z_(e,t){return e.status!==t.status?!1:!e.owner||!e.identity||!t.owner||!t.identity?e.owner===t.owner&&e.identity===t.identity:e.owner.id===t.owner.id&&pl(e.identity,t.identity)}async function Xt(e){let t,i;try{let r=await rn(e,my,{bigint:!0,label:"Native lock"});t=r.bytes,i=r.stat}catch(r){if(r.code==="ENOENT")return null;throw r instanceof Yt?r.reason==="too-large"?new Error(`Native lock metadata exceeds ${my} bytes: ${e}`,{cause:r}):r.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:r}):new Error(`Native lock changed while reading: ${e}`,{cause:r}):r}return{file:e,owner:Q_(JSON.parse(t.toString("utf8")),e),identity:yy(i)}}async function eT(e){return(await Xt(e))?.owner??null}function ph(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==wy.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=oT(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function tT(e,t){try{await xt.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await xt.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function ml(e,t){let i=await Xt(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!pl(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await xt.mkdir(t,{recursive:!0});let r=pe.join(t,`${pe.basename(e.file)}.${e.owner.id}.${gy()}.removed`);try{await xt.rename(e.file,r)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await Xt(r);if(!n||n.owner.id!==e.owner.id||!hl(n.identity,e.identity))throw await tT(r,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await xt.rm(r,{force:!0}),"removed"}function Ny(e){return{id:gy(),pid:process.pid,hostname:wy.hostname(),createdAt:new Date().toISOString(),operation:e}}async function by(e,t){let i;try{i=await xt.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await eT(e);throw new Error(`Native lock is already held: ${e}${o?` by pid ${o.pid} for ${o.operation}`:""}`,{cause:a})}throw a}let r;try{await i.writeFile(JSON.stringify(t,null,2)+`
173
+ `,"utf8"),await i.sync(),r=yy(await i.stat({bigint:!0}))}finally{await i.close()}let n=await Xt(e);if(!r||!n||n.owner.id!==t.id||!hl(n.identity,r))throw new Error(`Native lock changed after write: ${e}`);return n.identity}async function iT(e,t){let i=await T(e.runtimeDir,e.locksDir);await xt.mkdir(i,{recursive:!0});let r=await T(e.runtimeDir,pe.join(i,hh));await xt.mkdir(r,{recursive:!0});let n=Ny(t),a=pe.join(r,`.${n.id}.tmp`),o=pe.join(r,`${n.id}.claim`);try{let s=await by(a,n);await xt.rename(a,o);let c=await Xt(o);if(!c||!hl(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:i,owner:n,identity:c.identity}}finally{await xt.rm(a,{force:!0})}}async function rT(e){let t=pe.dirname(e.file),i=!1,r=pe.basename(e.file);for(let n of await xt.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=pe.join(t,n.name);if(pe.resolve(a)!==pe.resolve(e.file))try{let o=await Xt(a),s=ph(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await ml(o,t);continue}n.name<r&&(i=!0)}catch{n.name<r&&(i=!0)}}return i}async function ky(e){let t=await Xt(e.file);if(t){if(t.owner.id!==e.owner.id||!pl(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await ml(t,pe.dirname(e.file))}}async function nT(e,t){let i=Date.now()+Y_;for(;;){let r=await iT(e,t);if(!await rT(r))return r;if(await ky(r),Date.now()>=i)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function aT(e){let t=fl.get(e)??Promise.resolve(),i,r=new Promise(a=>{i=a}),n=t.then(()=>r);return fl.set(e,n),await t,()=>{i(),fl.get(e)===n&&fl.delete(e)}}async function vl(e,t,i){let r=pe.resolve(e.locksDir),n=vy.getStore();if(n?.has(r))return i();let a=await aT(r);try{let o=await nT(e,t),s=new Map(n??[]);return s.set(r,o),await vy.run(s,async()=>{try{return await i()}finally{await ky(o)}})}finally{a()}}async function Xn(e,t,i){let r=[...new Map(e.map(a=>[pe.resolve(a.locksDir),a])).values()].sort((a,o)=>pe.resolve(a.locksDir).localeCompare(pe.resolve(o.locksDir))),n=async a=>{let o=r[a];return o?vl(o,t,()=>n(a+1)):i()};return n(0)}async function pr(e,t,i){return vl(e,`acquire ${t}`,async()=>{let r=await T(e.runtimeDir,e.locksDir);await xt.mkdir(r,{recursive:!0});let n=await T(e.runtimeDir,pe.join(r,X_(t))),a=Ny(i),o=await by(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:r,owner:a,identity:o}})}async function mr(e){await Xt(e.file)&&await vl({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${pe.basename(e.file)}`,async()=>{let t=await Xt(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!pl(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=pe.join(e.locksDir,hh);await ml(t,i)})}function oT(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function Lo(e){return ph(await Xt(e))}async function mh(e,t,i){return vl(e,`take over ${pe.basename(t)}`,async()=>{let r=await T(e.runtimeDir,e.locksDir),n=await T(e.runtimeDir,t);if(pe.resolve(pe.dirname(n))!==pe.resolve(r))throw new Error(`Native lock takeover target is outside the lock directory: ${t}`);let a=await Xt(n),o=ph(a);if(o.status==="missing")return{status:"missing"};if(i&&!Z_(i,o))return{status:"changed",diagnosis:o};if(o.status!=="stale"||!a)return{status:"changed",diagnosis:o};let s=pe.join(r,hh);return await ml(a,s)==="removed"?{status:"removed",owner:a.owner}:{status:"missing"}})}import{promises as fI}from"node:fs";import Rh from"node:path";import XT from"node:path";import jy from"node:path";import Sy from"node:path";import{createHash as sT}from"crypto";function Qt(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function cT(e,t){t.has(e)&&Qt("cyclic structures are not supported"),t.add(e);try{let i=Object.keys(e);for(let r=0;r<e.length;r+=1)Object.prototype.hasOwnProperty.call(e,r)||Qt("sparse arrays are not supported");return(i.length!==e.length||i.some((r,n)=>r!==String(n)))&&Qt("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&Qt("symbol properties are not supported"),`[${e.map(r=>vh(r,t)).join(",")}]`}finally{t.delete(e)}}function lT(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&Qt("only plain objects are supported"),t.has(e)&&Qt("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&Qt("symbol properties are not supported"),t.add(e);try{let r=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=r[o];return(!s||!("value"in s))&&Qt("accessor properties are not supported"),`${JSON.stringify(o)}:${vh(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function vh(e,t){if(e===null)return"null";switch(typeof e){case"boolean":return e?"true":"false";case"string":return JSON.stringify(e);case"number":return Number.isFinite(e)||Qt("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?cT(e,t):lT(e,t);case"bigint":case"function":case"symbol":case"undefined":return Qt(`${typeof e} values are not supported`)}return Qt("unsupported value type")}function Mo(e){return vh(e,new Set)}function D(e,t){if(e.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(e))throw new TypeError("Canonical hash tag must not contain a line break");return sT("sha256").update(`${e}
174
+ ${Mo(t)}`).digest("hex")}var uT="comet.native.acceptance.v1",dT=/^acceptance-[a-f0-9]{64}$/u,fT=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),hT=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,pT=/^[a-f0-9]{64}$/u,mT=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function vT(e,t){return e<t?-1:e>t?1:0}var Ti=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Bo=Object.freeze({maxCriteria:1024}),Ey="<!-- comet-native:acceptance-evidence:start -->",Py="<!-- comet-native:acceptance-evidence:end -->";function Ry(e,t){if(Buffer.byteLength(e,"utf8")<=t)return{value:e,truncated:!1};let i="",r=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(r+a>t)break;i+=n,r+=a}return{value:i,truncated:!0}}function Cy(e,t){let i=t.toString(36),r=D("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${i}.${r}`}function gT(e){if(!pT.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=mT.exec(e.cursor);if(!t)throw new Error("Native acceptance cursor is invalid");if(t[1]!==e.acceptanceHash)throw new Error("Native acceptance cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native acceptance cursor offset is invalid");if(t[3]!==D("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:i}))throw new Error("Native acceptance cursor integrity check failed");return i}function wT(e,t){let i=Ry(e.text,Ti.maxTextBytes),r=e.context.slice(0,Ti.maxContextItems).map(n=>Ry(n,Ti.maxContextItemBytes));return{id:e.id,kind:e.kind,source:e.source,context:r.map(n=>n.value),text:i.value,contextTruncated:e.context.length>r.length||r.some(n=>n.truncated),textTruncated:i.truncated,verificationStatus:t}}function Ay(e){let t=gT({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),i=[],r=[...new Set(e.failedCheckIds??[])].sort(vT),n=r.slice(0,Ti.maxFailedCheckIds),a=e.criteria.slice(t,t+Ti.maxItems);for(let c of a){let l=[...i,wT(c,e.verificationStatuses?.get(c.id)??"unverified")],u=t+l.length,d={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:l,failedAcceptanceIds:l.filter(f=>f.verificationStatus==="failed").map(f=>f.id),missingAcceptanceIds:l.filter(f=>f.verificationStatus==="missing").map(f=>f.id),failedCheckIds:n,failedCheckIdsTruncated:r.length>n.length,nextCursor:u<e.criteria.length?Cy(e.acceptanceHash,u):null,limits:{...Ti}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>Ti.maxSerializedBytes){if(i.length===0)throw new Error("Native acceptance criterion exceeds the page serialization budget");break}i.push(l.at(-1))}if(e.criteria.length>0&&i.length===0)throw new Error("Native acceptance page could not project its next criterion");let o=t+i.length,s={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:i,failedAcceptanceIds:i.filter(c=>c.verificationStatus==="failed").map(c=>c.id),missingAcceptanceIds:i.filter(c=>c.verificationStatus==="missing").map(c=>c.id),failedCheckIds:n,failedCheckIdsTruncated:r.length>n.length,nextCursor:o<e.criteria.length?Cy(e.acceptanceHash,o):null,limits:{...Ti}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>Ti.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function wh(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 gh(e,t){let i=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!i)return t;let r=i[1][0];return t===null?{marker:r,length:i[1].length}:r===t.marker&&i[1].length>=t.length&&i[2].trim().length===0?null:t}function xy(e){return e.includes("-->")||e.includes("--!>")}function*Qn(e){let t=null,i=!1,r=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
175
175
  `),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
176
- `,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!i&&r===null,index:s},s+=1,t!==null)t=mh(l,t);else if(i)Cy(l)&&(i=!1);else if(r!==null)new RegExp(`</${r}\\s*>`,"iu").test(l)&&(r=null);else{let d=mh(l,null);if(d!==null)t=d;else{let f=l.trimStart();if(f.startsWith("<!--")&&!Cy(f))i=!0;else{let h=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(f);h&&n.has(h[1].toLowerCase())&&!f.startsWith("</")&&!f.endsWith("/>")&&!new RegExp(`</${h[1]}\\s*>`,"iu").test(f)&&(r=h[1])}}}if(c===-1)break;o=c+1}}function hT(e){return[...Jn(e)].map(({line:t,body:i})=>({line:t,body:i}))}function Ho(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function pT(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function gh(e,t,i,r=[],n="content-hash"){let a=Ho(i),o=t.replaceAll("\\","/").trim(),s=r.map(Ho);if(a.length===0)throw new Error(`${e} acceptance criterion must not be empty`);if(o.length===0)throw new Error(`${e} acceptance criterion source must not be empty`);return{id:n==="content-hash"?`acceptance-${D(nT,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function wh(e,t,i="content-hash"){let r=new Set;for(let n of e){let a=i==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(r.has(a))throw new Error(`${t} contains duplicate acceptance criteria`);r.add(a)}return e}function mT(e){let t=null,i=null,r=0,n=0;for(let{line:a,body:o,index:s}of Jn(e)){n=s+1;let c=o?vh(a):null;c?.level===1&&(Gs(c.text)==="acceptanceExamples"?(r+=1,r===1&&(t=s+1)):t!==null&&i===null&&(i=s))}if(r===0||t===null)return null;if(r!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:i??n}}function dl(e,t="brief.md",i=Do.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native brief acceptance budget is invalid");let n=mT(e);if(n===null)return[];let a=null;for(let{line:l,body:u,index:d}of Jn(e)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(f===null)continue;let h=f[1].length;a=a===null?h:Math.min(a,h)}let o=[],s=null,c=()=>{if(s!==null){if(o.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);o.push(s)}};for(let{line:l,body:u,index:d}of Jn(e)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;f&&f[1].length===a?(c(),s=[f[2]]):s!==null&&s.push(l)}return c(),wh(o.map(l=>gh("brief-example",t,l.join(`
177
- `),[],r)),"Brief",r)}function fl(e,t="spec.md",i=Do.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=()=>{if(o!==null){if(n.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);n.push(gh("spec-scenario",t,[o.title,...o.body].join(`
178
- `),o.context,r)),o=null}};for(let{line:c,body:l}of Jn(e)){let u=l?vh(c):null,d=u?/^Scenario\s*:\s*(.*)$/iu.exec(u.text):null;if(d){for(s();a.at(-1)&&a.at(-1).level>=u.level;)a.pop();let f=Ho(d[1]);if(f.length===0)throw new Error("Scenario title must not be empty");o={level:u.level,title:f,body:[],context:a.map(h=>h.text)}}else if(u){for(o!==null&&u.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=u.level;)a.pop();a.push(u)}else o!==null&&l&&o.body.push(c)}return s(),wh(n,"Specification",r)}function Ay(e,t="spec.md",i=Do.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=null,c=()=>{if(s!==null){if(n.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);n.push(gh("spec-must",t,s.parts.join(" "),s.context,r)),s=null}},l=()=>a.some(u=>/^(?:non-?goals?|非目标)$/iu.test(u.text.trim()));for(let{line:u,body:d}of Jn(e)){let f=d?vh(u):null;if(f){for(c(),o!==null&&f.level<=o&&(o=null);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f),/^Scenario\s*:/iu.test(f.text)&&(o=f.level);continue}let h=u.trim();if(!d||o!==null||l()){c();continue}if(h.length===0||mh(u,null)!==null||h.startsWith("<!--")||h==="-->"||h==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(h)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(h)||/^(?:[-*_]\s*){3,}$/u.test(h)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(h)){c();continue}let v=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(u);if(v){c(),s={parts:[v[1]],context:a.map(m=>m.text)};continue}if(/^\|.*\|$/u.test(h)){c(),s={parts:[h],context:a.map(m=>m.text)},c();continue}s===null?s={parts:[h],context:a.map(m=>m.text)}:s.parts.push(h)}return c(),wh(n,"Specification mandatory requirements",r)}function vT(e,t){let i=e.trim().replaceAll("\\","/");if(i.length===0||pT(i)||ky.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~|[A-Za-z][A-Za-z0-9+.-]*:)/u.test(i)||i.split("/").includes(".."))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);let r=ky.posix.normalize(i);if(r==="."||r===".."||r.startsWith("../"))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);if(r.split("/").some(n=>n.toLowerCase()===".git"||n.toLowerCase().startsWith(".env")))throw new Error(`Acceptance evidence ${t} references sensitive content`);if(!sT.test(r))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return r}function gT(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`Acceptance evidence entry ${t} must be an object`);let i=e,r=Object.keys(i).filter(n=>!oT.has(n));if(r.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${r.join(", ")}`);return i}function _y(e){if(!Array.isArray(e))throw new Error("Native acceptance evidence block must be a JSON array");let t=new Set;return e.map((i,r)=>{let n=gT(i,r),a=n.acceptance_id;if(typeof a!="string"||!aT.test(a))throw new Error(`Acceptance evidence entry ${r} has an invalid acceptance_id`);if(t.has(a))throw new Error(`Native acceptance evidence has duplicate acceptance_id: ${a}`);if(t.add(a),!Array.isArray(n.evidence_refs))throw new Error(`Acceptance evidence ${a} requires an evidence_refs array`);let o=n.evidence_refs.map(l=>{if(typeof l!="string"||l.trim().length===0)throw new Error(`Acceptance evidence ${a} has a non-empty string requirement`);return vT(l,a)});if(new Set(o).size!==o.length)throw new Error(`Acceptance evidence ${a} has a duplicate evidence ref`);let s=n.status;if(s!=="passed"&&s!=="failed")throw new Error(`Acceptance evidence ${a} status is invalid`);let c;if(Object.prototype.hasOwnProperty.call(n,"skipped_reason")){if(typeof n.skipped_reason!="string"||n.skipped_reason.trim().length===0)throw new Error(`Acceptance evidence ${a} skipped_reason must be a non-empty string`);c=n.skipped_reason.trim()}if(s==="passed"&&o.length===0)throw new Error(`Acceptance evidence ${a} passed status requires evidence_refs`);if(s==="failed"&&o.length===0&&c===void 0)throw new Error(`Acceptance evidence ${a} failed status requires evidence_refs or a skipped_reason`);if(s==="passed"&&c!==void 0)throw new Error(`Acceptance evidence ${a} passed status has invalid fields`);return{acceptance_id:a,status:s,evidence_refs:o,...c===void 0?{}:{skipped_reason:c}}})}function Ty(e){let t=hT(e);if(t.some(({line:l,body:u})=>!u&&(l===Sy||l===Ey)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let r=t.flatMap(({line:l,body:u},d)=>u&&l===Sy?[d]:[]),n=t.flatMap(({line:l,body:u},d)=>u&&l===Ey?[d]:[]);if(r.length!==1||n.length!==1)throw new Error("Verification must contain exactly one Native acceptance evidence block");if(r[0]>=n[0])throw new Error("Native acceptance evidence markers are out of order");let a=t.slice(r[0]+1,n[0]).map(({line:l})=>l).join(`
179
- `).trim();if(a.length===0)throw new Error("Native acceptance evidence block is empty");let o;try{o=JSON.parse(a)}catch(l){throw new Error(`Native acceptance evidence block is invalid JSON: ${l.message}`,{cause:l})}let s=_y(o),c=wT(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function wT(e){let t=_y([...e]).map(i=>({...i,evidence_refs:[...i.evidence_refs].sort()})).sort((i,r)=>i.acceptance_id.localeCompare(r.acceptance_id));return JSON.stringify(t,null,2)}var yT=/^A[1-9]\d*$/u;function jy(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||Iy.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||Iy.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function NT(e,t){return e.localeCompare(t,"en")}function hl(e){let t=jy(e.briefSource??"brief.md","Native brief source"),i=[...e.specs??[]].sort((a,o)=>NT(a.capability,o.capability));if(new Set(i.map(a=>a.capability)).size!==i.length)throw new Error("Native acceptance sources contain duplicate capabilities");let r=dl(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of i){let o=jy(a.source,`Native spec source for ${a.capability}`);r.push(...fl(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})))}let n=new Set;for(let a of r){a.text=Ho(a.text);let o=`${a.source}\0${a.text}`;if(n.has(o))throw new Error(`Native acceptance contains a duplicate criterion: ${a.text}`);n.add(o)}if(r.length===0)throw new Error("Native change must define at least one acceptance criterion");return r.map((a,o)=>({id:`A${o+1}`,source:a.source,text:a.text}))}function $y(e){let t=e.map(({id:i})=>i);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let i=0;i<t.length;i+=1)if(!yT.test(t[i])||t[i]!==`A${i+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function Oy(e,t){return e.length===t.length&&e.every((i,r)=>i.source===t[r]?.source&&i.text===t[r]?.text)}var vl=Rn(Qr(),1);import{promises as bT}from"node:fs";var Gn="comet.native.v4",Lo="comet.native.local-execution.v4";var Hy=["multi-session","single-session"];function yh(){return{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}}}var kT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ST=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ET=/^A[1-9][0-9]*$/u,PT=/^[a-f0-9]{64}$/u,RT=new Set(["schema","name","language","phase","status","state_version","brief","children_contract_hash","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),ml=class extends Error{constructor(i,r){super(`Native state version conflict: expected ${i}, got ${r}`);this.expectedStateVersion=i;this.actualStateVersion=r;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};function Xe(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Qe(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function _e(e,t,i){if(typeof e!="string"||!i?.empty&&e.length===0)throw new Error(`${t} must be ${i?.empty?"a string":"a non-empty string"}`);return e}function bh(e,t){return e===null?null:_e(e,t)}function CT(e,t){let i=_e(e,t);if(!PT.test(i))throw new Error(`${t} must be a SHA-256 hash`);return i}function Un(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function me(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function xT(e,t){return e===null?null:me(e,t,Number.MIN_SAFE_INTEGER)}function Se(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function ui(e,t,i){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,n)=>i(r,n))}function gl(e,t){return ui(e,t,(i,r)=>_e(i,`${t}[${r}]`))}function rn(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Kn(e,t){let i=_e(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO date or timestamp`);return i}function kh(e,t,i=!1){let r=_e(e,t);if(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").includes("..")||!i&&(r==="."||r.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return r}function At(e,t){let i=Xe(e,t);return Qe(i,new Set(["text","truncated"]),t),{text:_e(i.text,`${t}.text`,{empty:!0}),truncated:Un(i.truncated,`${t}.truncated`)}}function AT(e,t){let i=`Native spec_changes[${t}]`,r=Xe(e,i);Qe(r,new Set(["capability","operation","source"]),i);let n=_e(r.capability,`${i}.capability`);if(!ST.test(n))throw new Error(`${i}.capability is invalid`);let a=Se(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:kh(r.source,`${i}.source`);if(a==="remove"&&o!==null)throw new Error(`${i} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${i} ${a} requires a source`);return{capability:n,operation:a,source:o}}function _T(e){let t="Native workspace",i=Xe(e,t);Qe(i,new Set(["isolation","change_branch","target_branch","finish"]),t);let r=Se(i.isolation,["current","branch","worktree"],`${t}.isolation`),n=bh(i.change_branch,`${t}.change_branch`),a=bh(i.target_branch,`${t}.target_branch`),o=i.finish===null?null:Se(i.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(r==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(r==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(r!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:r,change_branch:n,target_branch:a,finish:o}}function TT(e){let t="Native loop",i=Xe(e,t);Qe(i,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let r=gl(i.previous_unresolved_ids,`${t}.previous_unresolved_ids`);rn(r,`${t}.previous_unresolved_ids`);let n=i.stop_reason===void 0?void 0:Se(i.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:Se(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:me(i.goal_cycle,`${t}.goal_cycle`,1),iteration:me(i.iteration,`${t}.iteration`),attempt:me(i.attempt,`${t}.attempt`),retry_epoch:me(i.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:me(i.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:me(i.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:me(i.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:r,next_action:bh(i.next_action,`${t}.next_action`)}}function IT(e,t){let i=`Native acceptance[${t}]`,r=Xe(e,i);Qe(r,new Set(["id","source","text","result","reason"]),i);let n=_e(r.id,`${i}.id`);if(!ET.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:kh(r.source,`${i}.source`),text:_e(r.text,`${i}.text`),result:Se(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:At(r.reason,`${i}.reason`)}}function jT(e,t){let i=`Native builder_handoff.checks[${t}]`,r=Xe(e,i);return Qe(r,new Set(["name","result","note"]),i),{name:At(r.name,`${i}.name`),result:Se(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:At(r.note,`${i}.note`)}}function $T(e){let t="Native builder_handoff",i=Xe(e,t);Qe(i,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let r=gl(i.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);rn(r,`${t}.addressed_acceptance_ids`);let n=i.review===null||i.review===void 0?null:Xe(i.review,`${t}.review`);return n&&Qe(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:_e(i.candidate_id,`${t}.candidate_id`),identity_provider:_e(i.identity_provider,`${t}.identity_provider`),builder_execution_ref:_e(i.builder_execution_ref,`${t}.builder_execution_ref`),iteration:me(i.iteration,`${t}.iteration`,1),summary:At(i.summary,`${t}.summary`),addressed_acceptance_ids:r,checks:ui(i.checks,`${t}.checks`,jT),checks_truncated:Un(i.checks_truncated,`${t}.checks_truncated`),known_limits:ui(i.known_limits,`${t}.known_limits`,(a,o)=>At(a,`${t}.known_limits[${o}]`)),known_limits_truncated:Un(i.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:Se(n.status,["passed"],`${t}.review.status`),summary:At(n.summary,`${t}.review.summary`),reviewer_execution_ref:_e(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:Kn(i.submitted_at,`${t}.submitted_at`)}}function OT(e,t){let i=`Native blockers[${t}]`,r=Xe(e,i);Qe(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=gl(r.acceptance_ids,`${i}.acceptance_ids`);return rn(n,`${i}.acceptance_ids`),{owner:Se(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:At(r.reason,`${i}.reason`),acceptance_ids:n,resolution_action:Se(r.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${i}.resolution_action`)}}function HT(e,t){let i=`Native verification.checks[${t}]`,r=Xe(e,i);return Qe(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:_e(r.id,`${i}.id`),name:At(r.name,`${i}.name`),argv_display:ui(r.argv_display,`${i}.argv_display`,(n,a)=>At(n,`${i}.argv_display[${a}]`)),argv_truncated:Un(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:kh(r.cwd_ref,`${i}.cwd_ref`,!0),status:Se(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:xT(r.exit_code,`${i}.exit_code`),duration_ms:me(r.duration_ms,`${i}.duration_ms`)}}function DT(e){let t="Native verification",i=Xe(e,t);Qe(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let r=ui(i.checks,`${t}.checks`,HT);rn(r.map(a=>a.id),`${t}.checks IDs`);let n=_e(i.identity_provider,`${t}.identity_provider`);return{candidate_id:_e(i.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:_e(i.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:me(i.iteration,`${t}.iteration`,1),attempt:me(i.attempt,`${t}.attempt`,1),assurance:i.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":Se(i.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:Se(i.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:r,summary:At(i.summary,`${t}.summary`),risks:ui(i.risks,`${t}.risks`,(a,o)=>At(a,`${t}.risks[${o}]`)),risks_truncated:Un(i.risks_truncated,`${t}.risks_truncated`),completed_at:Kn(i.completed_at,`${t}.completed_at`)}}function Dy(e,t){let i=`Native history[${t}]`,r=Xe(e,i);Qe(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=gl(r.unresolved_ids,`${i}.unresolved_ids`);return rn(n,`${i}.unresolved_ids`),{goal_cycle:me(r.goal_cycle,`${i}.goal_cycle`,1),iteration:me(r.iteration,`${i}.iteration`),attempt:me(r.attempt,`${i}.attempt`),outcome:Se(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:At(r.summary,`${i}.summary`),completed_at:Kn(r.completed_at,`${i}.completed_at`)}}function LT(e){let t="Native history_overflow.outcome_counts",i=Xe(e,t),r=["pass","fail","blocked","execution-error","recovery"];return Qe(i,new Set(r),t),{pass:me(i.pass,`${t}.pass`),fail:me(i.fail,`${t}.fail`),blocked:me(i.blocked,`${t}.blocked`),"execution-error":me(i["execution-error"],`${t}.execution-error`),recovery:me(i.recovery,`${t}.recovery`)}}function MT(e){let t="Native history_overflow",i=Xe(e,t);Qe(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let r=me(i.dropped_entries,`${t}.dropped_entries`),n=i.first_dropped_at===null?null:Kn(i.first_dropped_at,`${t}.first_dropped_at`),a=i.last_dropped_at===null?null:Kn(i.last_dropped_at,`${t}.last_dropped_at`);if(r===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(r>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=LT(i.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==r)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:r,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function FT(e){let t=new Set(e.acceptance.map(i=>i.id));for(let i of e.loop.previous_unresolved_ids)if(!t.has(i))throw new Error(`Native loop references unknown acceptance ID ${i}`);for(let i of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(i))throw new Error(`Native builder handoff references unknown ID ${i}`);for(let i of e.blockers)for(let r of i.acceptance_ids)if(!t.has(r))throw new Error(`Native blocker references unknown ID ${r}`);if(e.builder_handoff){if(!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let r=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!r&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function BT(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let i=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(i!==null&&e.loop.stage!==i)throw new Error(`Native status ${e.status} requires loop stage ${i}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(r=>r.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(r=>r.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function ct(e){let t=Xe(e,"Native portable state");if(Qe(t,RT,"Native portable state"),t.schema!==Gn)throw new Error(`Native portable state schema must be ${Gn}`);let i=_e(t.name,"Native state name");if(!kT.test(i))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let r=ui(t.spec_changes,"Native spec_changes",AT);rn(r.map(s=>s.capability),"Native spec change capabilities");let n=ui(t.acceptance,"Native acceptance",IT);rn(n.map(s=>s.id),"Native acceptance IDs");let a=ui(t.history,"Native history",Dy);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Gn,name:i,language:Se(t.language,["en","zh-CN"],"Native state language"),phase:Se(t.phase,["shape","build","verify","archive"],"Native state phase"),status:Se(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:me(t.state_version,"Native state_version",1),brief:"brief.md",...t.children_contract_hash===void 0?{}:{children_contract_hash:CT(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:Se(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:r,workspace:_T(t.workspace),loop:TT(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:$T(t.builder_handoff),blockers:ui(t.blockers,"Native blockers",OT),verification:t.verification===null?null:DT(t.verification),history:a,history_overflow:MT(t.history_overflow),verification_result:Se(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:Se(t.verification_report,["verification.md"],"Native verification_report"),archived:Un(t.archived,"Native archived"),created_at:Kn(t.created_at,"Native created_at")};return FT(o),BT(o),o}function Yn(e,t){let i=ct(e),r=Dy(t,i.history.length),n=[...i.history,r],a={...i.history_overflow,outcome_counts:{...i.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return ct({...i,history:n,history_overflow:a})}function VT(e,t){let i=(0,vl.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`${t} is invalid YAML: ${i.errors[0].message}`);return i.toJS({mapAsMap:!1})}async function Ze(e){let t=await bT.readFile(e,"utf8");return ct(VT(t,"Native portable state"))}async function wl(e,t,i={}){let r=ct(t);await he(e,(0,vl.stringify)(r),i)}var pl=new Map;async function qT(e,t){let i=pl.get(e)??Promise.resolve(),r,n=new Promise(o=>{r=o}),a=i.then(()=>n);pl.set(e,a),await i;try{return await t()}finally{r(),pl.get(e)===a&&pl.delete(e)}}async function nn(e){return qT(e.file,async()=>{let t=me(e.expectedStateVersion,"Native expected state version",1),i=ct(e.next);if(i.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let r=await Ze(e.file);if(r.state_version===i.state_version&&JSON.stringify(r)===JSON.stringify(i))return r;if(r.state_version!==t)throw new ml(t,r.state_version);return await wl(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Ze(e.file);if(n.state_version!==t)throw new ml(t,n.state_version)}}),i})}function WT(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function hr(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(WT(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let i="",r=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(r+a>t)break;i+=n,r+=a}return{text:i,truncated:!0}}var Ne="comet.native.v3",be="comet.native.v2",et="comet.native.v1",pr="comet.native.transition.v3",Ti="comet.native.transition.v2",an="comet.native.transition.v1";var yl="comet.native.portable-migration.v1",JT=new Set(["schema","id","change","fromSchema","status","createdAt"]),GT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,UT=/^[a-z0-9][a-z0-9-]{7,127}$/u,KT=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),YT=new Set([et,be,Ne]);function XT(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function QT(e,t){let i=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(i.valueOf()))throw new Error(`${t} must be a valid timestamp`);return i.toISOString()}function ZT(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function eI(e){return e.schema===et?on(e):e.schema===be?di(e):lt(e)}function tI(e){return zT.posix.normalize(e.replaceAll("\\","/"))}function iI(e){return e.spec_changes.map(t=>t.operation==="remove"?{capability:t.capability,operation:"remove",source:null}:{capability:t.capability,operation:t.operation==="replace"?"modify":"create",source:tI(t.source)})}function rI(e){return e==="shape"?"shape":"build"}function nI(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function aI(e,t,i){return e==="zh-CN"?`从旧版 ${t} ${i} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${i} state; prior Loop, verification results, and execution records were not inherited.`}function Ly(e){let t=eI(e.state);$y(e.acceptance);let i=rI(t.phase),r=i==="shape"?0:1,n=QT(e.migratedAt??`${t.created_at}T00:00:00.000Z`,"Native portable migration time"),a=e.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return ct({schema:Gn,name:t.name,language:t.language,phase:i,status:"active",state_version:1,brief:"brief.md",spec_changes:iI(t),workspace:e.workspace,loop:{stage:i==="shape"?"shape":"building",goal_cycle:1,iteration:r,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:nI(t.language,i)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:r,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:hr(aI(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:yh(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function Sh(e){let t=XT(e,"Native portable migration transaction"),i=Object.keys(t).filter(r=>!JT.has(r));if(i.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${i.join(", ")}`);if(t.schema!==yl)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!UT.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!GT.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!YT.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!KT.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:yl,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:ZT(t.createdAt,"Native portable migration transaction createdAt")}}function My(e){switch(Sh(e).status){case"prepared":return{action:"commit-portable-yaml",fromStatus:"prepared",nextStatus:"yaml-committed"};case"yaml-committed":return{action:"cleanup-legacy-runtime",fromStatus:"yaml-committed",nextStatus:"legacy-cleanup"};case"legacy-cleanup":return{action:"commit-transaction",fromStatus:"legacy-cleanup",nextStatus:"committed"};case"committed":return{action:"done",fromStatus:"committed",nextStatus:null}}}var Nl="comet.native.archive-transaction.v4",Fy="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",sI=new RegExp(`^portable-archive-(${Fy})\\.json$`,"u"),cI=new RegExp(`^portable-migration-(${Fy})\\.json$`,"u"),lI=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,uI=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,dI=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),fI=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),hI=new Set(["capability","operation","source","content"]),By=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Vy(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function qy(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(Object.keys(e).length!==t.size)throw new Error(`${i} fields are invalid`)}function pI(e,t){let i=`Native portable Archive spec_changes[${t}]`,r=Vy(e,i);if(qy(r,hI,i),typeof r.capability!="string"||!By.test(r.capability))throw new Error(`${i}.capability is invalid`);if(!["create","modify","remove"].includes(String(r.operation)))throw new Error(`${i}.operation is invalid`);let n=r.operation;if(n==="remove"){if(r.source!==null||r.content!==null)throw new Error(`${i} remove requires source and content null`);return{capability:r.capability,operation:n,source:null,content:null}}if(typeof r.source!="string"||r.source.length===0||r.source.includes("\\")||r.source.startsWith("/")||/^[A-Za-z]:/u.test(r.source)||r.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${i}.${n} source is invalid`);if(typeof r.content!="string")throw new Error(`${i}.${n} content is invalid`);return{capability:r.capability,operation:n,source:r.source,content:r.content}}function mI(e){let t=Vy(e,"Native portable Archive transaction");if(qy(t,fI,"Native portable Archive transaction"),t.schema!==Nl)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!lI.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!By.test(t.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(t.start_state_version)||Number(t.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof t.archive_ref!="string"||!uI.test(t.archive_ref)||!t.archive_ref.endsWith(`-${t.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof t.status!="string"||!dI.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let i=t.spec_changes.map(pI);if(new Set(i.map(({capability:n})=>n)).size!==i.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>i.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let r=new Date(t.created_at);if(Number.isNaN(r.valueOf())||r.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:Nl,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:i,created_at:t.created_at}}function sn(e){let t=sI.exec(e);if(t)return{kind:"archive",change:t[1]};let i=cI.exec(e);return i?{kind:"migration",change:i[1]}:null}function mr(e,t){let i=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,r=sn(i);if(!r||r.kind!==t.kind||r.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return Eh.join(e.transactionsDir,i)}async function Mo(e,t){let i=sn(t);if(!i)return null;let r=await Z({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(r.text),a=Eh.join(e.transactionsDir,t);if(i.kind==="archive"){let s=mI(n);if(s.change!==i.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:i.change,file:a,journal:s}}let o=Sh(n);if(o.change!==i.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:i.change,file:a,journal:o}}async function bl(e,t){let i=mr(e,t);try{return await Mo(e,Eh.basename(i))}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Wy(e){let t;try{t=await oI.readdir(e.transactionsDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}return t.map(({name:i})=>i).filter(i=>sn(i)!==null).sort((i,r)=>i.localeCompare(r,"en"))}function zy(e){return e.kind==="archive"||e.journal.status!=="committed"}import{promises as Fo}from"fs";import _t from"path";import{TextDecoder as NI}from"util";import{createHash as vI}from"node:crypto";import{constants as kl,promises as W}from"node:fs";import Y from"node:path";import{TextDecoder as gI}from"node:util";function ze(e,t){let i=Y.relative(e,t);return i===""||!Y.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Y.sep}`)}function Jy(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function Qn(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Gy(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Xn(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function vr(e,t){let i=await W.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await W.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function gr(e,t,i){let r=Y.resolve(e),n=Y.resolve(t);if(!ze(r,n))throw new Error(`${i} is outside its managed root`);let a=[await vr(r,i)],o=r;for(let s of Y.relative(r,n).split(Y.sep).filter(Boolean)){await we(a,i),o=Y.join(o,s);let c=await vr(o,i);if(!ze(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await we(a,i),a}async function we(e,t){for(let i of e){let r=await W.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!Qn(i,r)||await W.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function wI(e,t,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${i} exceeds ${t} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function re(e){let t=Jy(e.maxBytes),i=Y.resolve(e.file),r=await gr(e.root,Y.dirname(i),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>vr(Y.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await we(r,e.label);let a=await W.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=Gy(a),s=await W.realpath(i);if(!ze(r[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>ze(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?kl.O_RDONLY:kl.O_RDONLY|kl.O_NOFOLLOW|kl.O_NONBLOCK,l=await W.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([W.lstat(i),W.realpath(i)]);if(await we(r,e.label),await we(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!Xn(o,u)||!Xn(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let h=await wI(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,m,p]=await Promise.all([l.stat(),W.lstat(i),W.realpath(i)]);if(await we(r,e.label),await we(n,e.label),!m.isFile()||m.isSymbolicLink()||p!==s||!Xn(o,v)||!Xn(o,m))throw new Error(`${e.label} changed while reading`);return{bytes:h,hash:vI("sha256").update(h).digest("hex"),size:h.length}}finally{await l.close()}}async function Sl(e){let t=await re(e),i;try{i=new gI("utf-8",{fatal:!0}).decode(t.bytes)}catch(r){throw new Error(`${e.label} is not valid UTF-8`,{cause:r})}return{...t,text:i}}async function wt(e){let t=await gr(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await W.readdir(e.directory,{withFileTypes:!0});else{let r=Jy(e.maxEntries);i=[];let n=await W.opendir(e.directory);try{for await(let a of n)if(i.push(a),i.length>r)throw new Error(`${e.label} exceeds ${r} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await we(t,e.label),{entries:i,verify:()=>we(t,e.label)}}async function Qt(e){let t=await gr(e.root,e.directory,e.label);return{verify:()=>we(t,e.label)}}async function yI(e){let t=Y.resolve(e.directory),i=Y.resolve(e.quarantine);if(Y.dirname(i)!==Y.dirname(t)||!ze(Y.resolve(e.root),i)||i===t)throw new Error(`${e.label} quarantine must be a distinct sibling inside its root`);let r=await gr(e.root,Y.dirname(t),e.label),n=await vr(t,e.label);if(!ze(r[0].realPath,n.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeQuarantine?.(),await we(r,e.label);let a=await W.lstat(t);if(!a.isDirectory()||a.isSymbolicLink()||!Qn(n,a)||await W.realpath(t)!==n.realPath)throw new Error(`${e.label} changed before quarantine`);try{throw await W.lstat(i),new Error(`${e.label} quarantine path is occupied`)}catch(s){if(s.code!=="ENOENT")throw s}await W.rename(t,i),await we(r,e.label);let o=await W.lstat(i);if(!o.isDirectory()||o.isSymbolicLink()||!Qn(n,o))throw new Error(`${e.label} changed while quarantining`);await e.afterQuarantine?.(i);try{throw await W.lstat(t),new Error(`${e.label} path was recreated while quarantining`)}catch(s){if(s.code!=="ENOENT")throw s}return{quarantine:i,parentChain:r,identity:n}}async function Uy(e){await yI(e)}async function El(e){let t=Y.resolve(e.file),i=await gr(e.root,Y.dirname(t),e.label),r=await W.lstat(t);if(!r.isFile()||r.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let n=Gy(r),a=await W.realpath(t);if(!ze(i[0].realPath,a))throw new Error(`${e.label} resolves outside its managed root`);let o=await re({root:e.root,file:t,maxBytes:e.maxBytes,label:e.label});if(o.hash!==e.expectedHash||o.size!==e.expectedSize)throw new Error(`${e.label} changed before removal`);let[s,c]=await Promise.all([W.lstat(t),W.realpath(t)]);if(!s.isFile()||s.isSymbolicLink()||!Xn(n,s)||c!==a)throw new Error(`${e.label} changed while verifying removal`);await e.beforeRemove?.(),await we(i,e.label);let[l,u]=await Promise.all([W.lstat(t),W.realpath(t)]);if(!l.isFile()||l.isSymbolicLink()||!Xn(n,l)||u!==a)throw new Error(`${e.label} changed before removal`);await W.rm(t),await we(i,e.label)}async function Ph(e){let t=Y.resolve(e.directory),i=await gr(e.root,Y.dirname(t),e.label),r=await vr(t,e.label);if(!ze(i[0].realPath,r.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeRemove?.(),await we(i,e.label);let n=await W.lstat(t);if(!n.isDirectory()||n.isSymbolicLink()||!Qn(r,n)||await W.realpath(t)!==r.realPath)throw new Error(`${e.label} changed before removal`);await W.rmdir(t),await we(i,e.label)}async function fi(e){let t=Y.resolve(e.root),i=Y.resolve(e.directory);if(!ze(t,i))throw new Error(`${e.label} is outside its managed root`);let r=[await vr(t,e.label)],n=t;for(let a of Y.relative(t,i).split(Y.sep).filter(Boolean)){await we(r,e.label),n=Y.join(n,a);try{await W.mkdir(n)}catch(s){if(s.code!=="EEXIST")throw s}let o=await vr(n,e.label);if(!ze(r[0].realPath,o.realPath))throw new Error(`${e.label} resolves outside its managed root: ${n}`);r.push(o)}await we(r,e.label)}async function Rh(e){let t=Y.resolve(e.root),i=Y.resolve(e.source),r=Y.resolve(e.target);if(i===r||!ze(t,i)||!ze(t,r)||ze(i,r)||ze(r,i))throw new Error(`${e.label} source and target must be distinct paths inside one root`);await fi({root:t,directory:Y.dirname(r),label:`${e.label} target parent`});let n=await gr(t,Y.dirname(i),e.label),a=await gr(t,Y.dirname(r),e.label),o=await vr(i,e.label);if(!ze(n[0].realPath,o.realPath))throw new Error(`${e.label} source resolves outside its managed root`);try{throw await W.lstat(r),new Error(`${e.label} target already exists`)}catch(l){if(l.code!=="ENOENT")throw l}await e.beforeMove?.(),await Promise.all([we(n,e.label),we(a,e.label)]);let s=await W.lstat(i);if(!s.isDirectory()||s.isSymbolicLink()||!Qn(o,s)||await W.realpath(i)!==o.realPath)throw new Error(`${e.label} source changed before move`);await W.rename(i,r),await Promise.all([we(n,e.label),we(a,e.label)]);let c=await W.lstat(r);if(!c.isDirectory()||c.isSymbolicLink()||!Qn(o,c)||!ze(n[0].realPath,await W.realpath(r)))throw new Error(`${e.label} source identity changed while moving`);try{throw await W.lstat(i),new Error(`${e.label} source was recreated while moving`)}catch(l){if(l.code!=="ENOENT")throw l}}async function wr(e){let t=await re({root:e.sourceRoot,file:e.source,maxBytes:e.maxBytes,label:e.label,hooks:e.hooks,forbiddenRoots:e.forbiddenRoots});if(e.expectedHash!==void 0&&t.hash!==e.expectedHash)throw new Error(`${e.label} content changed before copy`);await Gw(e.target,t.bytes,{containedRoot:e.targetRoot,exclusive:e.exclusive,beforeCommit:async()=>{if(await e.hooks?.beforeTargetCommit?.(),e.expectedTargetHash===void 0)return;if(e.expectedTargetHash===null){try{await W.lstat(e.target)}catch(n){if(n.code==="ENOENT")return;throw n}throw new Error(`${e.label} target changed before commit`)}if((await re({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} existing target`})).hash!==e.expectedTargetHash)throw new Error(`${e.label} target changed before commit`)}});let i=await re({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} target`});if(i.hash!==t.hash||i.size!==t.size)throw new Error(`${e.label} target could not be verified`);return i}var bI=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),kI=new Set(["id","type","source","target","staged","backup"]),SI=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),EI=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),PI=new Set(["sequence","timestamp","type","operationId"]),Qy=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),Zy=new Set(["prepared","operation-started","operation-completed","archive-finalization-started","archive-finalized","commit","rollback-started","rollback-completed"]),RI=256*1024,CI=1024*1024,eN=16*1024,Rl=1024,Ah=64*1024*1024,xI=2e4,tN=new NI("utf-8",{fatal:!0});function Bo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Vo(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function ea(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Ch(e,t){if(typeof e!="string"||e.length===0||_t.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Pl(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function Ky(e,t){if(Ch(e,t),e.includes("\\")||e!==_t.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function AI(e,t){let i=Bo(e,`transaction operations[${t}]`);if(Vo(i,kI,`transaction operations[${t}]`),typeof i.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.id))throw new Error(`transaction operations[${t}].id is invalid`);if(i.type!=="write"&&i.type!=="remove"&&i.type!=="move")throw new Error(`transaction operation ${i.id} has an invalid type`);Ch(i.target,`transaction operation ${i.id} target`);for(let r of["source","staged","backup"])i[r]!==void 0&&Ch(i[r],`transaction operation ${i.id} ${r}`);if(i.type==="write"){if(i.staged===void 0||i.source!==void 0)throw new Error(`write operation ${i.id} requires staged and forbids source`)}else if(i.type==="remove"){if(i.source!==void 0||i.staged!==void 0)throw new Error(`remove operation ${i.id} forbids source and staged`)}else if(i.source===void 0||i.staged!==void 0||i.backup!==void 0)throw new Error(`move operation ${i.id} requires source and forbids staged and backup`);return i}function xl(e){let t=Bo(e,"Native Archive transaction journal");if(Vo(t,SI,"Native Archive transaction journal"),t.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native Archive transaction id is invalid");if(t.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof t.status!="string"||!Qy.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!ea(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Pl(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let i=t.operations.map((s,c)=>{let l=Bo(s,`Archive transaction operations[${c}]`);if(Vo(l,EI,`Archive transaction operations[${c}]`),typeof l.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(l.id))throw new Error(`Archive transaction operations[${c}].id is invalid`);if(l.type!=="write"&&l.type!=="remove"&&l.type!=="move")throw new Error(`Archive transaction operation ${l.id} has an invalid type`);Ky(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&Ky(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&Pl(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(Pl(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);Pl(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),r=i.map(s=>s.id);if(new Set(r).size!==r.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=i.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||i.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of i.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:i}}function _h(e){let t=Bo(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return xl(t);if(Vo(t,bI,"Native transaction journal"),t.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native transaction id is invalid");if(t.kind!=="archive"&&t.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof t.status!="string"||!Qy.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!_t.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!_t.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!ea(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let i=t.operations.map(AI),r=i.map(n=>n.id);if(new Set(r).size!==r.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:i}}function iN(e,t){let i=Bo(e,`Native transaction event at line ${t}`);if(Vo(i,PI,`Native transaction event at line ${t}`),i.sequence!==t)throw new Error(`Native transaction event sequence at line ${t} must be ${t}`);if(!ea(i.timestamp))throw new Error(`Native transaction event timestamp at line ${t} is invalid`);if(typeof i.type!="string"||!Zy.has(i.type))throw new Error(`Native transaction event type at line ${t} is invalid`);let r=i.type==="operation-started"||i.type==="operation-completed";if(r&&(typeof i.operationId!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.operationId)||Buffer.byteLength(i.operationId,"utf8")>256)||!r&&i.operationId!==void 0)throw new Error(`Native transaction event operationId at line ${t} is invalid`);return{sequence:i.sequence,timestamp:i.timestamp,type:i.type,...typeof i.operationId=="string"?{operationId:i.operationId}:{}}}function _I(e){if(e.length>24)return!1;let t="0000-00-00T00:00:00.000Z";for(let r=0;r<e.length;r+=1){let n=t[r],a=e[r];if(n==="0"){if(!/[0-9]/u.test(a))return!1}else if(a!==n)return!1}let i=[[5,2,1,12],[8,2,1,31],[11,2,0,23],[14,2,0,59],[17,2,0,59],[20,3,0,999]];for(let[r,n,a,o]of i){if(e.length<=r)continue;let s=e.slice(r,Math.min(r+n,e.length));if(!Array.from({length:o-a+1},(l,u)=>String(a+u).padStart(n,"0")).some(l=>l.startsWith(s)))return!1}return e.length>=10&&!ea(`${e.slice(0,10)}T00:00:00.000Z`)?!1:e.length<24||ea(e)}function Zn(e,t){return e.length<t.length&&t.startsWith(e)}function TI(e){let t='","operationId":"';if(Zn(e,t))return!0;if(!e.startsWith(t))return!1;let i=e.slice(t.length),r=i.indexOf('"');if(r===-1)return i.length===0||/^[a-z0-9][a-z0-9-]*$/u.test(i);let n=i.slice(0,r);return/^[a-z0-9][a-z0-9-]*$/u.test(n)?Zn(i.slice(r),'"}'):!1}function II(e,t){if(e.length===0||Buffer.byteLength(e,"utf8")>eN)return!1;let i=`{"sequence":${t},"timestamp":"`;if(Zn(e,i))return!0;if(!e.startsWith(i))return!1;let r=e.slice(i.length),n=r.slice(0,Math.min(24,r.length));if(!_I(n))return!1;if(r.length<24)return!0;if(!ea(n))return!1;let a='","type":"',o=r.slice(24);if(Zn(o,a))return!0;if(!o.startsWith(a))return!1;let s=o.slice(a.length);for(let c of Zy){if(Zn(s,c))return!0;if(!s.startsWith(c))continue;let l=s.slice(c.length);if(c==="operation-started"||c==="operation-completed"){if(TI(l))return!0}else if(Zn(l,'"}'))return!0}return!1}function jI(e,t){if(e.length===0)throw new Error("Blank transaction event line");if(Buffer.byteLength(e,"utf8")>eN)throw new Error(`Native transaction event at line ${t} is too large`);return iN(JSON.parse(e),t)}function $I(e){let t=e.split(`
180
- `),i=t.at(-1)==="";if(i&&t.pop(),t.length>Rl)throw new Error(`Native transaction event log exceeds ${Rl} events`);let r=[];for(let n=0;n<t.length;n+=1){let a=n+1,o=t[n],s=o.endsWith("\r")?o.slice(0,-1):o,c=!i&&n===t.length-1;try{r.push(jI(s,a))}catch(l){if(c){let u=!1;try{JSON.parse(s),u=!0}catch{}if(!u&&II(s,a))break}throw new Error(`Invalid Native transaction event at line ${a}`,{cause:l})}}return r}function rN(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
176
+ `,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!i&&r===null,index:s},s+=1,t!==null)t=gh(l,t);else if(i)xy(l)&&(i=!1);else if(r!==null)new RegExp(`</${r}\\s*>`,"iu").test(l)&&(r=null);else{let d=gh(l,null);if(d!==null)t=d;else{let f=l.trimStart();if(f.startsWith("<!--")&&!xy(f))i=!0;else{let h=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(f);h&&n.has(h[1].toLowerCase())&&!f.startsWith("</")&&!f.endsWith("/>")&&!new RegExp(`</${h[1]}\\s*>`,"iu").test(f)&&(r=h[1])}}}if(c===-1)break;o=c+1}}function yT(e){return[...Qn(e)].map(({line:t,body:i})=>({line:t,body:i}))}function Fo(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function NT(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function yh(e,t,i,r=[],n="content-hash"){let a=Fo(i),o=t.replaceAll("\\","/").trim(),s=r.map(Fo);if(a.length===0)throw new Error(`${e} acceptance criterion must not be empty`);if(o.length===0)throw new Error(`${e} acceptance criterion source must not be empty`);return{id:n==="content-hash"?`acceptance-${D(uT,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function Nh(e,t,i="content-hash"){let r=new Set;for(let n of e){let a=i==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(r.has(a))throw new Error(`${t} contains duplicate acceptance criteria`);r.add(a)}return e}function bT(e){let t=null,i=null,r=0,n=0;for(let{line:a,body:o,index:s}of Qn(e)){n=s+1;let c=o?wh(a):null;c?.level===1&&(Ys(c.text)==="acceptanceExamples"?(r+=1,r===1&&(t=s+1)):t!==null&&i===null&&(i=s))}if(r===0||t===null)return null;if(r!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:i??n}}function gl(e,t="brief.md",i=Bo.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native brief acceptance budget is invalid");let n=bT(e);if(n===null)return[];let a=null;for(let{line:l,body:u,index:d}of Qn(e)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(f===null)continue;let h=f[1].length;a=a===null?h:Math.min(a,h)}let o=[],s=null,c=()=>{if(s!==null){if(o.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);o.push(s)}};for(let{line:l,body:u,index:d}of Qn(e)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;f&&f[1].length===a?(c(),s=[f[2]]):s!==null&&s.push(l)}return c(),Nh(o.map(l=>yh("brief-example",t,l.join(`
177
+ `),[],r)),"Brief",r)}function wl(e,t="spec.md",i=Bo.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=()=>{if(o!==null){if(n.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);n.push(yh("spec-scenario",t,[o.title,...o.body].join(`
178
+ `),o.context,r)),o=null}};for(let{line:c,body:l}of Qn(e)){let u=l?wh(c):null,d=u?/^Scenario\s*:\s*(.*)$/iu.exec(u.text):null;if(d){for(s();a.at(-1)&&a.at(-1).level>=u.level;)a.pop();let f=Fo(d[1]);if(f.length===0)throw new Error("Scenario title must not be empty");o={level:u.level,title:f,body:[],context:a.map(h=>h.text)}}else if(u){for(o!==null&&u.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=u.level;)a.pop();a.push(u)}else o!==null&&l&&o.body.push(c)}return s(),Nh(n,"Specification",r)}function _y(e,t="spec.md",i=Bo.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=null,c=()=>{if(s!==null){if(n.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);n.push(yh("spec-must",t,s.parts.join(" "),s.context,r)),s=null}},l=()=>a.some(u=>/^(?:non-?goals?|非目标)$/iu.test(u.text.trim()));for(let{line:u,body:d}of Qn(e)){let f=d?wh(u):null;if(f){for(c(),o!==null&&f.level<=o&&(o=null);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f),/^Scenario\s*:/iu.test(f.text)&&(o=f.level);continue}let h=u.trim();if(!d||o!==null||l()){c();continue}if(h.length===0||gh(u,null)!==null||h.startsWith("<!--")||h==="-->"||h==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(h)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(h)||/^(?:[-*_]\s*){3,}$/u.test(h)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(h)){c();continue}let v=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(u);if(v){c(),s={parts:[v[1]],context:a.map(m=>m.text)};continue}if(/^\|.*\|$/u.test(h)){c(),s={parts:[h],context:a.map(m=>m.text)},c();continue}s===null?s={parts:[h],context:a.map(m=>m.text)}:s.parts.push(h)}return c(),Nh(n,"Specification mandatory requirements",r)}function kT(e,t){let i=e.trim().replaceAll("\\","/");if(i.length===0||NT(i)||Sy.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~|[A-Za-z][A-Za-z0-9+.-]*:)/u.test(i)||i.split("/").includes(".."))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);let r=Sy.posix.normalize(i);if(r==="."||r===".."||r.startsWith("../"))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);if(r.split("/").some(n=>n.toLowerCase()===".git"||n.toLowerCase().startsWith(".env")))throw new Error(`Acceptance evidence ${t} references sensitive content`);if(!hT.test(r))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return r}function ST(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`Acceptance evidence entry ${t} must be an object`);let i=e,r=Object.keys(i).filter(n=>!fT.has(n));if(r.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${r.join(", ")}`);return i}function Ty(e){if(!Array.isArray(e))throw new Error("Native acceptance evidence block must be a JSON array");let t=new Set;return e.map((i,r)=>{let n=ST(i,r),a=n.acceptance_id;if(typeof a!="string"||!dT.test(a))throw new Error(`Acceptance evidence entry ${r} has an invalid acceptance_id`);if(t.has(a))throw new Error(`Native acceptance evidence has duplicate acceptance_id: ${a}`);if(t.add(a),!Array.isArray(n.evidence_refs))throw new Error(`Acceptance evidence ${a} requires an evidence_refs array`);let o=n.evidence_refs.map(l=>{if(typeof l!="string"||l.trim().length===0)throw new Error(`Acceptance evidence ${a} has a non-empty string requirement`);return kT(l,a)});if(new Set(o).size!==o.length)throw new Error(`Acceptance evidence ${a} has a duplicate evidence ref`);let s=n.status;if(s!=="passed"&&s!=="failed")throw new Error(`Acceptance evidence ${a} status is invalid`);let c;if(Object.prototype.hasOwnProperty.call(n,"skipped_reason")){if(typeof n.skipped_reason!="string"||n.skipped_reason.trim().length===0)throw new Error(`Acceptance evidence ${a} skipped_reason must be a non-empty string`);c=n.skipped_reason.trim()}if(s==="passed"&&o.length===0)throw new Error(`Acceptance evidence ${a} passed status requires evidence_refs`);if(s==="failed"&&o.length===0&&c===void 0)throw new Error(`Acceptance evidence ${a} failed status requires evidence_refs or a skipped_reason`);if(s==="passed"&&c!==void 0)throw new Error(`Acceptance evidence ${a} passed status has invalid fields`);return{acceptance_id:a,status:s,evidence_refs:o,...c===void 0?{}:{skipped_reason:c}}})}function Iy(e){let t=yT(e);if(t.some(({line:l,body:u})=>!u&&(l===Ey||l===Py)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let r=t.flatMap(({line:l,body:u},d)=>u&&l===Ey?[d]:[]),n=t.flatMap(({line:l,body:u},d)=>u&&l===Py?[d]:[]);if(r.length!==1||n.length!==1)throw new Error("Verification must contain exactly one Native acceptance evidence block");if(r[0]>=n[0])throw new Error("Native acceptance evidence markers are out of order");let a=t.slice(r[0]+1,n[0]).map(({line:l})=>l).join(`
179
+ `).trim();if(a.length===0)throw new Error("Native acceptance evidence block is empty");let o;try{o=JSON.parse(a)}catch(l){throw new Error(`Native acceptance evidence block is invalid JSON: ${l.message}`,{cause:l})}let s=Ty(o),c=ET(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function ET(e){let t=Ty([...e]).map(i=>({...i,evidence_refs:[...i.evidence_refs].sort()})).sort((i,r)=>i.acceptance_id.localeCompare(r.acceptance_id));return JSON.stringify(t,null,2)}var PT=/^A[1-9]\d*$/u;function $y(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||jy.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||jy.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function RT(e,t){return e.localeCompare(t,"en")}function yl(e){let t=$y(e.briefSource??"brief.md","Native brief source"),i=[...e.specs??[]].sort((a,o)=>RT(a.capability,o.capability));if(new Set(i.map(a=>a.capability)).size!==i.length)throw new Error("Native acceptance sources contain duplicate capabilities");let r=gl(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of i){let o=$y(a.source,`Native spec source for ${a.capability}`);r.push(...wl(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})))}let n=new Set;for(let a of r){a.text=Fo(a.text);let o=`${a.source}\0${a.text}`;if(n.has(o))throw new Error(`Native acceptance contains a duplicate criterion: ${a.text}`);n.add(o)}if(r.length===0)throw new Error("Native change must define at least one acceptance criterion");return r.map((a,o)=>({id:`A${o+1}`,source:a.source,text:a.text}))}function Oy(e){let t=e.map(({id:i})=>i);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let i=0;i<t.length;i+=1)if(!PT.test(t[i])||t[i]!==`A${i+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function Hy(e,t){return e.length===t.length&&e.every((i,r)=>i.source===t[r]?.source&&i.text===t[r]?.text)}var kl=Tn(en(),1);import{promises as CT}from"node:fs";var Zn="comet.native.v4",Vo="comet.native.local-execution.v4";var Dy=["multi-session","single-session"];function bh(){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 xT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,AT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,_T=/^A[1-9][0-9]*$/u,TT=/^[a-f0-9]{64}$/u,IT=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"]),bl=class extends Error{constructor(i,r){super(`Native state version conflict: expected ${i}, got ${r}`);this.expectedStateVersion=i;this.actualStateVersion=r;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};function Xe(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Qe(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Te(e,t,i){if(typeof e!="string"||!i?.empty&&e.length===0)throw new Error(`${t} must be ${i?.empty?"a string":"a non-empty string"}`);return e}function Sh(e,t){return e===null?null:Te(e,t)}function jT(e,t){let i=Te(e,t);if(!TT.test(i))throw new Error(`${t} must be a SHA-256 hash`);return i}function ea(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function me(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function $T(e,t){return e===null?null:me(e,t,Number.MIN_SAFE_INTEGER)}function Se(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function ui(e,t,i){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,n)=>i(r,n))}function Sl(e,t){return ui(e,t,(i,r)=>Te(i,`${t}[${r}]`))}function an(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function ta(e,t){let i=Te(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO date or timestamp`);return i}function Eh(e,t,i=!1){let r=Te(e,t);if(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").includes("..")||!i&&(r==="."||r.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return r}function At(e,t){let i=Xe(e,t);return Qe(i,new Set(["text","truncated"]),t),{text:Te(i.text,`${t}.text`,{empty:!0}),truncated:ea(i.truncated,`${t}.truncated`)}}function OT(e,t){let i=`Native spec_changes[${t}]`,r=Xe(e,i);Qe(r,new Set(["capability","operation","source"]),i);let n=Te(r.capability,`${i}.capability`);if(!AT.test(n))throw new Error(`${i}.capability is invalid`);let a=Se(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:Eh(r.source,`${i}.source`);if(a==="remove"&&o!==null)throw new Error(`${i} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${i} ${a} requires a source`);return{capability:n,operation:a,source:o}}function HT(e){let t="Native workspace",i=Xe(e,t);Qe(i,new Set(["isolation","change_branch","target_branch","finish"]),t);let r=Se(i.isolation,["current","branch","worktree"],`${t}.isolation`),n=Sh(i.change_branch,`${t}.change_branch`),a=Sh(i.target_branch,`${t}.target_branch`),o=i.finish===null?null:Se(i.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(r==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(r==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(r!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:r,change_branch:n,target_branch:a,finish:o}}function DT(e){let t="Native loop",i=Xe(e,t);Qe(i,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let r=Sl(i.previous_unresolved_ids,`${t}.previous_unresolved_ids`);an(r,`${t}.previous_unresolved_ids`);let n=i.stop_reason===void 0?void 0:Se(i.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:Se(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:me(i.goal_cycle,`${t}.goal_cycle`,1),iteration:me(i.iteration,`${t}.iteration`),attempt:me(i.attempt,`${t}.attempt`),retry_epoch:me(i.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:me(i.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:me(i.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:me(i.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:r,next_action:Sh(i.next_action,`${t}.next_action`)}}function LT(e,t){let i=`Native acceptance[${t}]`,r=Xe(e,i);Qe(r,new Set(["id","source","text","result","reason"]),i);let n=Te(r.id,`${i}.id`);if(!_T.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:Eh(r.source,`${i}.source`),text:Te(r.text,`${i}.text`),result:Se(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:At(r.reason,`${i}.reason`)}}function MT(e,t){let i=`Native builder_handoff.checks[${t}]`,r=Xe(e,i);return Qe(r,new Set(["name","result","note"]),i),{name:At(r.name,`${i}.name`),result:Se(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:At(r.note,`${i}.note`)}}function FT(e){let t="Native builder_handoff",i=Xe(e,t);Qe(i,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let r=Sl(i.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);an(r,`${t}.addressed_acceptance_ids`);let n=i.review===null||i.review===void 0?null:Xe(i.review,`${t}.review`);return n&&Qe(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:Te(i.candidate_id,`${t}.candidate_id`),identity_provider:Te(i.identity_provider,`${t}.identity_provider`),builder_execution_ref:Te(i.builder_execution_ref,`${t}.builder_execution_ref`),iteration:me(i.iteration,`${t}.iteration`,1),summary:At(i.summary,`${t}.summary`),addressed_acceptance_ids:r,checks:ui(i.checks,`${t}.checks`,MT),checks_truncated:ea(i.checks_truncated,`${t}.checks_truncated`),known_limits:ui(i.known_limits,`${t}.known_limits`,(a,o)=>At(a,`${t}.known_limits[${o}]`)),known_limits_truncated:ea(i.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:Se(n.status,["passed"],`${t}.review.status`),summary:At(n.summary,`${t}.review.summary`),reviewer_execution_ref:Te(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:ta(i.submitted_at,`${t}.submitted_at`)}}function BT(e,t){let i=`Native blockers[${t}]`,r=Xe(e,i);Qe(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=Sl(r.acceptance_ids,`${i}.acceptance_ids`);return an(n,`${i}.acceptance_ids`),{owner:Se(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:At(r.reason,`${i}.reason`),acceptance_ids:n,resolution_action:Se(r.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${i}.resolution_action`)}}function VT(e,t){let i=`Native verification.checks[${t}]`,r=Xe(e,i);return Qe(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:Te(r.id,`${i}.id`),name:At(r.name,`${i}.name`),argv_display:ui(r.argv_display,`${i}.argv_display`,(n,a)=>At(n,`${i}.argv_display[${a}]`)),argv_truncated:ea(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:Eh(r.cwd_ref,`${i}.cwd_ref`,!0),status:Se(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:$T(r.exit_code,`${i}.exit_code`),duration_ms:me(r.duration_ms,`${i}.duration_ms`)}}function qT(e){let t="Native verification",i=Xe(e,t);Qe(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let r=ui(i.checks,`${t}.checks`,VT);an(r.map(a=>a.id),`${t}.checks IDs`);let n=Te(i.identity_provider,`${t}.identity_provider`);return{candidate_id:Te(i.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:Te(i.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:me(i.iteration,`${t}.iteration`,1),attempt:me(i.attempt,`${t}.attempt`,1),assurance:i.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":Se(i.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:Se(i.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:r,summary:At(i.summary,`${t}.summary`),risks:ui(i.risks,`${t}.risks`,(a,o)=>At(a,`${t}.risks[${o}]`)),risks_truncated:ea(i.risks_truncated,`${t}.risks_truncated`),completed_at:ta(i.completed_at,`${t}.completed_at`)}}function Ly(e,t){let i=`Native history[${t}]`,r=Xe(e,i);Qe(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=Sl(r.unresolved_ids,`${i}.unresolved_ids`);return an(n,`${i}.unresolved_ids`),{goal_cycle:me(r.goal_cycle,`${i}.goal_cycle`,1),iteration:me(r.iteration,`${i}.iteration`),attempt:me(r.attempt,`${i}.attempt`),outcome:Se(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:At(r.summary,`${i}.summary`),completed_at:ta(r.completed_at,`${i}.completed_at`)}}function WT(e){let t="Native history_overflow.outcome_counts",i=Xe(e,t),r=["pass","fail","blocked","execution-error","recovery"];return Qe(i,new Set(r),t),{pass:me(i.pass,`${t}.pass`),fail:me(i.fail,`${t}.fail`),blocked:me(i.blocked,`${t}.blocked`),"execution-error":me(i["execution-error"],`${t}.execution-error`),recovery:me(i.recovery,`${t}.recovery`)}}function zT(e){let t="Native history_overflow",i=Xe(e,t);Qe(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let r=me(i.dropped_entries,`${t}.dropped_entries`),n=i.first_dropped_at===null?null:ta(i.first_dropped_at,`${t}.first_dropped_at`),a=i.last_dropped_at===null?null:ta(i.last_dropped_at,`${t}.last_dropped_at`);if(r===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(r>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=WT(i.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==r)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:r,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function JT(e){let t=new Set(e.acceptance.map(i=>i.id));for(let i of e.loop.previous_unresolved_ids)if(!t.has(i))throw new Error(`Native loop references unknown acceptance ID ${i}`);for(let i of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(i))throw new Error(`Native builder handoff references unknown ID ${i}`);for(let i of e.blockers)for(let r of i.acceptance_ids)if(!t.has(r))throw new Error(`Native blocker references unknown ID ${r}`);if(e.builder_handoff){if(!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let r=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!r&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function GT(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let i=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(i!==null&&e.loop.stage!==i)throw new Error(`Native status ${e.status} requires loop stage ${i}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(r=>r.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(r=>r.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function ct(e){let t=Xe(e,"Native portable state");if(Qe(t,IT,"Native portable state"),t.schema!==Zn)throw new Error(`Native portable state schema must be ${Zn}`);let i=Te(t.name,"Native state name");if(!xT.test(i))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let r=ui(t.spec_changes,"Native spec_changes",OT);an(r.map(s=>s.capability),"Native spec change capabilities");let n=ui(t.acceptance,"Native acceptance",LT);an(n.map(s=>s.id),"Native acceptance IDs");let a=ui(t.history,"Native history",Ly);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Zn,name:i,language:Se(t.language,["en","zh-CN"],"Native state language"),phase:Se(t.phase,["shape","build","verify","archive"],"Native state phase"),status:Se(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:me(t.state_version,"Native state_version",1),brief:"brief.md",...t.children_contract_hash===void 0?{}:{children_contract_hash:jT(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:Se(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:r,workspace:HT(t.workspace),loop:DT(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:FT(t.builder_handoff),blockers:ui(t.blockers,"Native blockers",BT),verification:t.verification===null?null:qT(t.verification),history:a,history_overflow:zT(t.history_overflow),verification_result:Se(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:Se(t.verification_report,["verification.md"],"Native verification_report"),archived:ea(t.archived,"Native archived"),created_at:ta(t.created_at,"Native created_at")};return JT(o),GT(o),o}function on(e,t){let i=ct(e),r=Ly(t,i.history.length),n=[...i.history,r],a={...i.history_overflow,outcome_counts:{...i.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return ct({...i,history:n,history_overflow:a})}function UT(e,t){let i=(0,kl.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`${t} is invalid YAML: ${i.errors[0].message}`);return i.toJS({mapAsMap:!1})}async function Ze(e){let t=await CT.readFile(e,"utf8");return ct(UT(t,"Native portable state"))}async function El(e,t,i={}){let r=ct(t);await he(e,(0,kl.stringify)(r),i)}var Nl=new Map;async function KT(e,t){let i=Nl.get(e)??Promise.resolve(),r,n=new Promise(o=>{r=o}),a=i.then(()=>n);Nl.set(e,a),await i;try{return await t()}finally{r(),Nl.get(e)===a&&Nl.delete(e)}}async function sn(e){return KT(e.file,async()=>{let t=me(e.expectedStateVersion,"Native expected state version",1),i=ct(e.next);if(i.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let r=await Ze(e.file);if(r.state_version===i.state_version&&JSON.stringify(r)===JSON.stringify(i))return r;if(r.state_version!==t)throw new bl(t,r.state_version);return await El(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Ze(e.file);if(n.state_version!==t)throw new bl(t,n.state_version)}}),i})}function YT(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function Ii(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(YT(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let i="",r=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(r+a>t)break;i+=n,r+=a}return{text:i,truncated:!0}}var Ne="comet.native.v3",be="comet.native.v2",et="comet.native.v1",vr="comet.native.transition.v3",ji="comet.native.transition.v2",cn="comet.native.transition.v1";var Pl="comet.native.portable-migration.v1",QT=new Set(["schema","id","change","fromSchema","status","createdAt"]),ZT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,eI=/^[a-z0-9][a-z0-9-]{7,127}$/u,tI=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),iI=new Set([et,be,Ne]);function rI(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function nI(e,t){let i=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(i.valueOf()))throw new Error(`${t} must be a valid timestamp`);return i.toISOString()}function aI(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function oI(e){return e.schema===et?ln(e):e.schema===be?di(e):lt(e)}function sI(e){return XT.posix.normalize(e.replaceAll("\\","/"))}function cI(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:sI(t.source)})}function lI(e){return e==="shape"?"shape":"build"}function uI(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function dI(e,t,i){return e==="zh-CN"?`从旧版 ${t} ${i} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${i} state; prior Loop, verification results, and execution records were not inherited.`}function My(e){let t=oI(e.state);Oy(e.acceptance);let i=lI(t.phase),r=i==="shape"?0:1,n=nI(e.migratedAt??`${t.created_at}T00:00:00.000Z`,"Native portable migration time"),a=e.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return ct({schema:Zn,name:t.name,language:t.language,phase:i,status:"active",state_version:1,brief:"brief.md",spec_changes:cI(t),workspace:e.workspace,loop:{stage:i==="shape"?"shape":"building",goal_cycle:1,iteration:r,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:uI(t.language,i)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:r,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:Ii(dI(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:bh(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function Ph(e){let t=rI(e,"Native portable migration transaction"),i=Object.keys(t).filter(r=>!QT.has(r));if(i.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${i.join(", ")}`);if(t.schema!==Pl)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!eI.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!ZT.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!iI.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!tI.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Pl,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:aI(t.createdAt,"Native portable migration transaction createdAt")}}function Fy(e){switch(Ph(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 Rl="comet.native.archive-transaction.v4",By="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",hI=new RegExp(`^portable-archive-(${By})\\.json$`,"u"),pI=new RegExp(`^portable-migration-(${By})\\.json$`,"u"),mI=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,vI=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,gI=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),wI=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),yI=new Set(["capability","operation","source","content"]),Vy=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function qy(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Wy(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(Object.keys(e).length!==t.size)throw new Error(`${i} fields are invalid`)}function NI(e,t){let i=`Native portable Archive spec_changes[${t}]`,r=qy(e,i);if(Wy(r,yI,i),typeof r.capability!="string"||!Vy.test(r.capability))throw new Error(`${i}.capability is invalid`);if(!["create","modify","remove"].includes(String(r.operation)))throw new Error(`${i}.operation is invalid`);let n=r.operation;if(n==="remove"){if(r.source!==null||r.content!==null)throw new Error(`${i} remove requires source and content null`);return{capability:r.capability,operation:n,source:null,content:null}}if(typeof r.source!="string"||r.source.length===0||r.source.includes("\\")||r.source.startsWith("/")||/^[A-Za-z]:/u.test(r.source)||r.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${i}.${n} source is invalid`);if(typeof r.content!="string")throw new Error(`${i}.${n} content is invalid`);return{capability:r.capability,operation:n,source:r.source,content:r.content}}function bI(e){let t=qy(e,"Native portable Archive transaction");if(Wy(t,wI,"Native portable Archive transaction"),t.schema!==Rl)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!mI.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Vy.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"||!vI.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"||!gI.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let i=t.spec_changes.map(NI);if(new Set(i.map(({capability:n})=>n)).size!==i.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>i.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let r=new Date(t.created_at);if(Number.isNaN(r.valueOf())||r.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:Rl,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:i,created_at:t.created_at}}function un(e){let t=hI.exec(e);if(t)return{kind:"archive",change:t[1]};let i=pI.exec(e);return i?{kind:"migration",change:i[1]}:null}function gr(e,t){let i=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,r=un(i);if(!r||r.kind!==t.kind||r.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return Rh.join(e.transactionsDir,i)}async function qo(e,t){let i=un(t);if(!i)return null;let r=await Z({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(r.text),a=Rh.join(e.transactionsDir,t);if(i.kind==="archive"){let s=bI(n);if(s.change!==i.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:i.change,file:a,journal:s}}let o=Ph(n);if(o.change!==i.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:i.change,file:a,journal:o}}async function ia(e,t){let i=gr(e,t);try{return await qo(e,Rh.basename(i))}catch(r){if(r.code==="ENOENT")return null;throw r}}async function zy(e){let t;try{t=await fI.readdir(e.transactionsDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}return t.map(({name:i})=>i).filter(i=>un(i)!==null).sort((i,r)=>i.localeCompare(r,"en"))}function Jy(e){return e.kind==="archive"||e.journal.status!=="committed"}import{promises as Wo}from"fs";import _t from"path";import{TextDecoder as RI}from"util";import{createHash as kI}from"node:crypto";import{constants as Cl,promises as W}from"node:fs";import Y from"node:path";import{TextDecoder as SI}from"node:util";function ze(e,t){let i=Y.relative(e,t);return i===""||!Y.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Y.sep}`)}function Gy(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function na(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Uy(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 z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function wr(e,t){let i=await W.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await W.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function yr(e,t,i){let r=Y.resolve(e),n=Y.resolve(t);if(!ze(r,n))throw new Error(`${i} is outside its managed root`);let a=[await wr(r,i)],o=r;for(let s of Y.relative(r,n).split(Y.sep).filter(Boolean)){await we(a,i),o=Y.join(o,s);let c=await wr(o,i);if(!ze(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await we(a,i),a}async function we(e,t){for(let i of e){let r=await W.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!na(i,r)||await W.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function EI(e,t,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${i} exceeds ${t} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function re(e){let t=Gy(e.maxBytes),i=Y.resolve(e.file),r=await yr(e.root,Y.dirname(i),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>wr(Y.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await we(r,e.label);let a=await W.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=Uy(a),s=await W.realpath(i);if(!ze(r[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>ze(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Cl.O_RDONLY:Cl.O_RDONLY|Cl.O_NOFOLLOW|Cl.O_NONBLOCK,l=await W.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([W.lstat(i),W.realpath(i)]);if(await we(r,e.label),await we(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!ra(o,u)||!ra(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let h=await EI(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,m,p]=await Promise.all([l.stat(),W.lstat(i),W.realpath(i)]);if(await we(r,e.label),await we(n,e.label),!m.isFile()||m.isSymbolicLink()||p!==s||!ra(o,v)||!ra(o,m))throw new Error(`${e.label} changed while reading`);return{bytes:h,hash:kI("sha256").update(h).digest("hex"),size:h.length}}finally{await l.close()}}async function xl(e){let t=await re(e),i;try{i=new SI("utf-8",{fatal:!0}).decode(t.bytes)}catch(r){throw new Error(`${e.label} is not valid UTF-8`,{cause:r})}return{...t,text:i}}async function wt(e){let t=await yr(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await W.readdir(e.directory,{withFileTypes:!0});else{let r=Gy(e.maxEntries);i=[];let n=await W.opendir(e.directory);try{for await(let a of n)if(i.push(a),i.length>r)throw new Error(`${e.label} exceeds ${r} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await we(t,e.label),{entries:i,verify:()=>we(t,e.label)}}async function Zt(e){let t=await yr(e.root,e.directory,e.label);return{verify:()=>we(t,e.label)}}async function PI(e){let t=Y.resolve(e.directory),i=Y.resolve(e.quarantine);if(Y.dirname(i)!==Y.dirname(t)||!ze(Y.resolve(e.root),i)||i===t)throw new Error(`${e.label} quarantine must be a distinct sibling inside its root`);let r=await yr(e.root,Y.dirname(t),e.label),n=await wr(t,e.label);if(!ze(r[0].realPath,n.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeQuarantine?.(),await we(r,e.label);let a=await W.lstat(t);if(!a.isDirectory()||a.isSymbolicLink()||!na(n,a)||await W.realpath(t)!==n.realPath)throw new Error(`${e.label} changed before quarantine`);try{throw await W.lstat(i),new Error(`${e.label} quarantine path is occupied`)}catch(s){if(s.code!=="ENOENT")throw s}await W.rename(t,i),await we(r,e.label);let o=await W.lstat(i);if(!o.isDirectory()||o.isSymbolicLink()||!na(n,o))throw new Error(`${e.label} changed while quarantining`);await e.afterQuarantine?.(i);try{throw await W.lstat(t),new Error(`${e.label} path was recreated while quarantining`)}catch(s){if(s.code!=="ENOENT")throw s}return{quarantine:i,parentChain:r,identity:n}}async function Ky(e){await PI(e)}async function Al(e){let t=Y.resolve(e.file),i=await yr(e.root,Y.dirname(t),e.label),r=await W.lstat(t);if(!r.isFile()||r.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let n=Uy(r),a=await W.realpath(t);if(!ze(i[0].realPath,a))throw new Error(`${e.label} resolves outside its managed root`);let o=await re({root:e.root,file:t,maxBytes:e.maxBytes,label:e.label});if(o.hash!==e.expectedHash||o.size!==e.expectedSize)throw new Error(`${e.label} changed before removal`);let[s,c]=await Promise.all([W.lstat(t),W.realpath(t)]);if(!s.isFile()||s.isSymbolicLink()||!ra(n,s)||c!==a)throw new Error(`${e.label} changed while verifying removal`);await e.beforeRemove?.(),await we(i,e.label);let[l,u]=await Promise.all([W.lstat(t),W.realpath(t)]);if(!l.isFile()||l.isSymbolicLink()||!ra(n,l)||u!==a)throw new Error(`${e.label} changed before removal`);await W.rm(t),await we(i,e.label)}async function Ch(e){let t=Y.resolve(e.directory),i=await yr(e.root,Y.dirname(t),e.label),r=await wr(t,e.label);if(!ze(i[0].realPath,r.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeRemove?.(),await we(i,e.label);let n=await W.lstat(t);if(!n.isDirectory()||n.isSymbolicLink()||!na(r,n)||await W.realpath(t)!==r.realPath)throw new Error(`${e.label} changed before removal`);await W.rmdir(t),await we(i,e.label)}async function fi(e){let t=Y.resolve(e.root),i=Y.resolve(e.directory);if(!ze(t,i))throw new Error(`${e.label} is outside its managed root`);let r=[await wr(t,e.label)],n=t;for(let a of Y.relative(t,i).split(Y.sep).filter(Boolean)){await we(r,e.label),n=Y.join(n,a);try{await W.mkdir(n)}catch(s){if(s.code!=="EEXIST")throw s}let o=await wr(n,e.label);if(!ze(r[0].realPath,o.realPath))throw new Error(`${e.label} resolves outside its managed root: ${n}`);r.push(o)}await we(r,e.label)}async function xh(e){let t=Y.resolve(e.root),i=Y.resolve(e.source),r=Y.resolve(e.target);if(i===r||!ze(t,i)||!ze(t,r)||ze(i,r)||ze(r,i))throw new Error(`${e.label} source and target must be distinct paths inside one root`);await fi({root:t,directory:Y.dirname(r),label:`${e.label} target parent`});let n=await yr(t,Y.dirname(i),e.label),a=await yr(t,Y.dirname(r),e.label),o=await wr(i,e.label);if(!ze(n[0].realPath,o.realPath))throw new Error(`${e.label} source resolves outside its managed root`);try{throw await W.lstat(r),new Error(`${e.label} target already exists`)}catch(l){if(l.code!=="ENOENT")throw l}await e.beforeMove?.(),await Promise.all([we(n,e.label),we(a,e.label)]);let s=await W.lstat(i);if(!s.isDirectory()||s.isSymbolicLink()||!na(o,s)||await W.realpath(i)!==o.realPath)throw new Error(`${e.label} source changed before move`);await W.rename(i,r),await Promise.all([we(n,e.label),we(a,e.label)]);let c=await W.lstat(r);if(!c.isDirectory()||c.isSymbolicLink()||!na(o,c)||!ze(n[0].realPath,await W.realpath(r)))throw new Error(`${e.label} source identity changed while moving`);try{throw await W.lstat(i),new Error(`${e.label} source was recreated while moving`)}catch(l){if(l.code!=="ENOENT")throw l}}async function Nr(e){let t=await re({root:e.sourceRoot,file:e.source,maxBytes:e.maxBytes,label:e.label,hooks:e.hooks,forbiddenRoots:e.forbiddenRoots});if(e.expectedHash!==void 0&&t.hash!==e.expectedHash)throw new Error(`${e.label} content changed before copy`);await Uw(e.target,t.bytes,{containedRoot:e.targetRoot,exclusive:e.exclusive,beforeCommit:async()=>{if(await e.hooks?.beforeTargetCommit?.(),e.expectedTargetHash===void 0)return;if(e.expectedTargetHash===null){try{await W.lstat(e.target)}catch(n){if(n.code==="ENOENT")return;throw n}throw new Error(`${e.label} target changed before commit`)}if((await re({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} existing target`})).hash!==e.expectedTargetHash)throw new Error(`${e.label} target changed before commit`)}});let i=await re({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} target`});if(i.hash!==t.hash||i.size!==t.size)throw new Error(`${e.label} target could not be verified`);return i}var CI=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),xI=new Set(["id","type","source","target","staged","backup"]),AI=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),_I=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),TI=new Set(["sequence","timestamp","type","operationId"]),Zy=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),eN=new Set(["prepared","operation-started","operation-completed","archive-finalization-started","archive-finalized","commit","rollback-started","rollback-completed"]),II=256*1024,jI=1024*1024,tN=16*1024,Tl=1024,Th=64*1024*1024,$I=2e4,iN=new RI("utf-8",{fatal:!0});function zo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Jo(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function oa(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Ah(e,t){if(typeof e!="string"||e.length===0||_t.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function _l(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function Yy(e,t){if(Ah(e,t),e.includes("\\")||e!==_t.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function OI(e,t){let i=zo(e,`transaction operations[${t}]`);if(Jo(i,xI,`transaction operations[${t}]`),typeof i.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.id))throw new Error(`transaction operations[${t}].id is invalid`);if(i.type!=="write"&&i.type!=="remove"&&i.type!=="move")throw new Error(`transaction operation ${i.id} has an invalid type`);Ah(i.target,`transaction operation ${i.id} target`);for(let r of["source","staged","backup"])i[r]!==void 0&&Ah(i[r],`transaction operation ${i.id} ${r}`);if(i.type==="write"){if(i.staged===void 0||i.source!==void 0)throw new Error(`write operation ${i.id} requires staged and forbids source`)}else if(i.type==="remove"){if(i.source!==void 0||i.staged!==void 0)throw new Error(`remove operation ${i.id} forbids source and staged`)}else if(i.source===void 0||i.staged!==void 0||i.backup!==void 0)throw new Error(`move operation ${i.id} requires source and forbids staged and backup`);return i}function jl(e){let t=zo(e,"Native Archive transaction journal");if(Jo(t,AI,"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"||!Zy.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(!oa(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(_l(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let i=t.operations.map((s,c)=>{let l=zo(s,`Archive transaction operations[${c}]`);if(Jo(l,_I,`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`);Yy(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&Yy(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&_l(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(_l(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);_l(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),r=i.map(s=>s.id);if(new Set(r).size!==r.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=i.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||i.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of i.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:i}}function Ih(e){let t=zo(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return jl(t);if(Jo(t,CI,"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"||!Zy.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!_t.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!_t.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!oa(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let i=t.operations.map(OI),r=i.map(n=>n.id);if(new Set(r).size!==r.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:i}}function rN(e,t){let i=zo(e,`Native transaction event at line ${t}`);if(Jo(i,TI,`Native transaction event at line ${t}`),i.sequence!==t)throw new Error(`Native transaction event sequence at line ${t} must be ${t}`);if(!oa(i.timestamp))throw new Error(`Native transaction event timestamp at line ${t} is invalid`);if(typeof i.type!="string"||!eN.has(i.type))throw new Error(`Native transaction event type at line ${t} is invalid`);let r=i.type==="operation-started"||i.type==="operation-completed";if(r&&(typeof i.operationId!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.operationId)||Buffer.byteLength(i.operationId,"utf8")>256)||!r&&i.operationId!==void 0)throw new Error(`Native transaction event operationId at line ${t} is invalid`);return{sequence:i.sequence,timestamp:i.timestamp,type:i.type,...typeof i.operationId=="string"?{operationId:i.operationId}:{}}}function HI(e){if(e.length>24)return!1;let t="0000-00-00T00:00:00.000Z";for(let r=0;r<e.length;r+=1){let n=t[r],a=e[r];if(n==="0"){if(!/[0-9]/u.test(a))return!1}else if(a!==n)return!1}let i=[[5,2,1,12],[8,2,1,31],[11,2,0,23],[14,2,0,59],[17,2,0,59],[20,3,0,999]];for(let[r,n,a,o]of i){if(e.length<=r)continue;let s=e.slice(r,Math.min(r+n,e.length));if(!Array.from({length:o-a+1},(l,u)=>String(a+u).padStart(n,"0")).some(l=>l.startsWith(s)))return!1}return e.length>=10&&!oa(`${e.slice(0,10)}T00:00:00.000Z`)?!1:e.length<24||oa(e)}function aa(e,t){return e.length<t.length&&t.startsWith(e)}function DI(e){let t='","operationId":"';if(aa(e,t))return!0;if(!e.startsWith(t))return!1;let i=e.slice(t.length),r=i.indexOf('"');if(r===-1)return i.length===0||/^[a-z0-9][a-z0-9-]*$/u.test(i);let n=i.slice(0,r);return/^[a-z0-9][a-z0-9-]*$/u.test(n)?aa(i.slice(r),'"}'):!1}function LI(e,t){if(e.length===0||Buffer.byteLength(e,"utf8")>tN)return!1;let i=`{"sequence":${t},"timestamp":"`;if(aa(e,i))return!0;if(!e.startsWith(i))return!1;let r=e.slice(i.length),n=r.slice(0,Math.min(24,r.length));if(!HI(n))return!1;if(r.length<24)return!0;if(!oa(n))return!1;let a='","type":"',o=r.slice(24);if(aa(o,a))return!0;if(!o.startsWith(a))return!1;let s=o.slice(a.length);for(let c of eN){if(aa(s,c))return!0;if(!s.startsWith(c))continue;let l=s.slice(c.length);if(c==="operation-started"||c==="operation-completed"){if(DI(l))return!0}else if(aa(l,'"}'))return!0}return!1}function MI(e,t){if(e.length===0)throw new Error("Blank transaction event line");if(Buffer.byteLength(e,"utf8")>tN)throw new Error(`Native transaction event at line ${t} is too large`);return rN(JSON.parse(e),t)}function FI(e){let t=e.split(`
180
+ `),i=t.at(-1)==="";if(i&&t.pop(),t.length>Tl)throw new Error(`Native transaction event log exceeds ${Tl} events`);let r=[];for(let n=0;n<t.length;n+=1){let a=n+1,o=t[n],s=o.endsWith("\r")?o.slice(0,-1):o,c=!i&&n===t.length-1;try{r.push(MI(s,a))}catch(l){if(c){let u=!1;try{JSON.parse(s),u=!0}catch{}if(!u&&LI(s,a))break}throw new Error(`Invalid Native transaction event at line ${a}`,{cause:l})}}return r}function nN(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
181
181
  `)}
182
- `}function OI(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return _t.join(e.transactionsDir,t)}function Al(e,t){let i=OI(e,t);return{directory:i,journal:_t.join(i,"transaction.json"),events:_t.join(i,"events.jsonl"),staged:_t.join(i,"staged"),backups:_t.join(i,"backups")}}async function hi(e,t){let i=Al(e,t);return await Promise.all(Object.values(i).map(r=>T(e.runtimeDir,r))),i}function HI(e,t){if(t.length===0||_t.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Unsafe Native transaction ref: ${t}`);let i="runtime/",r=t==="runtime"||t.startsWith(i),n=r?e.runtimeDir:e.nativeRoot,a=t==="runtime"?"":r?t.slice(i.length):t,o=_t.resolve(n,...a.split(/[\\/]/u));if(!O(n,o))throw new Error(`Unsafe Native transaction ref: ${t}`);return o}async function yr(e,t){let i=HI(e,t);return T(j(e,i),i)}async function cn(e){try{return await Fo.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Th(e,t,i={}){let r=await hi(e,t);try{await Fo.lstat(r.events)}catch(n){if(n.code==="ENOENT")return{exists:!1,hash:null,size:0,events:[],canonicalSource:"",needsRepair:!1};throw n}try{let n=await re({root:e.runtimeDir,file:r.events,maxBytes:CI,label:`Native transaction event log ${t}`,hooks:i.hooks}),a;try{a=tN.decode(n.bytes)}catch(c){throw new Error(`Native transaction event log ${t} is not valid UTF-8`,{cause:c})}let o=$I(a),s=rN(o);return{exists:!0,hash:n.hash,size:n.size,events:o,canonicalSource:s,needsRepair:a!==s}}catch(n){throw n.code==="ENOENT"?new Error(`Native transaction event log ${t} changed while reading`,{cause:n}):n}}async function Yy(e,t,i){let r=await Th(e,t);if(r.exists!==i.exists||r.hash!==i.hash||r.size!==i.size)throw new Error(`Native transaction event log ${t} changed before append`)}async function Tt(e,t,i,r){let n=await hi(e,t),a=await Th(e,t),o=a.events.find(c=>c.type===i&&c.operationId===r);if(o)return a.needsRepair&&await he(n.events,a.canonicalSource,{containedRoot:e.runtimeDir,beforeCommit:()=>Yy(e,t,a)}),o;if(a.events.length>=Rl)throw new Error(`Native transaction event log ${t} exceeds ${Rl} events`);let s={sequence:a.events.length+1,timestamp:new Date().toISOString(),type:i,...r?{operationId:r}:{}};return iN(s,s.sequence),await Fo.mkdir(n.directory,{recursive:!0}),await he(n.events,rN([...a.events,s]),{containedRoot:e.runtimeDir,beforeCommit:()=>Yy(e,t,a)}),s}async function nN(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");t=_h(t);let i=await hi(e,t.id);await Fo.mkdir(i.staged,{recursive:!0}),await Fo.mkdir(i.backups,{recursive:!0}),await ee(i.journal,t,{containedRoot:e.runtimeDir}),await Tt(e,t.id,"prepared")}async function yt(e,t,i={}){let r=await hi(e,t),n=await re({root:e.runtimeDir,file:r.journal,maxBytes:RI,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(tN.decode(n.bytes)),o=_h(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function Nr(e,t,i={}){return(await Th(e,t,i)).events}async function Cl(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let r=_h({...t,status:i});return await ee((await hi(e,t.id)).journal,r,{containedRoot:e.runtimeDir}),r}async function xh(e,t,i){try{return await re({root:j(e,t),file:t,maxBytes:Ah,label:i})}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Ih(e,t,i,r){let n=await xh(e,t,`${r} source`);if(!n)throw new Error(`${r} source does not exist`);let a=await xh(e,i,`${r} target`);await fi({root:j(e,i),directory:_t.dirname(i),label:`${r} target parent`}),await wr({sourceRoot:j(e,t),source:t,targetRoot:j(e,i),target:i,maxBytes:Ah,label:r,expectedHash:n.hash,expectedTargetHash:a?.hash??null,exclusive:a===null})}async function aN(e,t,i){let r=await xh(e,t,i);r&&await El({root:j(e,t),file:t,maxBytes:Ah,expectedHash:r.hash,expectedSize:r.size,label:i})}async function Xy(e,t){if(!t.backup)return;let i=await yr(e,t.target),r=await yr(e,t.backup);!await cn(i)||await cn(r)||await Ih(e,i,r,`Legacy Native transaction backup ${t.id}`)}async function DI(e,t){let i=await yr(e,t.target);if(t.type==="write"){if(!t.staged)throw new Error(`Write operation ${t.id} has no staged ref`);await Xy(e,t),await Ih(e,await yr(e,t.staged),i,`Legacy Native transaction write ${t.id}`);return}if(t.type==="remove"){await Xy(e,t),await aN(e,i,`Legacy Native transaction remove ${t.id}`);return}if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let r=await yr(e,t.source),[n,a]=await Promise.all([cn(r),cn(i)]);if(!n&&a){await(await wt({root:j(e,i),directory:i,label:`Legacy Native transaction move target ${t.id}`,maxEntries:xI})).verify();return}if(a)throw new Error(`Move target already exists: ${t.target}`);if(!n)throw new Error(`Move source does not exist: ${t.source}`);await Rh({root:j(e,r),source:r,target:i,label:`Legacy Native transaction move ${t.id}`})}async function oN(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let r=t.status==="prepared"?await Cl(e,t,"applying"):t,n=await Nr(e,t.id),a=new Set(n.filter(s=>s.type==="operation-completed").map(s=>s.operationId)),o=a.size;for(let s of r.operations)a.has(s.id)||(await Tt(e,r.id,"operation-started",s.id),await DI(e,s),await Tt(e,r.id,"operation-completed",s.id),o+=1,await i?.afterOperation?.(s,o));return r=await yt(e,r.id),r}async function LI(e,t){let i=await yr(e,t.target),r=t.backup?await yr(e,t.backup):null;if(t.type==="move"){if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let n=await yr(e,t.source);if(await cn(i)){if(await cn(n))throw new Error(`Legacy Native rollback source already exists: ${t.source}`);await Rh({root:j(e,i),source:i,target:n,label:`Legacy Native transaction rollback move ${t.id}`})}return}r&&await cn(r)?await Ih(e,r,i,`Legacy Native transaction rollback restore ${t.id}`):await aN(e,i,`Legacy Native transaction rollback remove ${t.id}`)}async function _l(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let i=await Nr(e,t.id);if(i.some(a=>a.type==="archive-finalization-started"||a.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let r=await Cl(e,t,"rolling-back");await Tt(e,r.id,"rollback-started");let n=new Set(i.filter(a=>a.type==="operation-started"||a.type==="operation-completed").map(a=>a.operationId));for(let a of[...r.operations].reverse())n.has(a.id)&&await LI(e,a);return await Tt(e,r.id,"rollback-completed"),r=await Cl(e,r,"rolled-back"),r}async function ta(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");return await Tt(e,t.id,i),i==="commit"?Cl(e,t,"committed"):t}async function BI(e,t,i){let r;try{r=await MI.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await yt(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of r)if(sn(n.name))try{let a=await Mo(e,n.name);if(!a||i?.kind===a.kind&&i.change===a.change)continue;if(zy(a))return!0}catch{return!0}return!1}async function VI(e,t){let i=Date.now()+5e3,r=FI.join(e.locksDir,"root-move.lock");for(;;)try{return await dr(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await $o(r);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=i)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function se(e,t,i,r){let n=await VI(e,t);try{if(await Wn(e.projectRoot),await BI(e,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await fr(n)}}function sN(e){return Number.isSafeInteger(e)&&e>=1}async function cN(e){if(!sN(e.expectedRevision))throw new Error("Native expected revision must be a positive integer");if(e.next.revision!==e.expectedRevision+1)throw new Error("Native CAS next revision must increment the expected revision exactly once");let t=await e.read();if(!sN(t.revision))throw new Error("Native current revision must be a positive integer");let i=e.equals??((r,n)=>JSON.stringify(r)===JSON.stringify(n));if(t.revision===e.next.revision&&i(t,e.next))return t;if(t.revision!==e.expectedRevision)throw e.conflict(t.revision);return await e.write(e.next),e.next}import{createHash as Ol}from"crypto";import{spawn as wN}from"node:child_process";import{promises as ce}from"fs";import V from"path";import{createHash as lN}from"crypto";import{createReadStream as qI}from"fs";async function Zt(e){let t=lN("sha256");for await(let i of qI(e))t.update(i);return t.digest("hex")}function L(e){return lN("sha256").update(e).digest("hex")}var Tl={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},Lh=1e3,WI=8*1024*1024,zI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,JI=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),GI=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),UI=new Set(["schema","include","exclude","hash"]),KI=new Set(["provider","gitSelection","physicalSelection","projection"]),YI=new Set(["provider","selection"]),XI=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),QI=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),ZI=new Set(["schema","status","before","after"]),ej=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),tj=new Set(["path","hash","size","type","gitObjectId"]),ij=new Set(["path","size","type","reason"]),rj=new Set(["ref","hash","count"]),nj=new Set(["change-created","legacy-migration","explicit"]),aj=new Set(["file","directory","other"]),oj=new Set(["file-size","file-count","total-size","manifest-size","changed-during-read","unreadable","gitlink-unavailable","gitlink-dirty","gitlink-changed","legacy-gitlink-boundary","git-enumeration-limit","git-selection-changed","physical-enumeration-limit","physical-selection-changed"]),Hl=/^[a-f0-9]{64}$/u,yN=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,sj=new Set(["EACCES","EPERM"]),oa=64*1024,Hh=64*1024,cj=6e4,lj=1e3,uj=2,Mh={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},dj={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function NN(e){let t=e.deadlineMs??cj;if(!Number.isSafeInteger(t)||t<1)throw new Error("Native snapshot execution budget must be a positive integer");return{deadlineAt:Date.now()+t,gitProcess:e.gitProcess??{command:"git"}}}function ei(e){return Math.max(0,e.deadlineAt-Date.now())}function M(e){return ei(e)>=1}function jh(e){let t=e===void 0?new Error("Native snapshot deadline exceeded while waiting for Git"):new Error("Native snapshot deadline exceeded while waiting for Git",{cause:e});return Object.assign(t,{code:"GIT_SNAPSHOT_TIMEOUT"})}function na(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function fj(e){let t={...dj,...e};if(!Number.isSafeInteger(t.maxNodes)||t.maxNodes<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxPathBytes)||t.maxPathBytes<1||t.maxPathBytes>t.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return t}async function hj(e,t){if(t.terminateTree){await t.terminateTree(e);return}let i=e.pid;if(i===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let r=process.env.SystemRoot??process.env.WINDIR,n=r&&V.win32.isAbsolute(r)?V.win32.resolve(r):"C:\\Windows",a=V.win32.join(n,"System32","taskkill.exe");if(!V.win32.isAbsolute(a))throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git taskkill path is not trusted"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"});let o=()=>new Promise(s=>{let c=!1,l=null,u=null,d=(f,h=!1)=>{c||(c=!0,u&&clearTimeout(u),h&&l?.kill("SIGKILL"),s(f))};try{l=wN(a,["/pid",String(i),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>d(!1)),l.once("close",f=>d(f===0)),u=setTimeout(()=>d(!1,!0),lj),u.unref()}catch{d(!1)}});for(let s=0;s<uj;s+=1)if(await o()){e.kill("SIGKILL");return}throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git process-tree termination could not be confirmed on Windows"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"})}try{process.kill(-i,"SIGKILL")}catch(r){if(r.code!=="ESRCH")throw r}e.kill("SIGKILL")}function Fh(e,t,i,r){let n=ei(e);if(n<1)throw jh();let a=e.gitProcess,o=wN(a.command,[...a.argsPrefix??[],"-C",t,...i],{cwd:t,stdio:[r?"pipe":"ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"}),s=null,c=!1,l=null;o.once("error",h=>{s=h});let u=new Promise(h=>{o.once("close",h)}),d=setTimeout(()=>{c=!0,l=hj(o,a).then(()=>({error:null}),h=>({error:h}))},n);d.unref();let f=u.then(async h=>{if(clearTimeout(d),c){let v=await l;throw v?.error?jh(v.error):jh()}return{code:h,spawnError:s}});return{child:o,completion:f}}function bN(e){let t={...Mh,...e};if(!Number.isSafeInteger(t.maxRecords)||t.maxRecords<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxRecordBytes)||t.maxRecordBytes<1||t.maxRecordBytes>t.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return t}async function Il(e,t,i,r=Hh){let{child:n,completion:a}=Fh(e,t,i,!1),o=[],s=[],c=0,l=0,u=!1;n.stdout.on("data",h=>{let v=Math.max(0,r-l);v>0&&o.push(Buffer.from(h).subarray(0,v)),l+=h.byteLength,l>r&&(u=!0)}),n.stderr.on("data",h=>{if(c>=oa)return;let v=oa-c,m=Buffer.from(h).subarray(0,v);s.push(m),c+=m.byteLength});let{code:d,spawnError:f}=await a;if(d===0&&f===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${i.join(" ")} failed${f?`: ${f.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function $h(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function Wo(e,t,i,r){if(r.outputChunkBytes!==void 0&&(!Number.isSafeInteger(r.outputChunkBytes)||r.outputChunkBytes<1))throw new Error("Native Git output chunk size must be a positive integer");return new Promise((n,a)=>{let{child:o,completion:s}=Fh(e,t,i,r.stdin!==void 0),c=[],l=Ol("sha256"),u=[],d=0,f=0,h=0,v=0,m=Buffer.alloc(0),p=!1,b=!1,g=!1,y=E=>{let k=0;for(;k<E.byteLength;){let S=E.indexOf(0,k),R=S<0?E.byteLength:S,N=E.subarray(k,R);if(!p&&N.byteLength>0&&(m.byteLength+N.byteLength>r.maxRecordBytes?(m=Buffer.alloc(0),p=!0,b=!0):m=Buffer.concat([m,N])),S<0)break;v+=1,m.byteLength===0&&!p&&(g=!0);let w=m.byteLength+1;!p&&v<=r.maxRecords&&h+w<=r.maxBytes?(c.push(m),h+=w):b=!0,m=Buffer.alloc(0),p=!1,k=S+1}};o.stdout.on("data",E=>{l.update(E),f+=E.byteLength,f>r.maxBytes&&(b=!0);let k=r.outputChunkBytes;if(k===void 0){y(E);return}for(let S=0;S<E.byteLength;S+=k)y(E.subarray(S,Math.min(E.byteLength,S+k)))}),o.stderr.on("data",E=>{if(d>=oa)return;let k=oa-d,S=Buffer.from(E).subarray(0,k);u.push(S),d+=S.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:E,spawnError:k})=>{let S=r.acceptedExitCodes??[0];if(E!==null&&S.includes(E)&&k===null&&!g&&m.byteLength===0&&!p){n({records:c,digest:l.digest("hex"),overflow:b,recordCount:v,stdoutBytes:f});return}a(new Error(`git ${i.join(" ")} failed${k?`: ${k.message}`:g||m.byteLength>0||p?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),r.stdin&&o.stdin?.end(r.stdin)})}function jl(e){let t=e.toString("utf8");if(!Buffer.from(t,"utf8").equals(e))throw new Error("Native Git snapshot provider returned non-UTF-8 path data");return t}async function pj(e,t,i){if(i.length===0)return new Set;let r=await Wo(e,t,["check-ignore","--no-index","-z","--stdin"],{...Mh,maxRecords:Math.max(1,i.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${i.join("\0")}\0`,"utf8")});if(r.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(r.records.map(n=>{let a=jl(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function mj(e,t,i){let{child:r,completion:n}=Fh(e,t,i,!1),a=[],o=0,s=!1;r.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),r.stderr.on("data",u=>{if(o>=oa)return;let d=oa-o,f=Buffer.from(u).subarray(0,d);a.push(f),o+=f.byteLength});let{code:c,spawnError:l}=await n;if(c===0&&l===null)return s;throw new Error(`git ${i.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function aa(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||V.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||V.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function vj(e,t){return e.map(i=>{let r=aa(i);if(r===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return r})}async function gj(e){let t=V.resolve(e);for(;;){try{return await ce.lstat(V.join(t,".git")),!0}catch(r){if(r.code!=="ENOENT")throw r}let i=V.dirname(t);if(i===t)return!1;t=i}}async function kN(e,t,i,r={}){let n=V.resolve(t.projectRoot),a=V.join(n,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,a].map(f=>{let h=V.relative(n,V.resolve(f)).replaceAll("\\","/"),v=aa(h);if(v===null)throw new Error("Native Git snapshot exclusion escaped the project root");return v}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`])],c={...i,...r.outputChunkBytes===void 0?{}:{outputChunkBytes:r.outputChunkBytes}},l=await Wo(e,n,["ls-files","--stage","-z",...s],c);await r.afterStageBefore?.();let u=await Wo(e,n,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await r.afterCombined?.();let d=await Wo(e,n,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function SN(e){return{stageBefore:$h(e.stagedBefore),combined:$h(e.combined),stageAfter:$h(e.stagedAfter)}}async function EN(e,t,i=Mh,r={}){let n=V.resolve(t.projectRoot);if(!await gj(n))return null;let a;try{a=await Il(e,n,["rev-parse","--is-inside-work-tree"])}catch(g){throw na(g)?g:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:g})}if(a.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let o;try{o=await kN(e,t,i,r)}catch(g){throw na(g)?g:new Error("Native Git snapshot provider failed after repository detection",{cause:g})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,u=new Set,d=new Map,f=new Set,h=g=>{for(let y of g){let E=jl(y),k=E.indexOf(" ");if(k<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let S=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(E.slice(0,k))?.groups;if(!S)throw new Error("Native Git snapshot provider returned a malformed staged header");let R=aa(E.slice(k+1));if(R===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(R),S.stage==="0"&&d.set(R,S.objectId),S.mode==="160000"&&S.stage==="0"&&f.add(R)}};h(s.records),h(l.records);let v=c.records.map(jl),m=vj(v,"combined"),p=new Set(m.filter(g=>!u.has(g))),b=new Set(m.filter((g,y)=>!u.has(g)&&v[y].endsWith("/")));for(let g of f)b.delete(g);return{tracked:u,trackedObjectIds:d,untracked:p,gitlinks:f,nestedRepositories:b,omissions:[],overflow:null,evidence:null,initialFence:SN(o)}}function kr(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function uN(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function wj(e,t){return!kr(e.stageBefore,e.stageAfter)||!kr(e.stageAfter,t.stageBefore)||!kr(e.combined,t.combined)||!kr(t.stageBefore,t.stageAfter)}async function PN(e,t,i,r,n){let a;try{a=await kN(e,t,i,{...n===void 0?{}:{outputChunkBytes:n}})}catch(u){throw na(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=r.initialFence,s=SN(a),c=uN(o)||uN(s),l=wj(o,s);c&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),l&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),r.evidence=c||l?{schema:"comet.native.git-selection.v1",status:c&&l?"overflow-and-changed":c?"overflow":"changed",...o,finalStageBefore:s.stageBefore,finalCombined:s.combined,finalStageAfter:s.stageAfter}:null,(o.combined.overflow||s.combined.overflow)&&(r.overflow={count:Math.max(1,o.combined.recordCount-o.combined.storedRecordCount,s.combined.recordCount-s.combined.storedRecordCount),hash:L(`comet.native.git-selection-overflow.v2
183
- ${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var yj=(1n<<256n)-1n;function Nj(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function dN(e){let t=V.resolve(e.paths.projectRoot),i=V.resolve(e.paths.nativeRoot),r=V.resolve(e.paths.runtimeDir),n=V.resolve(e.paths.configFile),a=V.join(t,".comet","current-change.json"),o=[],s=[],c=Buffer.alloc(32),l=0n,u=0,d=0,f=0,h=!1,v=!1,m=!1,p=()=>ei(e.execution)>=1?!0:(h=!0,m=!0,!1),b=E=>{let k=Buffer.from(`${E.type}\0${E.path}`,"utf8"),S=Ol("sha256").update("comet.native.physical-selection-record.v1\0").update(k).digest();for(let R=0;R<c.length;R+=1)c[R]^=S[R];if(l=l+BigInt(`0x${S.toString("hex")}`)&yj,d+=1,f+=k.byteLength,Buffer.byteLength(E.path,"utf8")>e.limits.maxPathBytes||f>e.limits.maxBytes){h=!0,m=!0;return}o.push(E)},g=async E=>{if(m||!p())return;let k;try{k=await ce.opendir(E)}catch(P){if(!p())return;if(!Pe(P)&&!Ee(P)||E===t&&Pe(P))throw P;v||=Ee(P),h||=Pe(P),m=!0;return}if(!p()){try{await k.close()}catch(P){if(P.code!=="ERR_DIR_CLOSED")throw P}return}let S=!1,R;try{for(;!m&&p();){let P;try{P=await k.read()}catch(te){if(!p())break;if(!Pe(te)&&!Ee(te)||E===t&&Pe(te))throw te;v||=Ee(te),h||=Pe(te),m=!0;break}if(!p()||P===null)break;if(u+=1,u>e.limits.maxNodes){h=!0,m=!0;break}let F=V.join(E,P.name),$=kj(t,F);if(F===n||F===a||ti(i,F)||ti(r,F)||e.denylist.some(te=>ti(te,F))||ci($)!==null)continue;if(!p())break;let Fe;try{Fe=await ce.lstat(F)}catch(te){if(!p())break;if(!Pe(te)&&!Ee(te))throw te;if(v=!0,b({path:$,type:"other"}),s.push({path:$,size:null,type:"file",reason:Pe(te)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.($),m||!p())break;continue}if(!p())break;let ue=Nj(Fe);if(ue==="directory"){if(Rj(e.policy,$))continue;if(!p())break;let te;try{te=await ce.realpath(F)}catch(ai){if(!p())break;if(!Pe(ai)&&!Ee(ai))throw ai;if(v=!0,b({path:$,type:ue}),s.push({path:$,size:null,type:"directory",reason:Pe(ai)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.($),m||!p())break;continue}if(!p())break;if(!O(e.physicalProjectRoot,te)||ti(e.physicalNativeRoot,te))continue;if(b({path:$,type:ue}),await e.hooks?.afterNode?.($),!p()||(await g(F),m))break;continue}if(b({path:$,type:ue}),await e.hooks?.afterNode?.($),!p()||m)break}}catch(P){S=!0,R=P}let N;try{await k.close()}catch(P){N=P}let w=p();if(S)throw R;if(w&&N!==void 0&&N.code!=="ERR_DIR_CLOSED")throw N};await g(t),p(),h?(o.length=0,d=0,f=0):(o.sort((E,k)=>E.path.localeCompare(k.path,"en")),s.sort((E,k)=>E.path.localeCompare(k.path,"en")));let y=h?L(`comet.native.physical-selection-incomplete.v1
182
+ `}function BI(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return _t.join(e.transactionsDir,t)}function $l(e,t){let i=BI(e,t);return{directory:i,journal:_t.join(i,"transaction.json"),events:_t.join(i,"events.jsonl"),staged:_t.join(i,"staged"),backups:_t.join(i,"backups")}}async function hi(e,t){let i=$l(e,t);return await Promise.all(Object.values(i).map(r=>T(e.runtimeDir,r))),i}function VI(e,t){if(t.length===0||_t.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Unsafe Native transaction ref: ${t}`);let i="runtime/",r=t==="runtime"||t.startsWith(i),n=r?e.runtimeDir:e.nativeRoot,a=t==="runtime"?"":r?t.slice(i.length):t,o=_t.resolve(n,...a.split(/[\\/]/u));if(!O(n,o))throw new Error(`Unsafe Native transaction ref: ${t}`);return o}async function br(e,t){let i=VI(e,t);return T(j(e,i),i)}async function dn(e){try{return await Wo.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function jh(e,t,i={}){let r=await hi(e,t);try{await Wo.lstat(r.events)}catch(n){if(n.code==="ENOENT")return{exists:!1,hash:null,size:0,events:[],canonicalSource:"",needsRepair:!1};throw n}try{let n=await re({root:e.runtimeDir,file:r.events,maxBytes:jI,label:`Native transaction event log ${t}`,hooks:i.hooks}),a;try{a=iN.decode(n.bytes)}catch(c){throw new Error(`Native transaction event log ${t} is not valid UTF-8`,{cause:c})}let o=FI(a),s=nN(o);return{exists:!0,hash:n.hash,size:n.size,events:o,canonicalSource:s,needsRepair:a!==s}}catch(n){throw n.code==="ENOENT"?new Error(`Native transaction event log ${t} changed while reading`,{cause:n}):n}}async function Xy(e,t,i){let r=await jh(e,t);if(r.exists!==i.exists||r.hash!==i.hash||r.size!==i.size)throw new Error(`Native transaction event log ${t} changed before append`)}async function Tt(e,t,i,r){let n=await hi(e,t),a=await jh(e,t),o=a.events.find(c=>c.type===i&&c.operationId===r);if(o)return a.needsRepair&&await he(n.events,a.canonicalSource,{containedRoot:e.runtimeDir,beforeCommit:()=>Xy(e,t,a)}),o;if(a.events.length>=Tl)throw new Error(`Native transaction event log ${t} exceeds ${Tl} events`);let s={sequence:a.events.length+1,timestamp:new Date().toISOString(),type:i,...r?{operationId:r}:{}};return rN(s,s.sequence),await Wo.mkdir(n.directory,{recursive:!0}),await he(n.events,nN([...a.events,s]),{containedRoot:e.runtimeDir,beforeCommit:()=>Xy(e,t,a)}),s}async function aN(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");t=Ih(t);let i=await hi(e,t.id);await Wo.mkdir(i.staged,{recursive:!0}),await Wo.mkdir(i.backups,{recursive:!0}),await ee(i.journal,t,{containedRoot:e.runtimeDir}),await Tt(e,t.id,"prepared")}async function yt(e,t,i={}){let r=await hi(e,t),n=await re({root:e.runtimeDir,file:r.journal,maxBytes:II,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(iN.decode(n.bytes)),o=Ih(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function kr(e,t,i={}){return(await jh(e,t,i)).events}async function Il(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let r=Ih({...t,status:i});return await ee((await hi(e,t.id)).journal,r,{containedRoot:e.runtimeDir}),r}async function _h(e,t,i){try{return await re({root:j(e,t),file:t,maxBytes:Th,label:i})}catch(r){if(r.code==="ENOENT")return null;throw r}}async function $h(e,t,i,r){let n=await _h(e,t,`${r} source`);if(!n)throw new Error(`${r} source does not exist`);let a=await _h(e,i,`${r} target`);await fi({root:j(e,i),directory:_t.dirname(i),label:`${r} target parent`}),await Nr({sourceRoot:j(e,t),source:t,targetRoot:j(e,i),target:i,maxBytes:Th,label:r,expectedHash:n.hash,expectedTargetHash:a?.hash??null,exclusive:a===null})}async function oN(e,t,i){let r=await _h(e,t,i);r&&await Al({root:j(e,t),file:t,maxBytes:Th,expectedHash:r.hash,expectedSize:r.size,label:i})}async function Qy(e,t){if(!t.backup)return;let i=await br(e,t.target),r=await br(e,t.backup);!await dn(i)||await dn(r)||await $h(e,i,r,`Legacy Native transaction backup ${t.id}`)}async function qI(e,t){let i=await br(e,t.target);if(t.type==="write"){if(!t.staged)throw new Error(`Write operation ${t.id} has no staged ref`);await Qy(e,t),await $h(e,await br(e,t.staged),i,`Legacy Native transaction write ${t.id}`);return}if(t.type==="remove"){await Qy(e,t),await oN(e,i,`Legacy Native transaction remove ${t.id}`);return}if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let r=await br(e,t.source),[n,a]=await Promise.all([dn(r),dn(i)]);if(!n&&a){await(await wt({root:j(e,i),directory:i,label:`Legacy Native transaction move target ${t.id}`,maxEntries:$I})).verify();return}if(a)throw new Error(`Move target already exists: ${t.target}`);if(!n)throw new Error(`Move source does not exist: ${t.source}`);await xh({root:j(e,r),source:r,target:i,label:`Legacy Native transaction move ${t.id}`})}async function sN(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let r=t.status==="prepared"?await Il(e,t,"applying"):t,n=await kr(e,t.id),a=new Set(n.filter(s=>s.type==="operation-completed").map(s=>s.operationId)),o=a.size;for(let s of r.operations)a.has(s.id)||(await Tt(e,r.id,"operation-started",s.id),await qI(e,s),await Tt(e,r.id,"operation-completed",s.id),o+=1,await i?.afterOperation?.(s,o));return r=await yt(e,r.id),r}async function WI(e,t){let i=await br(e,t.target),r=t.backup?await br(e,t.backup):null;if(t.type==="move"){if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let n=await br(e,t.source);if(await dn(i)){if(await dn(n))throw new Error(`Legacy Native rollback source already exists: ${t.source}`);await xh({root:j(e,i),source:i,target:n,label:`Legacy Native transaction rollback move ${t.id}`})}return}r&&await dn(r)?await $h(e,r,i,`Legacy Native transaction rollback restore ${t.id}`):await oN(e,i,`Legacy Native transaction rollback remove ${t.id}`)}async function Ol(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let i=await kr(e,t.id);if(i.some(a=>a.type==="archive-finalization-started"||a.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let r=await Il(e,t,"rolling-back");await Tt(e,r.id,"rollback-started");let n=new Set(i.filter(a=>a.type==="operation-started"||a.type==="operation-completed").map(a=>a.operationId));for(let a of[...r.operations].reverse())n.has(a.id)&&await WI(e,a);return await Tt(e,r.id,"rollback-completed"),r=await Il(e,r,"rolled-back"),r}async function sa(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");return await Tt(e,t.id,i),i==="commit"?Il(e,t,"committed"):t}async function GI(e,t,i){let r;try{r=await zI.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await yt(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of r)if(un(n.name))try{let a=await qo(e,n.name);if(!a||i?.kind===a.kind&&i.change===a.change)continue;if(Jy(a))return!0}catch{return!0}return!1}async function UI(e,t){let i=Date.now()+5e3,r=JI.join(e.locksDir,"root-move.lock");for(;;)try{return await pr(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await Lo(r);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=i)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function se(e,t,i,r){let n=await UI(e,t);try{if(await Yn(e.projectRoot),await GI(e,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await mr(n)}}function cN(e){return Number.isSafeInteger(e)&&e>=1}async function lN(e){if(!cN(e.expectedRevision))throw new Error("Native expected revision must be a positive integer");if(e.next.revision!==e.expectedRevision+1)throw new Error("Native CAS next revision must increment the expected revision exactly once");let t=await e.read();if(!cN(t.revision))throw new Error("Native current revision must be a positive integer");let i=e.equals??((r,n)=>JSON.stringify(r)===JSON.stringify(n));if(t.revision===e.next.revision&&i(t,e.next))return t;if(t.revision!==e.expectedRevision)throw e.conflict(t.revision);return await e.write(e.next),e.next}import{createHash as Fl}from"crypto";import{spawn as yN}from"node:child_process";import{promises as ce}from"fs";import V from"path";import{createHash as uN}from"crypto";import{createReadStream as KI}from"fs";async function ei(e){let t=uN("sha256");for await(let i of KI(e))t.update(i);return t.digest("hex")}function L(e){return uN("sha256").update(e).digest("hex")}var Hl={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},Fh=1e3,YI=8*1024*1024,XI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,QI=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),ZI=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),ej=new Set(["schema","include","exclude","hash"]),tj=new Set(["provider","gitSelection","physicalSelection","projection"]),ij=new Set(["provider","selection"]),rj=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),nj=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),aj=new Set(["schema","status","before","after"]),oj=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),sj=new Set(["path","hash","size","type","gitObjectId"]),cj=new Set(["path","size","type","reason"]),lj=new Set(["ref","hash","count"]),uj=new Set(["change-created","legacy-migration","explicit"]),dj=new Set(["file","directory","other"]),fj=new Set(["file-size","file-count","total-size","manifest-size","changed-during-read","unreadable","gitlink-unavailable","gitlink-dirty","gitlink-changed","legacy-gitlink-boundary","git-enumeration-limit","git-selection-changed","physical-enumeration-limit","physical-selection-changed"]),Bl=/^[a-f0-9]{64}$/u,NN=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,hj=new Set(["EACCES","EPERM"]),fa=64*1024,Lh=64*1024,pj=6e4,mj=1e3,vj=2,Bh={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},gj={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function bN(e){let t=e.deadlineMs??pj;if(!Number.isSafeInteger(t)||t<1)throw new Error("Native snapshot execution budget must be a positive integer");return{deadlineAt:Date.now()+t,gitProcess:e.gitProcess??{command:"git"}}}function ti(e){return Math.max(0,e.deadlineAt-Date.now())}function M(e){return ti(e)>=1}function Oh(e){let t=e===void 0?new Error("Native snapshot deadline exceeded while waiting for Git"):new Error("Native snapshot deadline exceeded while waiting for Git",{cause:e});return Object.assign(t,{code:"GIT_SNAPSHOT_TIMEOUT"})}function ua(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function wj(e){let t={...gj,...e};if(!Number.isSafeInteger(t.maxNodes)||t.maxNodes<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxPathBytes)||t.maxPathBytes<1||t.maxPathBytes>t.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return t}async function yj(e,t){if(t.terminateTree){await t.terminateTree(e);return}let i=e.pid;if(i===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let r=process.env.SystemRoot??process.env.WINDIR,n=r&&V.win32.isAbsolute(r)?V.win32.resolve(r):"C:\\Windows",a=V.win32.join(n,"System32","taskkill.exe");if(!V.win32.isAbsolute(a))throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git taskkill path is not trusted"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"});let o=()=>new Promise(s=>{let c=!1,l=null,u=null,d=(f,h=!1)=>{c||(c=!0,u&&clearTimeout(u),h&&l?.kill("SIGKILL"),s(f))};try{l=yN(a,["/pid",String(i),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>d(!1)),l.once("close",f=>d(f===0)),u=setTimeout(()=>d(!1,!0),mj),u.unref()}catch{d(!1)}});for(let s=0;s<vj;s+=1)if(await o()){e.kill("SIGKILL");return}throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git process-tree termination could not be confirmed on Windows"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"})}try{process.kill(-i,"SIGKILL")}catch(r){if(r.code!=="ESRCH")throw r}e.kill("SIGKILL")}function Vh(e,t,i,r){let n=ti(e);if(n<1)throw Oh();let a=e.gitProcess,o=yN(a.command,[...a.argsPrefix??[],"-C",t,...i],{cwd:t,stdio:[r?"pipe":"ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"}),s=null,c=!1,l=null;o.once("error",h=>{s=h});let u=new Promise(h=>{o.once("close",h)}),d=setTimeout(()=>{c=!0,l=yj(o,a).then(()=>({error:null}),h=>({error:h}))},n);d.unref();let f=u.then(async h=>{if(clearTimeout(d),c){let v=await l;throw v?.error?Oh(v.error):Oh()}return{code:h,spawnError:s}});return{child:o,completion:f}}function kN(e){let t={...Bh,...e};if(!Number.isSafeInteger(t.maxRecords)||t.maxRecords<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxRecordBytes)||t.maxRecordBytes<1||t.maxRecordBytes>t.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return t}async function Dl(e,t,i,r=Lh){let{child:n,completion:a}=Vh(e,t,i,!1),o=[],s=[],c=0,l=0,u=!1;n.stdout.on("data",h=>{let v=Math.max(0,r-l);v>0&&o.push(Buffer.from(h).subarray(0,v)),l+=h.byteLength,l>r&&(u=!0)}),n.stderr.on("data",h=>{if(c>=fa)return;let v=fa-c,m=Buffer.from(h).subarray(0,v);s.push(m),c+=m.byteLength});let{code:d,spawnError:f}=await a;if(d===0&&f===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${i.join(" ")} failed${f?`: ${f.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function Hh(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function Uo(e,t,i,r){if(r.outputChunkBytes!==void 0&&(!Number.isSafeInteger(r.outputChunkBytes)||r.outputChunkBytes<1))throw new Error("Native Git output chunk size must be a positive integer");return new Promise((n,a)=>{let{child:o,completion:s}=Vh(e,t,i,r.stdin!==void 0),c=[],l=Fl("sha256"),u=[],d=0,f=0,h=0,v=0,m=Buffer.alloc(0),p=!1,b=!1,g=!1,y=E=>{let k=0;for(;k<E.byteLength;){let S=E.indexOf(0,k),R=S<0?E.byteLength:S,N=E.subarray(k,R);if(!p&&N.byteLength>0&&(m.byteLength+N.byteLength>r.maxRecordBytes?(m=Buffer.alloc(0),p=!0,b=!0):m=Buffer.concat([m,N])),S<0)break;v+=1,m.byteLength===0&&!p&&(g=!0);let w=m.byteLength+1;!p&&v<=r.maxRecords&&h+w<=r.maxBytes?(c.push(m),h+=w):b=!0,m=Buffer.alloc(0),p=!1,k=S+1}};o.stdout.on("data",E=>{l.update(E),f+=E.byteLength,f>r.maxBytes&&(b=!0);let k=r.outputChunkBytes;if(k===void 0){y(E);return}for(let S=0;S<E.byteLength;S+=k)y(E.subarray(S,Math.min(E.byteLength,S+k)))}),o.stderr.on("data",E=>{if(d>=fa)return;let k=fa-d,S=Buffer.from(E).subarray(0,k);u.push(S),d+=S.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:E,spawnError:k})=>{let S=r.acceptedExitCodes??[0];if(E!==null&&S.includes(E)&&k===null&&!g&&m.byteLength===0&&!p){n({records:c,digest:l.digest("hex"),overflow:b,recordCount:v,stdoutBytes:f});return}a(new Error(`git ${i.join(" ")} failed${k?`: ${k.message}`:g||m.byteLength>0||p?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),r.stdin&&o.stdin?.end(r.stdin)})}function Ll(e){let t=e.toString("utf8");if(!Buffer.from(t,"utf8").equals(e))throw new Error("Native Git snapshot provider returned non-UTF-8 path data");return t}async function Nj(e,t,i){if(i.length===0)return new Set;let r=await Uo(e,t,["check-ignore","--no-index","-z","--stdin"],{...Bh,maxRecords:Math.max(1,i.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${i.join("\0")}\0`,"utf8")});if(r.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(r.records.map(n=>{let a=Ll(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function bj(e,t,i){let{child:r,completion:n}=Vh(e,t,i,!1),a=[],o=0,s=!1;r.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),r.stderr.on("data",u=>{if(o>=fa)return;let d=fa-o,f=Buffer.from(u).subarray(0,d);a.push(f),o+=f.byteLength});let{code:c,spawnError:l}=await n;if(c===0&&l===null)return s;throw new Error(`git ${i.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function da(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||V.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||V.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function kj(e,t){return e.map(i=>{let r=da(i);if(r===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return r})}async function Sj(e){let t=V.resolve(e);for(;;){try{return await ce.lstat(V.join(t,".git")),!0}catch(r){if(r.code!=="ENOENT")throw r}let i=V.dirname(t);if(i===t)return!1;t=i}}async function SN(e,t,i,r={}){let n=V.resolve(t.projectRoot),a=V.join(n,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,a].map(f=>{let h=V.relative(n,V.resolve(f)).replaceAll("\\","/"),v=da(h);if(v===null)throw new Error("Native Git snapshot exclusion escaped the project root");return v}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`])],c={...i,...r.outputChunkBytes===void 0?{}:{outputChunkBytes:r.outputChunkBytes}},l=await Uo(e,n,["ls-files","--stage","-z",...s],c);await r.afterStageBefore?.();let u=await Uo(e,n,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await r.afterCombined?.();let d=await Uo(e,n,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function EN(e){return{stageBefore:Hh(e.stagedBefore),combined:Hh(e.combined),stageAfter:Hh(e.stagedAfter)}}async function PN(e,t,i=Bh,r={}){let n=V.resolve(t.projectRoot);if(!await Sj(n))return null;let a;try{a=await Dl(e,n,["rev-parse","--is-inside-work-tree"])}catch(g){throw ua(g)?g:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:g})}if(a.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let o;try{o=await SN(e,t,i,r)}catch(g){throw ua(g)?g:new Error("Native Git snapshot provider failed after repository detection",{cause:g})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,u=new Set,d=new Map,f=new Set,h=g=>{for(let y of g){let E=Ll(y),k=E.indexOf(" ");if(k<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let S=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(E.slice(0,k))?.groups;if(!S)throw new Error("Native Git snapshot provider returned a malformed staged header");let R=da(E.slice(k+1));if(R===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(R),S.stage==="0"&&d.set(R,S.objectId),S.mode==="160000"&&S.stage==="0"&&f.add(R)}};h(s.records),h(l.records);let v=c.records.map(Ll),m=kj(v,"combined"),p=new Set(m.filter(g=>!u.has(g))),b=new Set(m.filter((g,y)=>!u.has(g)&&v[y].endsWith("/")));for(let g of f)b.delete(g);return{tracked:u,trackedObjectIds:d,untracked:p,gitlinks:f,nestedRepositories:b,omissions:[],overflow:null,evidence:null,initialFence:EN(o)}}function Er(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function dN(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function Ej(e,t){return!Er(e.stageBefore,e.stageAfter)||!Er(e.stageAfter,t.stageBefore)||!Er(e.combined,t.combined)||!Er(t.stageBefore,t.stageAfter)}async function RN(e,t,i,r,n){let a;try{a=await SN(e,t,i,{...n===void 0?{}:{outputChunkBytes:n}})}catch(u){throw ua(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=r.initialFence,s=EN(a),c=dN(o)||dN(s),l=Ej(o,s);c&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),l&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),r.evidence=c||l?{schema:"comet.native.git-selection.v1",status:c&&l?"overflow-and-changed":c?"overflow":"changed",...o,finalStageBefore:s.stageBefore,finalCombined:s.combined,finalStageAfter:s.stageAfter}:null,(o.combined.overflow||s.combined.overflow)&&(r.overflow={count:Math.max(1,o.combined.recordCount-o.combined.storedRecordCount,s.combined.recordCount-s.combined.storedRecordCount),hash:L(`comet.native.git-selection-overflow.v2
183
+ ${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var Pj=(1n<<256n)-1n;function Rj(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function fN(e){let t=V.resolve(e.paths.projectRoot),i=V.resolve(e.paths.nativeRoot),r=V.resolve(e.paths.runtimeDir),n=V.resolve(e.paths.configFile),a=V.join(t,".comet","current-change.json"),o=[],s=[],c=Buffer.alloc(32),l=0n,u=0,d=0,f=0,h=!1,v=!1,m=!1,p=()=>ti(e.execution)>=1?!0:(h=!0,m=!0,!1),b=E=>{let k=Buffer.from(`${E.type}\0${E.path}`,"utf8"),S=Fl("sha256").update("comet.native.physical-selection-record.v1\0").update(k).digest();for(let R=0;R<c.length;R+=1)c[R]^=S[R];if(l=l+BigInt(`0x${S.toString("hex")}`)&Pj,d+=1,f+=k.byteLength,Buffer.byteLength(E.path,"utf8")>e.limits.maxPathBytes||f>e.limits.maxBytes){h=!0,m=!0;return}o.push(E)},g=async E=>{if(m||!p())return;let k;try{k=await ce.opendir(E)}catch(P){if(!p())return;if(!Pe(P)&&!Ee(P)||E===t&&Pe(P))throw P;v||=Ee(P),h||=Pe(P),m=!0;return}if(!p()){try{await k.close()}catch(P){if(P.code!=="ERR_DIR_CLOSED")throw P}return}let S=!1,R;try{for(;!m&&p();){let P;try{P=await k.read()}catch(te){if(!p())break;if(!Pe(te)&&!Ee(te)||E===t&&Pe(te))throw te;v||=Ee(te),h||=Pe(te),m=!0;break}if(!p()||P===null)break;if(u+=1,u>e.limits.maxNodes){h=!0,m=!0;break}let F=V.join(E,P.name),$=xj(t,F);if(F===n||F===a||ii(i,F)||ii(r,F)||e.denylist.some(te=>ii(te,F))||li($)!==null)continue;if(!p())break;let Be;try{Be=await ce.lstat(F)}catch(te){if(!p())break;if(!Pe(te)&&!Ee(te))throw te;if(v=!0,b({path:$,type:"other"}),s.push({path:$,size:null,type:"file",reason:Pe(te)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.($),m||!p())break;continue}if(!p())break;let ue=Rj(Be);if(ue==="directory"){if(Ij(e.policy,$))continue;if(!p())break;let te;try{te=await ce.realpath(F)}catch(oi){if(!p())break;if(!Pe(oi)&&!Ee(oi))throw oi;if(v=!0,b({path:$,type:ue}),s.push({path:$,size:null,type:"directory",reason:Pe(oi)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.($),m||!p())break;continue}if(!p())break;if(!O(e.physicalProjectRoot,te)||ii(e.physicalNativeRoot,te))continue;if(b({path:$,type:ue}),await e.hooks?.afterNode?.($),!p()||(await g(F),m))break;continue}if(b({path:$,type:ue}),await e.hooks?.afterNode?.($),!p()||m)break}}catch(P){S=!0,R=P}let N;try{await k.close()}catch(P){N=P}let w=p();if(S)throw R;if(w&&N!==void 0&&N.code!=="ERR_DIR_CLOSED")throw N};await g(t),p(),h?(o.length=0,d=0,f=0):(o.sort((E,k)=>E.path.localeCompare(k.path,"en")),s.sort((E,k)=>E.path.localeCompare(k.path,"en")));let y=h?L(`comet.native.physical-selection-incomplete.v1
184
184
  ${JSON.stringify({maxNodes:e.limits.maxNodes,maxBytes:e.limits.maxBytes,maxPathBytes:e.limits.maxPathBytes})}`):L(`comet.native.physical-selection.v1
185
- ${JSON.stringify({visitedNodeCount:u,recordCount:d,encodedBytes:f,xor:c.toString("hex"),sum:l.toString(16).padStart(64,"0")})}`);return{records:o,omissions:s,evidence:{hash:y,visitedNodeCount:u,recordCount:d,storedRecordCount:o.length,encodedBytes:f,overflow:h,unstable:v}}}function RN(e,t){return e.hash===t.hash&&e.visitedNodeCount===t.visitedNodeCount&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.encodedBytes===t.encodedBytes&&e.overflow===t.overflow&&e.unstable===t.unstable}function bj(e,t){let i=e.overflow||t.overflow,r=e.unstable||t.unstable||!RN(e,t),n=[];return i&&n.push({path:".",size:null,type:"directory",reason:"physical-enumeration-limit"}),r&&n.push({path:".",size:null,type:"directory",reason:"physical-selection-changed"}),{omissions:n,evidence:i||r?{schema:"comet.native.physical-selection.v1",status:i&&r?"overflow-and-changed":i?"overflow":"changed",before:e,after:t}:null}}function CN(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,i)=>t.localeCompare(i,"en"))}async function fN(e,t){let r=(await Il(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!yN.test(r))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return L(`gitlink:${r}`)}async function hN(e,t){let i=await fN(e,t),r=await mj(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),n=await fN(e,t);if(n!==i)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:n,dirty:r}}function qo(e,t){if(ci(t)!==null)return!1;let i=V.resolve(e.projectRoot,...t.split("/"));return!ti(V.resolve(e.nativeRoot),i)&&!ti(V.resolve(e.runtimeDir),i)}function Bh(e,t={}){let i=Ii(e),r=t.maxRecordedPaths??20;if(!Number.isSafeInteger(r)||r<0)throw new Error("Native snapshot health maxRecordedPaths must be a non-negative integer");let n=i.omitted.slice(0,r).map(a=>a.path);return{complete:i.complete,omittedCount:i.omittedCount,recordedOmissionCount:i.omitted.length,overflowCount:i.omissionOverflow?.count??0,samplePaths:n,sampleTruncated:n.length<i.omittedCount}}function kj(e,t){return V.relative(e,t).split(V.sep).join("/")}function Sj(e,t){return t.map(i=>V.resolve(e,...i.split(/[\\/]/u)))}function ti(e,t){let i=V.resolve(e),r=V.resolve(t);return r===i||O(i,r)}function Pe(e){return sj.has(e.code??"")}function Ee(e){return e.code==="ENOENT"}function Vh(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
186
- `)}function Ej(e,t){return L(`comet.native.snapshot-policy.v1
187
- ${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function Oh(e,t,i){let r=new Set(t),n=[...t];for(;n.length>0;){if(i&&!i())return null;let a=n.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!r.has(a+1)&&(r.add(a+1),n.push(a+1))}return r}function Pj(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function pN(e){let t=ol(e,"Native snapshot pattern"),i=[];for(let r=0;r<t.length;r+=1){let n=t[r];n==="*"&&t[r+1]==="*"?(r+=1,t[r+1]==="/"?(r+=1,i.push({kind:"globstar-slash"})):i.push({kind:"globstar"})):n==="*"?i.push({kind:"star"}):n==="?"?i.push({kind:"question"}):i.push({kind:"literal",value:n})}return(r,n)=>{let a=n?Pj(n):void 0;if(a&&!a())return!1;let o=Oh(i,new Set([0]),a);if(o===null)return!1;for(let s of r){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let u=i[l];u&&(u.kind==="literal"&&u.value===s||u.kind==="question"&&s!=="/"?c.add(l+1):u.kind==="star"&&s!=="/"||u.kind==="globstar"?c.add(l):u.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=Oh(i,c,a),o===null||o.size===0)return!1}return Oh(i,o,a)?.has(i.length)??!1}}function xN(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>ol(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),i=[...new Set(e.exclude.map(n=>ol(n,"exclude")))].sort((n,a)=>n.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let r=Ej(t,i);if("hash"in e&&e.hash!==r)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:i,hash:r},includeMatchers:t.map(pN),excludeMatchers:i.map(pN),excludedDirectoryPrefixes:i.flatMap(n=>{if(!n.endsWith("/**"))return[];let a=n.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((n,a)=>n.localeCompare(a,"en"))}}function Rj(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function mN(e,t,i){if(!e)return!0;let r=()=>M(i),n=!1;for(let a of e.includeMatchers){if(!r())return!1;if(a(t,r)){n=!0;break}}if(!n)return!1;for(let a of e.excludeMatchers)if(!r()||a(t,r))return!1;return!0}function zo(e,t,i){let r=JSON.stringify(i);return L(`${e}
185
+ ${JSON.stringify({visitedNodeCount:u,recordCount:d,encodedBytes:f,xor:c.toString("hex"),sum:l.toString(16).padStart(64,"0")})}`);return{records:o,omissions:s,evidence:{hash:y,visitedNodeCount:u,recordCount:d,storedRecordCount:o.length,encodedBytes:f,overflow:h,unstable:v}}}function CN(e,t){return e.hash===t.hash&&e.visitedNodeCount===t.visitedNodeCount&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.encodedBytes===t.encodedBytes&&e.overflow===t.overflow&&e.unstable===t.unstable}function Cj(e,t){let i=e.overflow||t.overflow,r=e.unstable||t.unstable||!CN(e,t),n=[];return i&&n.push({path:".",size:null,type:"directory",reason:"physical-enumeration-limit"}),r&&n.push({path:".",size:null,type:"directory",reason:"physical-selection-changed"}),{omissions:n,evidence:i||r?{schema:"comet.native.physical-selection.v1",status:i&&r?"overflow-and-changed":i?"overflow":"changed",before:e,after:t}:null}}function xN(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,i)=>t.localeCompare(i,"en"))}async function hN(e,t){let r=(await Dl(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!NN.test(r))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return L(`gitlink:${r}`)}async function pN(e,t){let i=await hN(e,t),r=await bj(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),n=await hN(e,t);if(n!==i)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:n,dirty:r}}function Go(e,t){if(li(t)!==null)return!1;let i=V.resolve(e.projectRoot,...t.split("/"));return!ii(V.resolve(e.nativeRoot),i)&&!ii(V.resolve(e.runtimeDir),i)}function qh(e,t={}){let i=$i(e),r=t.maxRecordedPaths??20;if(!Number.isSafeInteger(r)||r<0)throw new Error("Native snapshot health maxRecordedPaths must be a non-negative integer");let n=i.omitted.slice(0,r).map(a=>a.path);return{complete:i.complete,omittedCount:i.omittedCount,recordedOmissionCount:i.omitted.length,overflowCount:i.omissionOverflow?.count??0,samplePaths:n,sampleTruncated:n.length<i.omittedCount}}function xj(e,t){return V.relative(e,t).split(V.sep).join("/")}function Aj(e,t){return t.map(i=>V.resolve(e,...i.split(/[\\/]/u)))}function ii(e,t){let i=V.resolve(e),r=V.resolve(t);return r===i||O(i,r)}function Pe(e){return hj.has(e.code??"")}function Ee(e){return e.code==="ENOENT"}function Wh(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
186
+ `)}function _j(e,t){return L(`comet.native.snapshot-policy.v1
187
+ ${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function Dh(e,t,i){let r=new Set(t),n=[...t];for(;n.length>0;){if(i&&!i())return null;let a=n.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!r.has(a+1)&&(r.add(a+1),n.push(a+1))}return r}function Tj(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function mN(e){let t=dl(e,"Native snapshot pattern"),i=[];for(let r=0;r<t.length;r+=1){let n=t[r];n==="*"&&t[r+1]==="*"?(r+=1,t[r+1]==="/"?(r+=1,i.push({kind:"globstar-slash"})):i.push({kind:"globstar"})):n==="*"?i.push({kind:"star"}):n==="?"?i.push({kind:"question"}):i.push({kind:"literal",value:n})}return(r,n)=>{let a=n?Tj(n):void 0;if(a&&!a())return!1;let o=Dh(i,new Set([0]),a);if(o===null)return!1;for(let s of r){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let u=i[l];u&&(u.kind==="literal"&&u.value===s||u.kind==="question"&&s!=="/"?c.add(l+1):u.kind==="star"&&s!=="/"||u.kind==="globstar"?c.add(l):u.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=Dh(i,c,a),o===null||o.size===0)return!1}return Dh(i,o,a)?.has(i.length)??!1}}function AN(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>dl(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),i=[...new Set(e.exclude.map(n=>dl(n,"exclude")))].sort((n,a)=>n.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let r=_j(t,i);if("hash"in e&&e.hash!==r)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:i,hash:r},includeMatchers:t.map(mN),excludeMatchers:i.map(mN),excludedDirectoryPrefixes:i.flatMap(n=>{if(!n.endsWith("/**"))return[];let a=n.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((n,a)=>n.localeCompare(a,"en"))}}function Ij(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function vN(e,t,i){if(!e)return!0;let r=()=>M(i),n=!1;for(let a of e.includeMatchers){if(!r())return!1;if(a(t,r)){n=!0;break}}if(!n)return!1;for(let a of e.excludeMatchers)if(!r()||a(t,r))return!1;return!0}function Ko(e,t,i){let r=JSON.stringify(i);return L(`${e}
188
188
  ${Buffer.byteLength(t)}:${t}
189
- ${Buffer.byteLength(r)}:${r}`)}function Dh(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function $l(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!Dh(i))return e.splice(t,1),i}return null}function br(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return vt(i,r)?z(i,r):z(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Cj(e,t,i,r){if(!M(r))return{status:"budget-exhausted"};let n;try{n=await ce.open(e,"r")}catch(c){if(!M(r))return{status:"budget-exhausted"};throw c}if(!M(r))return await n.close(),{status:"budget-exhausted"};let a=Ol("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!M(r))return{status:"budget-exhausted"};let c=await n.stat();if(!M(r))return{status:"budget-exhausted"};if(!c.isFile()||!br(i,c))return{status:"changed"};for(;;){if(!M(r))return{status:"budget-exhausted"};let l=t+1-s;if(l<1)return{status:"changed"};let u=await n.read(o,0,Math.min(o.length,l),null);if(!M(r))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!M(r))return{status:"budget-exhausted"};let d=await n.stat();return M(r)?!d.isFile()||!br(c,d)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:d}:{status:"budget-exhausted"}}if(s+u.bytesRead>t)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await n.close()}}function It(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function jt(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function ra(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function pi(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function AN(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let i=V.posix.normalize(e);if(i!==e||V.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function xj(e,t){let i=It(e,`Native snapshot entry ${t}`);jt(i,tj,`Native snapshot entry ${t}`);let r=AN(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!Hl.test(i.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(i.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:r,hash:i.hash,size:pi(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!yN.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=i.gitObjectId}return n}function Aj(e,t){let i=It(e,`Native snapshot omission ${t}`);if(jt(i,ij,`Native snapshot omission ${t}`),!aj.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!oj.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:AN(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:pi(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function _j(e){let t=It(e,"Native snapshot omission overflow");if(jt(t,rj,"Native snapshot omission overflow"),typeof t.hash!="string"||!Hl.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let i=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==i)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:i,hash:t.hash,count:ra(t.count,"Native snapshot omission overflow count")}}function ia(e,t){let i=It(e,t);if(jt(i,QI,t),typeof i.hash!="string"||!Hl.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let r=pi(i.recordCount,`${t} recordCount`),n=pi(i.storedRecordCount,`${t} storedRecordCount`),a=pi(i.stdoutBytes,`${t} stdoutBytes`);if(n>r||!i.overflow&&n!==r)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,recordCount:r,storedRecordCount:n,stdoutBytes:a,overflow:i.overflow}}function vN(e){let t=It(e,"Native Git selection evidence");if(jt(t,XI,"Native Git selection evidence"),t.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let i=ia(t.stageBefore,"Native Git selection stageBefore"),r=ia(t.combined,"Native Git selection combined"),n=ia(t.stageAfter,"Native Git selection stageAfter"),a=ia(t.finalStageBefore,"Native Git selection finalStageBefore"),o=ia(t.finalCombined,"Native Git selection finalCombined"),s=ia(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,r,n,a,o,s].some(d=>d.overflow),l=!kr(i,n)||!kr(n,a)||!kr(r,o)||!kr(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(t.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:i,combined:r,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function gN(e,t){let i=It(e,t);if(jt(i,ej,t),typeof i.hash!="string"||!Hl.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean"||typeof i.unstable!="boolean")throw new Error(`${t} flags are invalid`);let r=pi(i.visitedNodeCount,`${t} visitedNodeCount`),n=pi(i.recordCount,`${t} recordCount`),a=pi(i.storedRecordCount,`${t} storedRecordCount`),o=pi(i.encodedBytes,`${t} encodedBytes`);if(a>n||!i.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,visitedNodeCount:r,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:i.overflow,unstable:i.unstable}}function Tj(e){let t=It(e,"Native physical selection evidence");if(jt(t,ZI,"Native physical selection evidence"),t.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let i=gN(t.before,"Native physical selection before"),r=gN(t.after,"Native physical selection after"),n=i.overflow||r.overflow,a=i.unstable||r.unstable||!RN(i,r);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:i,after:r}}function Ii(e){let t=It(e,"Native content snapshot manifest");if(jt(t,JI,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!nj.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let S=It(t.capture,"Native content snapshot capture");if(jt(S,KI,"Native content snapshot capture"),S.provider!=="git"&&S.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let R=S.gitSelection===void 0?void 0:vN(S.gitSelection),N=S.physicalSelection===void 0?void 0:Tj(S.physicalSelection),w=null;if(S.projection!==void 0){let P=It(S.projection,"Native content snapshot projection");if(jt(P,YI,"Native content snapshot projection"),P.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");w={provider:"git",...P.selection===void 0?{}:{selection:vN(P.selection)}}}if(S.provider==="git"){if(N||w)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...R?{gitSelection:R}:{}}}else{if(R)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(N&&w)throw new Error("Native physical-tree capture cannot combine selection and projection");i=w?{provider:"physical-tree",projection:w}:{provider:"physical-tree",...N?{physicalSelection:N}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let r=It(t.limits,"Native content snapshot limits");jt(r,GI,"Native content snapshot limits");let n={maxFiles:ra(r.maxFiles,"Native snapshot maxFiles"),maxFileBytes:ra(r.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:ra(r.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:ra(r.maxManifestBytes,"Native snapshot maxManifestBytes"),...r.maxDurationMs===void 0?{}:{maxDurationMs:ra(r.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let S=It(t.policy,"Native snapshot policy");if(jt(S,UI,"Native snapshot policy"),S.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(S.include)||!Array.isArray(S.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=xN({include:S.include,exclude:S.exclude,hash:S.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(xj),s=t.omitted.map(Aj),c=pi(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:_j(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(S=>S.size>n.maxFileBytes)||o.reduce((S,R)=>S+R.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(S=>S.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>Lh||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(S=>S.reason==="git-enumeration-limit"),f=s.filter(S=>S.reason==="git-selection-changed");for(let S of[...d,...f])if(S.path!=="."||S.size!==null||S.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let h=i?.provider==="git"?i.gitSelection:i?.projection?.selection,v=h?.status==="overflow"||h?.status==="overflow-and-changed",m=h?.status==="changed"||h?.status==="overflow-and-changed";if(v!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(m!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let p=s.filter(S=>S.reason==="physical-enumeration-limit"),b=s.filter(S=>S.reason==="physical-selection-changed");for(let S of[...p,...b])if(S.path!=="."||S.size!==null||S.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(p.length>1||b.length>1)throw new Error("Native physical selection omissions must not be duplicated");let g=i?.physicalSelection,y=g?.status==="overflow"||g?.status==="overflow-and-changed",E=g?.status==="changed"||g?.status==="overflow-and-changed";if(y!==(p.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(E!==(b.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let k={schema:"comet.native.content-snapshot.v1",origin:t.origin,...i?{capture:i}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(Vh(k)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return k}async function Dl(e,t,i={}){let r=Ii(t);if(r.capture?.provider==="git"||r.capture?.projection||r.capture?.physicalSelection)return r;let n=V.resolve(e.projectRoot),a=NN(i),o=bN(i.gitSelectionLimits),s=await EN(a,e,o,i.gitSelectionHooks);if(s===null)return r;let c=new Set(CN(s).filter(N=>qo(e,N))),l=[...s.gitlinks].filter(N=>c.has(N)),u=[...s.nestedRepositories].filter(N=>qo(e,N)),d=(N,w)=>w.some(P=>N===P||N.startsWith(`${P}/`)),f=N=>d(N,l),h=N=>d(N,u),v=[...r.entries.map(N=>N.path),...r.omitted.flatMap(N=>N.type==="directory"?[N.path,`${N.path}/`]:[N.path])].filter(N=>!c.has(N)&&!f(N)&&!h(N)),m=await pj(a,n,v),p=r.entries.filter(N=>!f(N.path)&&!h(N.path)&&qo(e,N.path)&&(c.has(N.path)||!m.has(N.path)));await PN(a,e,o,s,i.gitSelectionHooks?.outputChunkBytes);let b=[...s.omissions];for(let N of l)b.push({path:N,size:null,type:"directory",reason:"legacy-gitlink-boundary"});p.sort((N,w)=>N.path.localeCompare(w.path,"en"));let g=r.omitted.filter(N=>f(N.path)||h(N.path)||!qo(e,N.path)?!1:m.has(N.path)?c.has(N.path)||[...c].some(w=>w.startsWith(`${N.path}/`)):!0);for(let N of b)g.some(w=>w.path===N.path&&w.reason===N.reason)||g.push(N);g.sort((N,w)=>N.path.localeCompare(w.path,"en"));let y=r.omissionOverflow?.count??0,E=r.omissionOverflow?.hash??L("comet.native.snapshot-omission-overflow.v1");s.overflow&&(y+=s.overflow.count,E=zo(E,"git-selection",{source:"git-selection",...s.overflow}));let k=N=>{y+=1,E=zo(E,"omission",N)};for(;g.length>Lh;){let N=$l(g);if(N===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");k(N)}let S=()=>({...r,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:g.length+y===0,entries:p,omitted:g,omittedCount:g.length+y,...y>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${E}`,hash:E,count:y}}:{}}),R=S();for(;Vh(R)>r.limits.maxManifestBytes;){let N=$l(g);if(N===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");k(N),R=S()}return Ii(R)}function _N(e,t){if(!zI.test(t))throw new Error(`Invalid Native change name: ${t}`);return V.join(H(e,t),"baseline-manifest.json")}async function Ll(e,t={}){let i={maxFiles:t.limits?.maxFiles??Tl.maxFiles,maxFileBytes:t.limits?.maxFileBytes??Tl.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??Tl.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??Tl.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},r=xN(t.policy),n=NN({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=bN(t.gitSelectionLimits),o=fj(t.physicalSelectionLimits);if(i.maxFiles<1||i.maxFileBytes<1||i.maxTotalBytes<1||i.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=V.resolve(e.projectRoot),c=await ce.realpath(s),l=V.resolve(e.nativeRoot),u=await ce.realpath(l),d=V.resolve(e.runtimeDir),f=V.resolve(e.configFile),h=V.join(s,".comet","current-change.json"),v=Sj(s,t.denylist??[]),m=[],p=[],b=new Map,g=new Map,y=0,E=0,k=L("comet.native.snapshot-omission-overflow.v1"),S=0,R=!1,N=null,w=_=>{E+=1,k=zo(k,"omission",_)},P=_=>{if(y+=1,p.length<Lh){p.push(_);return}if(Dh(_)){let A=$l(p);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");w(A),p.push(_);return}w(_)},F=_=>{y+=_.count,E+=_.count,k=zo(k,"git-selection",{source:"git-selection",..._})},$=_=>{E+=1,k=zo(k,"manifest-entry",{reason:"manifest-size",entry:_})},Fe=async(_,A)=>{m.push(_),S+=_.size,b.set(_.path,A),R||(R=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(_.path))},ue=(_,A)=>{let I=m.findIndex(oe=>oe.path===_);if(I<0)return;let[q]=m.splice(I,1);S-=q.size,b.delete(_),P(A)},te=async(_,A,I,q)=>{if(!I.isFile()||I.isSymbolicLink()||!M(n))return;let oe;try{oe=await ce.realpath(_)}catch(x){if(!M(n))return;if(!Pe(x)&&!Ee(x))throw x;P({path:A,size:I.size,type:"file",reason:Ee(x)?"changed-during-read":"unreadable"});return}if(!M(n)||!O(c,oe)||ti(u,oe))return;if(m.length>=i.maxFiles){P({path:A,size:I.size,type:"file",reason:"file-count"});return}if(I.size>i.maxFileBytes){P({path:A,size:I.size,type:"file",reason:"file-size"});return}if(S+I.size>i.maxTotalBytes){P({path:A,size:I.size,type:"file",reason:"total-size"});return}let U,B,ve;try{if(U=await Cj(oe,I.size,I,n),U.status==="budget-exhausted"||!M(n))return;if(U.status==="changed"){P({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!M(n)||(ve=await ce.realpath(_),!M(n)))return;B=await ce.lstat(_)}catch(x){if(!M(n))return;if(!Pe(x)&&!Ee(x))throw x;P({path:A,size:I.size,type:"file",reason:Ee(x)?"changed-during-read":"unreadable"});return}if(M(n)){if(U.bytes!==I.size||ve!==oe||!br(I,U.finalStat)||!br(U.finalStat,B)||!B.isFile()||B.isSymbolicLink()||B.size!==I.size||B.mtimeMs!==I.mtimeMs||B.ctimeMs!==I.ctimeMs){P({path:A,size:B.isFile()?B.size:null,type:B.isFile()?"file":"other",reason:"changed-during-read"});return}M(n)&&await Fe({path:A,hash:U.hash,size:B.size,type:"file",...q===void 0?{}:{gitObjectId:q}},{kind:"file",target:_,realTarget:oe,stat:B})}},ai=async(_,A,I)=>{if(!M(n))return;let q,oe,U;try{if(q=await ce.readlink(_,{encoding:"buffer"}),!M(n)||(U=await ce.lstat(_),!M(n)))return;oe=await ce.readlink(_,{encoding:"buffer"})}catch(x){if(!M(n))return;if(!Pe(x)&&!Ee(x))throw x;P({path:A,size:null,type:"other",reason:Ee(x)?"changed-during-read":"unreadable"});return}if(!M(n))return;if(!U.isSymbolicLink()||!br(I,U)||U.mtimeMs!==I.mtimeMs||U.ctimeMs!==I.ctimeMs||!q.equals(oe)){P({path:A,size:null,type:"other",reason:"changed-during-read"});return}let B=q.byteLength;if(m.length>=i.maxFiles){P({path:A,size:B,type:"other",reason:"file-count"});return}if(B>i.maxFileBytes){P({path:A,size:B,type:"other",reason:"file-size"});return}if(S+B>i.maxTotalBytes){P({path:A,size:B,type:"other",reason:"total-size"});return}let ve=Ol("sha256").update("symlink\0").update(q).digest("hex");M(n)&&await Fe({path:A,hash:ve,size:B,type:"file"},{kind:"symlink",target:_,rawTarget:q,stat:U})},Vt=async()=>{for(let[_,A]of[...b]){if(!M(n))return;if(A.kind==="file"){let B,ve;try{if(B=await ce.realpath(A.target),!M(n))return;ve=await ce.lstat(A.target)}catch(x){if(!M(n))return;if(!Pe(x)&&!Ee(x))throw x;ue(_,{path:_,size:null,type:"file",reason:Pe(x)?"unreadable":"changed-during-read"});continue}if(!M(n))return;(B!==A.realTarget||!ve.isFile()||ve.isSymbolicLink()||!br(A.stat,ve)||ve.size!==A.stat.size||ve.mtimeMs!==A.stat.mtimeMs||ve.ctimeMs!==A.stat.ctimeMs)&&ue(_,{path:_,size:ve.isFile()?ve.size:null,type:ve.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let B,ve;try{if(B=await ce.lstat(A.target),!M(n))return;ve=await ce.readlink(A.target,{encoding:"buffer"})}catch(x){if(!M(n))return;if(!Pe(x)&&!Ee(x))throw x;ue(_,{path:_,size:null,type:"other",reason:Pe(x)?"unreadable":"changed-during-read"});continue}if(!M(n))return;(!B.isSymbolicLink()||!br(A.stat,B)||B.mtimeMs!==A.stat.mtimeMs||B.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(ve))&&ue(_,{path:_,size:null,type:"other",reason:"changed-during-read"});continue}let I,q;try{if(I=await ce.realpath(A.target),!M(n))return;q=await ce.lstat(A.target)}catch{if(!M(n))return;ue(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!M(n))return;if(!(I===A.realTarget&&q.isDirectory()&&!q.isSymbolicLink()&&br(A.stat,q)&&O(c,I)&&!ti(u,I))){ue(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let U;try{if(!M(n))return;U=await hN(n,I)}catch(B){if(na(B))throw B;ue(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!M(n))return;U.dirty?ue(_,{path:_,size:null,type:"directory",reason:"gitlink-dirty"}):U.hash!==A.hash&&ue(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"})}for(let[_,A]of g){if(!M(n))return;try{let I=await ce.lstat(A);if(!M(n))return;P({path:_,size:I.isFile()?I.size:null,type:I.isFile()?"file":I.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(I){if(!M(n))return;if(Ee(I))continue;if(!Pe(I))throw I;P({path:_,size:null,type:"file",reason:"unreadable"})}}},pt=await EN(n,e,a,t.gitSelectionHooks);if(pt===null){let _=await dN({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let q of _.records){if(q.type!=="file"&&q.type!=="symlink"||b.has(q.path))continue;if(ei(n)<1)break;if(!mN(r,q.path,n))continue;if(ei(n)<1)break;let oe=V.resolve(s,...q.path.split("/")),U;try{U=await ce.lstat(oe)}catch(B){if(!M(n))break;if(!Pe(B)&&!Ee(B))throw B;P({path:q.path,size:null,type:"file",reason:Ee(B)?"changed-during-read":"unreadable"});continue}if(ei(n)<1)break;if(q.type==="symlink"&&U.isSymbolicLink()){if(await ai(oe,q.path,U),ei(n)<1)break;continue}if(q.type!=="file"||!U.isFile()||U.isSymbolicLink()){P({path:q.path,size:U.isFile()?U.size:null,type:U.isDirectory()?"directory":U.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await te(oe,q.path,U),ei(n)<1)break}ei(n)>=1&&await Vt();let A=await dN({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o}),I=bj(_.evidence,A.evidence);N=I.evidence;for(let q of[..._.omissions,...A.omissions,...I.omissions])p.some(oe=>oe.path===q.path&&oe.reason===q.reason)||P(q)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let _=t.incrementalBaseline,A=new Map,I=!1;if(_){let x=Ii(_);for(let de of x.entries)de.gitObjectId!==void 0&&A.set(de.path,de);I=A.size>0}let q=new Set,oe=!0;try{let x=await Wo(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(x.overflow)I=!1,oe=!1,A.clear();else for(let de of x.records){let ge=jl(de),Ye=ge.indexOf(" "),Be=Ye<0?null:aa(ge.slice(Ye+1));if(Ye!==1||Be===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");ge[0]!=="H"&&q.add(Be)}}catch(x){if(na(x))throw x;I=!1,oe=!1,A.clear()}let U=new Set;try{let x=await Il(n,s,["ls-files","--modified","-z"],Hh);for(let de of x.toString("utf8").split("\0")){let ge=aa(de);ge!==null&&U.add(ge)}}catch{I=!1,oe=!1,A.clear()}let B=new Set,ve=new Set;for(let x of CN(pt)){if(b.has(x)||!qo(e,x))continue;if(ei(n)<1)break;if(!mN(r,x,n))continue;if(ei(n)<1)break;let de=V.resolve(s,...x.split("/"));if(de===f||de===h||ti(d,de)||v.some(mt=>ti(mt,de)))continue;if(pt.gitlinks.has(x)){if(m.length>=i.maxFiles){P({path:x,size:0,type:"file",reason:"file-count"});continue}let mt,zs;try{[mt,zs]=await Promise.all([ce.realpath(de),ce.lstat(de)])}catch{P({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(zs.isSymbolicLink()||!zs.isDirectory()||!O(c,mt)||ti(u,mt)){P({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let Pn=await hN(n,mt);if(Pn.dirty){P({path:x,size:null,type:"directory",reason:"gitlink-dirty"});continue}await Fe({path:x,hash:Pn.hash,size:0,type:"file"},{kind:"gitlink",target:de,realTarget:mt,stat:zs,hash:Pn.hash})}catch(Pn){if(na(Pn))throw Pn;P({path:x,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let ge;try{ge=await ce.lstat(de)}catch(mt){if(Ee(mt)&&pt.tracked.has(x)){g.set(x,de);continue}if(!Pe(mt)&&!Ee(mt))throw mt;P({path:x,size:null,type:"file",reason:Ee(mt)?"changed-during-read":"unreadable"});continue}if(ge.isSymbolicLink()){await ai(de,x,ge);continue}if(!ge.isFile()){pt.nestedRepositories.has(x)||P({path:x,size:null,type:"other",reason:"changed-during-read"});continue}let Ye=pt.trackedObjectIds.get(x),Be=Ye?A.get(x):void 0;if(I&&Be?.gitObjectId!==void 0&&Be.gitObjectId===Ye&&!q.has(x)&&!U.has(x)){if(m.length>=i.maxFiles){P({path:x,size:Be.size,type:"file",reason:"file-count"});continue}if(Be.size>i.maxFileBytes){P({path:x,size:Be.size,type:"file",reason:"file-size"});continue}if(S+Be.size>i.maxTotalBytes){P({path:x,size:Be.size,type:"file",reason:"total-size"});continue}m.push({...Be}),S+=Be.size,B.add(x);continue}let qm=oe&&!q.has(x)&&!U.has(x)?Ye:void 0;await te(de,x,ge,qm),qm!==void 0&&ve.add(x)}if(await Vt(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await PN(n,e,a,pt,t.gitSelectionHooks?.outputChunkBytes),B.size>0||I&&ve.size>0){let x=await Il(n,s,["ls-files","--modified","-z"],Hh),de=new Set;for(let ge of x.toString("utf8").split("\0")){let Ye=aa(ge);Ye!==null&&de.add(Ye)}for(let ge of B){if(!de.has(ge))continue;let Ye=m.find(Be=>Be.path===ge);ue(ge,{path:ge,size:Ye?.size??null,type:"file",reason:"changed-during-read"})}for(let ge of ve){if(!de.has(ge))continue;let Ye=m.find(Be=>Be.path===ge);Ye&&delete Ye.gitObjectId}}for(let x of pt.omissions)P(x);pt.overflow&&F(pt.overflow)}m.sort((_,A)=>_.path.localeCompare(A.path,"en")),p.sort((_,A)=>_.path.localeCompare(A.path,"en"));let fP=pt===null?{provider:"physical-tree",...N?{physicalSelection:N}:{}}:{provider:"git",...pt.evidence?{gitSelection:pt.evidence}:{}},Vm=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:fP,createdAt:(t.now??new Date).toISOString(),complete:y===0,limits:i,...r?{policy:r.manifest}:{},entries:m,omitted:p,omittedCount:y,...E>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${k}`,hash:k,count:E}}:{}}),sd=Vm();for(;Vh(sd)>i.maxManifestBytes;){if(p.filter(A=>!Dh(A)).length>0){let A=Math.max(1,Math.ceil(p.length/4));for(let I=0;I<A;I+=1){let q=$l(p);if(q===null)break;w(q)}}else if(m.length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let I of m.splice(-A))y+=1,$(I)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");sd=Vm()}return sd}async function qh(e,t,i={}){let n=(await ye(e.projectRoot))?.native.snapshot??lh;return Ll(e,{...i,policy:t.policy,incrementalBaseline:t,limits:{maxFiles:n.max_files,maxFileBytes:n.max_total_bytes,maxTotalBytes:n.max_total_bytes,maxDurationMs:n.max_duration_ms},deadlineMs:n.max_duration_ms})}async function Wh(e,t,i){let r=_N(e,t);await T(j(e,r),r),await ee(r,Ii(i))}async function sa(e,t){let i=_N(e,t),r=j(e,i);await T(r,i);try{let n=await Sl({root:r,file:i,maxBytes:WI,label:"Native baseline snapshot manifest"});return Ii(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as Xj}from"crypto";import Qj from"path";var Nt=Object.freeze({stateRef:"runtime/run-state.json",pendingRef:"runtime/pending-action.json",trajectoryRef:"runtime/trajectory.jsonl",contextRef:"runtime/context.md",artifactsRef:"runtime/artifacts.json",checkpointRef:"runtime/checkpoints/latest.json",snapshotsRef:"runtime/skill-snapshots"});import{createHash as zj}from"node:crypto";import{constants as Fl,promises as tt}from"node:fs";import bt from"node:path";import{TextDecoder as Jj}from"node:util";import Bj from"path";var Dj=Rn(Qr(),1);var J1=4*1024*1024;var Lj=null;function Mj(e,t){let i=e;for(let r of t)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function TN(e,t){return(...i)=>{let r=Lj;if(r===null)return t(...i);let n=Mj(`async:${e}`,i),a=r.entries.get(n);if(a)return a.value;let o=t(...i).catch(s=>{throw r.entries.delete(n),s});return r.entries.set(n,{value:o}),o}}var X1=TN("hookWritePolicy",async e=>(await nh(e))?.hook??{allow_paths:[]});var IN=(e,t)=>{let i=e[t];return i==null?null:String(i)};function Go(e,t){let i=e[t];if(typeof i!="string"||i.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return i}function Jo(e,t){let i=Go(e,t);if(Bj.isAbsolute(i)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(i)||i.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return i}function Vj(e){let t=e.run_retries??"{}",i;try{i=typeof t=="string"?JSON.parse(t):t}catch(r){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:r})}if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let r of Object.values(i))if(!Number.isInteger(r)||Number(r)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return i}function jN(e){if(!e.run_id)return null;let t=Go(e,"run_id"),i=Go(e,"skill"),r=Go(e,"skill_version"),n=Go(e,"skill_hash"),a=Jo(e,"pending_ref"),o=Jo(e,"trajectory_ref"),s=Jo(e,"context_ref"),c=Jo(e,"artifacts_ref"),l=Jo(e,"checkpoint_ref"),u=Number(e.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(e.orchestration!=="deterministic"&&e.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(e.run_status!=="running"&&e.run_status!=="waiting"&&e.run_status!=="completed"&&e.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:t,skill:i,skillVersion:r,skillHash:n,orchestration:e.orchestration,currentStep:IN(e,"current_step"),iteration:u,pending:IN(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:Vj(e)}}var zW=256*1024;var qj=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function Wj(e){let t={run_id:e.runId,skill:e.skill,skill_version:e.skillVersion,skill_hash:e.skillHash,orchestration:e.orchestration,current_step:e.currentStep,iteration:e.iteration,pending:e.pending,pending_ref:e.pendingRef,trajectory_ref:e.trajectoryRef,context_ref:e.contextRef,artifacts_ref:e.artifactsRef,checkpoint_ref:e.checkpointRef,run_status:e.status,run_retries:JSON.stringify(e.retries)},i=jN(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function Ml(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Run state: stored value must be an object");let t=e,i=Object.keys(t).find(r=>!qj.has(r));if(i)throw new Error(`Invalid Run state: unknown field ${i}`);if(t.currentStep!==null&&(typeof t.currentStep!="string"||t.currentStep.length===0))throw new Error("Invalid Run state: currentStep must be a non-empty string or null");if(t.pending!==null&&(typeof t.pending!="string"||t.pending.length===0))throw new Error("Invalid Run state: pending must be a non-empty string or null");if(!t.retries||typeof t.retries!="object"||Array.isArray(t.retries))throw new Error("Invalid Run state: retries must be an object");return Wj(t)}var Je={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};function Ko(e,t){let i=bt.relative(e,t);return i===""||!bt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${bt.sep}`)}function ON(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Uo(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function Gj(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Sr(e,t,i){let r=Nt[t];if(i!==void 0&&i!==r)throw new Error(`Native Run ${t} ref must be ${r}`);let n=bt.resolve(e),a=bt.resolve(n,...r.slice(8).split("/"));if(!Ko(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function $N(e){let t=await tt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await tt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function zh(e,t){let i=bt.resolve(e),r=bt.resolve(t);if(!Ko(i,r))throw new Error("Native Run path is outside its change");let n=[await $N(i)],a=i;for(let o of bt.relative(i,r).split(bt.sep).filter(Boolean)){a=bt.join(a,o);let s;try{s=await $N(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!Ko(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function Bl(e){for(let t of e){let i=await tt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!Gj(t,i)||await tt.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function Uj(e,t,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${i} exceeds ${t} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function ln(e,t,i,r,n){let a=await zh(e,bt.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await tt.lstat(t)}catch(d){if(d.code==="ENOENT")return null;throw d}if(!o.isFile()||o.isSymbolicLink())throw new Error(`${r} must be a regular file`);if(o.size>i)throw new Error(`${r} exceeds ${i} bytes`);let s=ON(o),c=await tt.realpath(t);if(!Ko(a[0].realPath,c))throw new Error(`${r} resolves outside its change`);let l=process.platform==="win32"?Fl.O_RDONLY:Fl.O_RDONLY|Fl.O_NOFOLLOW|Fl.O_NONBLOCK,u;try{u=await tt.open(t,l)}catch(d){throw new Error(`${r} changed while opening`,{cause:d})}try{let[d,f,h]=await Promise.all([u.stat(),tt.lstat(t),tt.realpath(t)]);if(await Bl(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||h!==c||!Uo(s,d)||!Uo(s,f))throw new Error(`${r} changed while opening`);await n?.afterOpen?.();let v=await Uj(u,i,r);await n?.beforeFinalCheck?.();let[m,p,b]=await Promise.all([u.stat(),tt.lstat(t),tt.realpath(t)]);if(await Bl(a),!p.isFile()||p.isSymbolicLink()||b!==c||!Uo(s,m)||!Uo(s,p))throw new Error(`${r} changed while reading`);let g;try{g=new Jj("utf-8",{fatal:!0}).decode(v)}catch(y){throw new Error(`${r} is not valid UTF-8`,{cause:y})}return{text:g,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}async function Kj(e,t,i){let r=await zh(e,bt.dirname(t));if(!r)return{exists:!1};let n;try{n=await tt.lstat(t)}catch(o){if(o.code==="ENOENT")return{exists:!1};throw o}if(!n.isFile()||n.isSymbolicLink())throw new Error(`${i} must be a regular file`);let a=await tt.realpath(t);if(!Ko(r[0].realPath,a))throw new Error(`${i} resolves outside its change`);return await Bl(r),{exists:!0,identity:ON(n),realPath:a}}async function Yj(e,t,i,r){let n=await zh(e,bt.dirname(t));if(!n){if(!i.exists)return;throw new Error(`${r} parent changed before commit`)}let a;try{a=await tt.lstat(t)}catch(o){if(o.code==="ENOENT"&&!i.exists)return;throw new Error(`${r} changed before commit`,{cause:o})}if(!i.exists||!a.isFile()||a.isSymbolicLink()||!Uo(i.identity,a)||await tt.realpath(t)!==i.realPath)throw new Error(`${r} changed before commit`);await Bl(n)}async function Vl(e){if(Buffer.byteLength(e.content,"utf8")>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);let i=e.expected??await Kj(e.changeDir,e.file,e.label);if(i.exists&&i.identity.size>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);await he(e.file,e.content,{containedRoot:e.changeDir,beforeCommit:async()=>{await e.hooks?.beforeCommit?.(),await Yj(e.changeDir,e.file,i,e.label)}});let r=await ln(e.changeDir,e.file,e.maxBytes,e.label);if(!r||r.text!==e.content)throw new Error(`${e.label} commit could not be verified`)}function HN(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function DN(e){return`${JSON.stringify(e,null,2)}
190
- `}function Er(e){return Ml(e)}async function $e(e,t){let i=Sr(e,"stateRef"),r=await ln(e,i,Je.runStateBytes,"Native Run state",t);return r?Ml(HN(r.text,"Native Run state")):null}async function un(e,t,i){let r=Ml(t);await Vl({changeDir:e,file:Sr(e,"stateRef"),content:DN(r),maxBytes:Je.runStateBytes,label:"Native Run state",hooks:i})}async function it(e,t,i){let r=Sr(e,"trajectoryRef",t),n=await ln(e,r,Je.trajectoryBytes,"Native Run trajectory",i);if(!n)return[];let a=n.text.split(/\r?\n/u).map((o,s)=>({line:o,number:s+1})).filter(({line:o})=>o.length>0);if(a.length>Je.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Je.trajectoryEvents} events`);return a.map(({line:o,number:s})=>{try{return JSON.parse(o)}catch(c){throw new Error(`Invalid Native Run trajectory event at line ${s}`,{cause:c})}})}async function LN(e,t,i){return(await ln(e,Sr(e,"trajectoryRef",t),Je.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function MN(e,t,i,r,n){if(!/^[a-f0-9]{64}$/u.test(r))throw new Error("Native Run trajectory expected hash is invalid");let a=Sr(e,"trajectoryRef",t),o=await ln(e,a,Je.trajectoryBytes,"Native Run trajectory");if(!o)throw new Error("Native Run trajectory disappeared before repair");if(zj("sha256").update(o.text,"utf8").digest("hex")!==r)throw new Error("Native Run trajectory changed before repair");await Vl({changeDir:e,file:a,content:i,maxBytes:Je.trajectoryBytes,label:"Native Run trajectory",expected:o.target,hooks:n})}async function FN(e,t,i,r){let n=Sr(e,"trajectoryRef",t),a=`${JSON.stringify(i)}
191
- `;if(Buffer.byteLength(a,"utf8")>Je.trajectoryEventBytes)throw new Error(`Native Run trajectory event exceeds ${Je.trajectoryEventBytes} bytes`);let o=await ln(e,n,Je.trajectoryBytes,"Native Run trajectory");if((o?o.text.split(/\r?\n/u).filter(c=>c.length>0).length:0)>=Je.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Je.trajectoryEvents} events`);await Vl({changeDir:e,file:n,content:`${o?.text??""}${a}`,maxBytes:Je.trajectoryBytes,label:"Native Run trajectory",expected:o?.target??{exists:!1},hooks:r})}async function ca(e,t,i){let r=await ln(e,Sr(e,"checkpointRef",t),Je.checkpointBytes,"Native Run checkpoint",i);return r?HN(r.text,"Native Run checkpoint"):null}async function BN(e,t,i,r){await Vl({changeDir:e,file:Sr(e,"checkpointRef",t),content:DN(i),maxBytes:Je.checkpointBytes,label:"Native Run checkpoint",hooks:r})}var Zj=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ql=class extends Error{constructor(i){super(i.status==="repairable"?`Native trajectory has an incomplete final line at ${i.file}:${i.line}; run doctor --repair`:`Native trajectory is invalid at ${i.file}:${i.line}: ${i.message}`);this.inspection=i;this.name="NativeTrajectoryRepairRequiredError"}inspection;code="native-trajectory-tail-repair-required"};function Jh(e){return Xj("sha256").update(e).digest("hex")}function e$(e,t){if(!Zj.test(t))throw new Error(`Invalid Native change name: ${t}`);return Qj.join(H(e,t),"trajectory.jsonl")}function t$(e){let t=e.split(/\n/u),i=0;for(let r=0;r<t.length;r+=1){let n=t[r].endsWith("\r")?t[r].slice(0,-1):t[r];if(n.length!==0){i=r+1;try{JSON.parse(n)}catch(a){return{status:"invalid",line:r+1,message:a.message}}}}return{status:"valid",count:i}}function i$(e,t){if(/Unexpected end|Unterminated string/iu.test(e.message))return!0;let i=/position (\d+)/iu.exec(e.message)?.[1];return i!==void 0&&Number(i)>=Math.max(0,t.length-1)}function r$(e,t){let i=t.lastIndexOf(10),r=t.subarray(0,i+1),n=t$(r.toString("utf8"));if(n.status==="invalid")return{status:"invalid",file:e,line:n.line,message:n.message};if(i===t.length-1)return{status:"clean",file:e};let a=t.subarray(i+1),o=a.toString("utf8"),s=n.count+1,c,l;try{JSON.parse(o.endsWith("\r")?o.slice(0,-1):o),c="missing-newline",l=Buffer.concat([t,Buffer.from(`
192
- `)])}catch(d){if(!i$(d,o))return{status:"invalid",file:e,line:s,message:d.message};c="incomplete-json",l=r}return{inspection:{status:"repairable",file:e,reason:c,line:s,originalHash:Jh(t),targetHash:Jh(l),tailHash:Jh(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function VN(e,t){let i=e$(e,t);await T(j(e,i),i);let r=H(e,t),n=await LN(r,Nt.trajectoryRef);return n===null?{status:"clean",file:i}:r$(i,Buffer.from(n))}async function la(e,t){let i=await VN(e,t);return"inspection"in i?i.inspection:i}async function Wl(e,t){let i=await la(e,t);if(i.status!=="clean")throw new ql(i)}async function qN(e,t,i){return se(e,`repair trajectory tail for ${t}`,async()=>{let r=await VN(e,t);if(!("inspection"in r)){if(r.status==="clean")return null;throw new ql(r)}try{await MN(H(e,t),Nt.trajectoryRef,r.targetContent,r.inspection.originalHash,{beforeCommit:i?.beforeCommit})}catch(a){throw/changed (?:before|while)/iu.test(a.message)?new Error(`Native trajectory changed while preparing tail repair for ${t}; inspect it again before retrying`,{cause:a}):a}if((await la(e,t)).status!=="clean")throw new Error(`Native trajectory tail repair did not produce a clean file for ${t}`);return r.inspection})}import{createHash as n$}from"node:crypto";import{promises as zl}from"node:fs";import ji from"node:path";var Yo=/^[a-f0-9]{64}$/u,WN=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,a$=16*1024,Uh=process.platform,o$=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function ua(e){return o$.has(e)}function GN(e,t){let i=ji.relative(e,t);return ji.isAbsolute(i)||i===".."||i.startsWith(`..${ji.sep}`)?null:i.replaceAll("\\","/")||"."}function UN(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function KN(e,t){if(e.length===0||UN(e)||e.includes("\\")||ji.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let i=ji.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function Kh(e,t){return n$("sha256").update(`${e}
193
- ${t}`).digest("hex")}async function zN(e,t){let i=await zl.realpath(t),r=await zl.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Uh==="win32"?ji.normalize(i).toLowerCase():i;return Kh(e,`${n}
189
+ ${Buffer.byteLength(r)}:${r}`)}function Mh(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function Ml(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!Mh(i))return e.splice(t,1),i}return null}function Sr(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return vt(i,r)?z(i,r):z(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function jj(e,t,i,r){if(!M(r))return{status:"budget-exhausted"};let n;try{n=await ce.open(e,"r")}catch(c){if(!M(r))return{status:"budget-exhausted"};throw c}if(!M(r))return await n.close(),{status:"budget-exhausted"};let a=Fl("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!M(r))return{status:"budget-exhausted"};let c=await n.stat();if(!M(r))return{status:"budget-exhausted"};if(!c.isFile()||!Sr(i,c))return{status:"changed"};for(;;){if(!M(r))return{status:"budget-exhausted"};let l=t+1-s;if(l<1)return{status:"changed"};let u=await n.read(o,0,Math.min(o.length,l),null);if(!M(r))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!M(r))return{status:"budget-exhausted"};let d=await n.stat();return M(r)?!d.isFile()||!Sr(c,d)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:d}:{status:"budget-exhausted"}}if(s+u.bytesRead>t)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await n.close()}}function It(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function jt(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function la(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function pi(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function _N(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let i=V.posix.normalize(e);if(i!==e||V.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function $j(e,t){let i=It(e,`Native snapshot entry ${t}`);jt(i,sj,`Native snapshot entry ${t}`);let r=_N(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!Bl.test(i.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(i.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:r,hash:i.hash,size:pi(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!NN.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=i.gitObjectId}return n}function Oj(e,t){let i=It(e,`Native snapshot omission ${t}`);if(jt(i,cj,`Native snapshot omission ${t}`),!dj.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!fj.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:_N(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:pi(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function Hj(e){let t=It(e,"Native snapshot omission overflow");if(jt(t,lj,"Native snapshot omission overflow"),typeof t.hash!="string"||!Bl.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let i=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==i)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:i,hash:t.hash,count:la(t.count,"Native snapshot omission overflow count")}}function ca(e,t){let i=It(e,t);if(jt(i,nj,t),typeof i.hash!="string"||!Bl.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let r=pi(i.recordCount,`${t} recordCount`),n=pi(i.storedRecordCount,`${t} storedRecordCount`),a=pi(i.stdoutBytes,`${t} stdoutBytes`);if(n>r||!i.overflow&&n!==r)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,recordCount:r,storedRecordCount:n,stdoutBytes:a,overflow:i.overflow}}function gN(e){let t=It(e,"Native Git selection evidence");if(jt(t,rj,"Native Git selection evidence"),t.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let i=ca(t.stageBefore,"Native Git selection stageBefore"),r=ca(t.combined,"Native Git selection combined"),n=ca(t.stageAfter,"Native Git selection stageAfter"),a=ca(t.finalStageBefore,"Native Git selection finalStageBefore"),o=ca(t.finalCombined,"Native Git selection finalCombined"),s=ca(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,r,n,a,o,s].some(d=>d.overflow),l=!Er(i,n)||!Er(n,a)||!Er(r,o)||!Er(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(t.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:i,combined:r,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function wN(e,t){let i=It(e,t);if(jt(i,oj,t),typeof i.hash!="string"||!Bl.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean"||typeof i.unstable!="boolean")throw new Error(`${t} flags are invalid`);let r=pi(i.visitedNodeCount,`${t} visitedNodeCount`),n=pi(i.recordCount,`${t} recordCount`),a=pi(i.storedRecordCount,`${t} storedRecordCount`),o=pi(i.encodedBytes,`${t} encodedBytes`);if(a>n||!i.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,visitedNodeCount:r,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:i.overflow,unstable:i.unstable}}function Dj(e){let t=It(e,"Native physical selection evidence");if(jt(t,aj,"Native physical selection evidence"),t.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let i=wN(t.before,"Native physical selection before"),r=wN(t.after,"Native physical selection after"),n=i.overflow||r.overflow,a=i.unstable||r.unstable||!CN(i,r);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:i,after:r}}function $i(e){let t=It(e,"Native content snapshot manifest");if(jt(t,QI,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!uj.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let S=It(t.capture,"Native content snapshot capture");if(jt(S,tj,"Native content snapshot capture"),S.provider!=="git"&&S.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let R=S.gitSelection===void 0?void 0:gN(S.gitSelection),N=S.physicalSelection===void 0?void 0:Dj(S.physicalSelection),w=null;if(S.projection!==void 0){let P=It(S.projection,"Native content snapshot projection");if(jt(P,ij,"Native content snapshot projection"),P.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");w={provider:"git",...P.selection===void 0?{}:{selection:gN(P.selection)}}}if(S.provider==="git"){if(N||w)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...R?{gitSelection:R}:{}}}else{if(R)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(N&&w)throw new Error("Native physical-tree capture cannot combine selection and projection");i=w?{provider:"physical-tree",projection:w}:{provider:"physical-tree",...N?{physicalSelection:N}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let r=It(t.limits,"Native content snapshot limits");jt(r,ZI,"Native content snapshot limits");let n={maxFiles:la(r.maxFiles,"Native snapshot maxFiles"),maxFileBytes:la(r.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:la(r.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:la(r.maxManifestBytes,"Native snapshot maxManifestBytes"),...r.maxDurationMs===void 0?{}:{maxDurationMs:la(r.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let S=It(t.policy,"Native snapshot policy");if(jt(S,ej,"Native snapshot policy"),S.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(S.include)||!Array.isArray(S.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=AN({include:S.include,exclude:S.exclude,hash:S.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map($j),s=t.omitted.map(Oj),c=pi(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:Hj(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(S=>S.size>n.maxFileBytes)||o.reduce((S,R)=>S+R.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(S=>S.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>Fh||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(S=>S.reason==="git-enumeration-limit"),f=s.filter(S=>S.reason==="git-selection-changed");for(let S of[...d,...f])if(S.path!=="."||S.size!==null||S.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let h=i?.provider==="git"?i.gitSelection:i?.projection?.selection,v=h?.status==="overflow"||h?.status==="overflow-and-changed",m=h?.status==="changed"||h?.status==="overflow-and-changed";if(v!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(m!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let p=s.filter(S=>S.reason==="physical-enumeration-limit"),b=s.filter(S=>S.reason==="physical-selection-changed");for(let S of[...p,...b])if(S.path!=="."||S.size!==null||S.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(p.length>1||b.length>1)throw new Error("Native physical selection omissions must not be duplicated");let g=i?.physicalSelection,y=g?.status==="overflow"||g?.status==="overflow-and-changed",E=g?.status==="changed"||g?.status==="overflow-and-changed";if(y!==(p.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(E!==(b.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let k={schema:"comet.native.content-snapshot.v1",origin:t.origin,...i?{capture:i}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(Wh(k)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return k}async function Vl(e,t,i={}){let r=$i(t);if(r.capture?.provider==="git"||r.capture?.projection||r.capture?.physicalSelection)return r;let n=V.resolve(e.projectRoot),a=bN(i),o=kN(i.gitSelectionLimits),s=await PN(a,e,o,i.gitSelectionHooks);if(s===null)return r;let c=new Set(xN(s).filter(N=>Go(e,N))),l=[...s.gitlinks].filter(N=>c.has(N)),u=[...s.nestedRepositories].filter(N=>Go(e,N)),d=(N,w)=>w.some(P=>N===P||N.startsWith(`${P}/`)),f=N=>d(N,l),h=N=>d(N,u),v=[...r.entries.map(N=>N.path),...r.omitted.flatMap(N=>N.type==="directory"?[N.path,`${N.path}/`]:[N.path])].filter(N=>!c.has(N)&&!f(N)&&!h(N)),m=await Nj(a,n,v),p=r.entries.filter(N=>!f(N.path)&&!h(N.path)&&Go(e,N.path)&&(c.has(N.path)||!m.has(N.path)));await RN(a,e,o,s,i.gitSelectionHooks?.outputChunkBytes);let b=[...s.omissions];for(let N of l)b.push({path:N,size:null,type:"directory",reason:"legacy-gitlink-boundary"});p.sort((N,w)=>N.path.localeCompare(w.path,"en"));let g=r.omitted.filter(N=>f(N.path)||h(N.path)||!Go(e,N.path)?!1:m.has(N.path)?c.has(N.path)||[...c].some(w=>w.startsWith(`${N.path}/`)):!0);for(let N of b)g.some(w=>w.path===N.path&&w.reason===N.reason)||g.push(N);g.sort((N,w)=>N.path.localeCompare(w.path,"en"));let y=r.omissionOverflow?.count??0,E=r.omissionOverflow?.hash??L("comet.native.snapshot-omission-overflow.v1");s.overflow&&(y+=s.overflow.count,E=Ko(E,"git-selection",{source:"git-selection",...s.overflow}));let k=N=>{y+=1,E=Ko(E,"omission",N)};for(;g.length>Fh;){let N=Ml(g);if(N===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");k(N)}let S=()=>({...r,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:g.length+y===0,entries:p,omitted:g,omittedCount:g.length+y,...y>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${E}`,hash:E,count:y}}:{}}),R=S();for(;Wh(R)>r.limits.maxManifestBytes;){let N=Ml(g);if(N===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");k(N),R=S()}return $i(R)}function TN(e,t){if(!XI.test(t))throw new Error(`Invalid Native change name: ${t}`);return V.join(H(e,t),"baseline-manifest.json")}async function ql(e,t={}){let i={maxFiles:t.limits?.maxFiles??Hl.maxFiles,maxFileBytes:t.limits?.maxFileBytes??Hl.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??Hl.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??Hl.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},r=AN(t.policy),n=bN({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=kN(t.gitSelectionLimits),o=wj(t.physicalSelectionLimits);if(i.maxFiles<1||i.maxFileBytes<1||i.maxTotalBytes<1||i.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=V.resolve(e.projectRoot),c=await ce.realpath(s),l=V.resolve(e.nativeRoot),u=await ce.realpath(l),d=V.resolve(e.runtimeDir),f=V.resolve(e.configFile),h=V.join(s,".comet","current-change.json"),v=Aj(s,t.denylist??[]),m=[],p=[],b=new Map,g=new Map,y=0,E=0,k=L("comet.native.snapshot-omission-overflow.v1"),S=0,R=!1,N=null,w=_=>{E+=1,k=Ko(k,"omission",_)},P=_=>{if(y+=1,p.length<Fh){p.push(_);return}if(Mh(_)){let A=Ml(p);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");w(A),p.push(_);return}w(_)},F=_=>{y+=_.count,E+=_.count,k=Ko(k,"git-selection",{source:"git-selection",..._})},$=_=>{E+=1,k=Ko(k,"manifest-entry",{reason:"manifest-size",entry:_})},Be=async(_,A)=>{m.push(_),S+=_.size,b.set(_.path,A),R||(R=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(_.path))},ue=(_,A)=>{let I=m.findIndex(oe=>oe.path===_);if(I<0)return;let[q]=m.splice(I,1);S-=q.size,b.delete(_),P(A)},te=async(_,A,I,q)=>{if(!I.isFile()||I.isSymbolicLink()||!M(n))return;let oe;try{oe=await ce.realpath(_)}catch(x){if(!M(n))return;if(!Pe(x)&&!Ee(x))throw x;P({path:A,size:I.size,type:"file",reason:Ee(x)?"changed-during-read":"unreadable"});return}if(!M(n)||!O(c,oe)||ii(u,oe))return;if(m.length>=i.maxFiles){P({path:A,size:I.size,type:"file",reason:"file-count"});return}if(I.size>i.maxFileBytes){P({path:A,size:I.size,type:"file",reason:"file-size"});return}if(S+I.size>i.maxTotalBytes){P({path:A,size:I.size,type:"file",reason:"total-size"});return}let U,B,ve;try{if(U=await jj(oe,I.size,I,n),U.status==="budget-exhausted"||!M(n))return;if(U.status==="changed"){P({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!M(n)||(ve=await ce.realpath(_),!M(n)))return;B=await ce.lstat(_)}catch(x){if(!M(n))return;if(!Pe(x)&&!Ee(x))throw x;P({path:A,size:I.size,type:"file",reason:Ee(x)?"changed-during-read":"unreadable"});return}if(M(n)){if(U.bytes!==I.size||ve!==oe||!Sr(I,U.finalStat)||!Sr(U.finalStat,B)||!B.isFile()||B.isSymbolicLink()||B.size!==I.size||B.mtimeMs!==I.mtimeMs||B.ctimeMs!==I.ctimeMs){P({path:A,size:B.isFile()?B.size:null,type:B.isFile()?"file":"other",reason:"changed-during-read"});return}M(n)&&await Be({path:A,hash:U.hash,size:B.size,type:"file",...q===void 0?{}:{gitObjectId:q}},{kind:"file",target:_,realTarget:oe,stat:B})}},oi=async(_,A,I)=>{if(!M(n))return;let q,oe,U;try{if(q=await ce.readlink(_,{encoding:"buffer"}),!M(n)||(U=await ce.lstat(_),!M(n)))return;oe=await ce.readlink(_,{encoding:"buffer"})}catch(x){if(!M(n))return;if(!Pe(x)&&!Ee(x))throw x;P({path:A,size:null,type:"other",reason:Ee(x)?"changed-during-read":"unreadable"});return}if(!M(n))return;if(!U.isSymbolicLink()||!Sr(I,U)||U.mtimeMs!==I.mtimeMs||U.ctimeMs!==I.ctimeMs||!q.equals(oe)){P({path:A,size:null,type:"other",reason:"changed-during-read"});return}let B=q.byteLength;if(m.length>=i.maxFiles){P({path:A,size:B,type:"other",reason:"file-count"});return}if(B>i.maxFileBytes){P({path:A,size:B,type:"other",reason:"file-size"});return}if(S+B>i.maxTotalBytes){P({path:A,size:B,type:"other",reason:"total-size"});return}let ve=Fl("sha256").update("symlink\0").update(q).digest("hex");M(n)&&await Be({path:A,hash:ve,size:B,type:"file"},{kind:"symlink",target:_,rawTarget:q,stat:U})},Vt=async()=>{for(let[_,A]of[...b]){if(!M(n))return;if(A.kind==="file"){let B,ve;try{if(B=await ce.realpath(A.target),!M(n))return;ve=await ce.lstat(A.target)}catch(x){if(!M(n))return;if(!Pe(x)&&!Ee(x))throw x;ue(_,{path:_,size:null,type:"file",reason:Pe(x)?"unreadable":"changed-during-read"});continue}if(!M(n))return;(B!==A.realTarget||!ve.isFile()||ve.isSymbolicLink()||!Sr(A.stat,ve)||ve.size!==A.stat.size||ve.mtimeMs!==A.stat.mtimeMs||ve.ctimeMs!==A.stat.ctimeMs)&&ue(_,{path:_,size:ve.isFile()?ve.size:null,type:ve.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let B,ve;try{if(B=await ce.lstat(A.target),!M(n))return;ve=await ce.readlink(A.target,{encoding:"buffer"})}catch(x){if(!M(n))return;if(!Pe(x)&&!Ee(x))throw x;ue(_,{path:_,size:null,type:"other",reason:Pe(x)?"unreadable":"changed-during-read"});continue}if(!M(n))return;(!B.isSymbolicLink()||!Sr(A.stat,B)||B.mtimeMs!==A.stat.mtimeMs||B.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(ve))&&ue(_,{path:_,size:null,type:"other",reason:"changed-during-read"});continue}let I,q;try{if(I=await ce.realpath(A.target),!M(n))return;q=await ce.lstat(A.target)}catch{if(!M(n))return;ue(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!M(n))return;if(!(I===A.realTarget&&q.isDirectory()&&!q.isSymbolicLink()&&Sr(A.stat,q)&&O(c,I)&&!ii(u,I))){ue(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let U;try{if(!M(n))return;U=await pN(n,I)}catch(B){if(ua(B))throw B;ue(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!M(n))return;U.dirty?ue(_,{path:_,size:null,type:"directory",reason:"gitlink-dirty"}):U.hash!==A.hash&&ue(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"})}for(let[_,A]of g){if(!M(n))return;try{let I=await ce.lstat(A);if(!M(n))return;P({path:_,size:I.isFile()?I.size:null,type:I.isFile()?"file":I.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(I){if(!M(n))return;if(Ee(I))continue;if(!Pe(I))throw I;P({path:_,size:null,type:"file",reason:"unreadable"})}}},pt=await PN(n,e,a,t.gitSelectionHooks);if(pt===null){let _=await fN({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let q of _.records){if(q.type!=="file"&&q.type!=="symlink"||b.has(q.path))continue;if(ti(n)<1)break;if(!vN(r,q.path,n))continue;if(ti(n)<1)break;let oe=V.resolve(s,...q.path.split("/")),U;try{U=await ce.lstat(oe)}catch(B){if(!M(n))break;if(!Pe(B)&&!Ee(B))throw B;P({path:q.path,size:null,type:"file",reason:Ee(B)?"changed-during-read":"unreadable"});continue}if(ti(n)<1)break;if(q.type==="symlink"&&U.isSymbolicLink()){if(await oi(oe,q.path,U),ti(n)<1)break;continue}if(q.type!=="file"||!U.isFile()||U.isSymbolicLink()){P({path:q.path,size:U.isFile()?U.size:null,type:U.isDirectory()?"directory":U.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await te(oe,q.path,U),ti(n)<1)break}ti(n)>=1&&await Vt();let A=await fN({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o}),I=Cj(_.evidence,A.evidence);N=I.evidence;for(let q of[..._.omissions,...A.omissions,...I.omissions])p.some(oe=>oe.path===q.path&&oe.reason===q.reason)||P(q)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let _=t.incrementalBaseline,A=new Map,I=!1;if(_){let x=$i(_);for(let de of x.entries)de.gitObjectId!==void 0&&A.set(de.path,de);I=A.size>0}let q=new Set,oe=!0;try{let x=await Uo(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(x.overflow)I=!1,oe=!1,A.clear();else for(let de of x.records){let ge=Ll(de),Ye=ge.indexOf(" "),Ve=Ye<0?null:da(ge.slice(Ye+1));if(Ye!==1||Ve===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");ge[0]!=="H"&&q.add(Ve)}}catch(x){if(ua(x))throw x;I=!1,oe=!1,A.clear()}let U=new Set;try{let x=await Dl(n,s,["ls-files","--modified","-z"],Lh);for(let de of x.toString("utf8").split("\0")){let ge=da(de);ge!==null&&U.add(ge)}}catch{I=!1,oe=!1,A.clear()}let B=new Set,ve=new Set;for(let x of xN(pt)){if(b.has(x)||!Go(e,x))continue;if(ti(n)<1)break;if(!vN(r,x,n))continue;if(ti(n)<1)break;let de=V.resolve(s,...x.split("/"));if(de===f||de===h||ii(d,de)||v.some(mt=>ii(mt,de)))continue;if(pt.gitlinks.has(x)){if(m.length>=i.maxFiles){P({path:x,size:0,type:"file",reason:"file-count"});continue}let mt,Us;try{[mt,Us]=await Promise.all([ce.realpath(de),ce.lstat(de)])}catch{P({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(Us.isSymbolicLink()||!Us.isDirectory()||!O(c,mt)||ii(u,mt)){P({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let _n=await pN(n,mt);if(_n.dirty){P({path:x,size:null,type:"directory",reason:"gitlink-dirty"});continue}await Be({path:x,hash:_n.hash,size:0,type:"file"},{kind:"gitlink",target:de,realTarget:mt,stat:Us,hash:_n.hash})}catch(_n){if(ua(_n))throw _n;P({path:x,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let ge;try{ge=await ce.lstat(de)}catch(mt){if(Ee(mt)&&pt.tracked.has(x)){g.set(x,de);continue}if(!Pe(mt)&&!Ee(mt))throw mt;P({path:x,size:null,type:"file",reason:Ee(mt)?"changed-during-read":"unreadable"});continue}if(ge.isSymbolicLink()){await oi(de,x,ge);continue}if(!ge.isFile()){pt.nestedRepositories.has(x)||P({path:x,size:null,type:"other",reason:"changed-during-read"});continue}let Ye=pt.trackedObjectIds.get(x),Ve=Ye?A.get(x):void 0;if(I&&Ve?.gitObjectId!==void 0&&Ve.gitObjectId===Ye&&!q.has(x)&&!U.has(x)){if(m.length>=i.maxFiles){P({path:x,size:Ve.size,type:"file",reason:"file-count"});continue}if(Ve.size>i.maxFileBytes){P({path:x,size:Ve.size,type:"file",reason:"file-size"});continue}if(S+Ve.size>i.maxTotalBytes){P({path:x,size:Ve.size,type:"file",reason:"total-size"});continue}m.push({...Ve}),S+=Ve.size,B.add(x);continue}let Wm=oe&&!q.has(x)&&!U.has(x)?Ye:void 0;await te(de,x,ge,Wm),Wm!==void 0&&ve.add(x)}if(await Vt(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await RN(n,e,a,pt,t.gitSelectionHooks?.outputChunkBytes),B.size>0||I&&ve.size>0){let x=await Dl(n,s,["ls-files","--modified","-z"],Lh),de=new Set;for(let ge of x.toString("utf8").split("\0")){let Ye=da(ge);Ye!==null&&de.add(Ye)}for(let ge of B){if(!de.has(ge))continue;let Ye=m.find(Ve=>Ve.path===ge);ue(ge,{path:ge,size:Ye?.size??null,type:"file",reason:"changed-during-read"})}for(let ge of ve){if(!de.has(ge))continue;let Ye=m.find(Ve=>Ve.path===ge);Ye&&delete Ye.gitObjectId}}for(let x of pt.omissions)P(x);pt.overflow&&F(pt.overflow)}m.sort((_,A)=>_.path.localeCompare(A.path,"en")),p.sort((_,A)=>_.path.localeCompare(A.path,"en"));let gP=pt===null?{provider:"physical-tree",...N?{physicalSelection:N}:{}}:{provider:"git",...pt.evidence?{gitSelection:pt.evidence}:{}},qm=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:gP,createdAt:(t.now??new Date).toISOString(),complete:y===0,limits:i,...r?{policy:r.manifest}:{},entries:m,omitted:p,omittedCount:y,...E>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${k}`,hash:k,count:E}}:{}}),fd=qm();for(;Wh(fd)>i.maxManifestBytes;){if(p.filter(A=>!Mh(A)).length>0){let A=Math.max(1,Math.ceil(p.length/4));for(let I=0;I<A;I+=1){let q=Ml(p);if(q===null)break;w(q)}}else if(m.length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let I of m.splice(-A))y+=1,$(I)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");fd=qm()}return fd}async function zh(e,t,i={}){let n=(await ye(e.projectRoot))?.native.snapshot??fh;return ql(e,{...i,policy:t.policy,incrementalBaseline:t,limits:{maxFiles:n.max_files,maxFileBytes:n.max_total_bytes,maxTotalBytes:n.max_total_bytes,maxDurationMs:n.max_duration_ms},deadlineMs:n.max_duration_ms})}async function Jh(e,t,i){let r=TN(e,t);await T(j(e,r),r),await ee(r,$i(i))}async function ha(e,t){let i=TN(e,t),r=j(e,i);await T(r,i);try{let n=await xl({root:r,file:i,maxBytes:YI,label:"Native baseline snapshot manifest"});return $i(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as r$}from"crypto";import n$ from"path";var Nt=Object.freeze({stateRef:"runtime/run-state.json",pendingRef:"runtime/pending-action.json",trajectoryRef:"runtime/trajectory.jsonl",contextRef:"runtime/context.md",artifactsRef:"runtime/artifacts.json",checkpointRef:"runtime/checkpoints/latest.json",snapshotsRef:"runtime/skill-snapshots"});import{createHash as Xj}from"node:crypto";import{constants as zl,promises as tt}from"node:fs";import bt from"node:path";import{TextDecoder as Qj}from"node:util";import Gj from"path";var qj=Tn(en(),1);var Qq=4*1024*1024;var Wj=null;function zj(e,t){let i=e;for(let r of t)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function IN(e,t){return(...i)=>{let r=Wj;if(r===null)return t(...i);let n=zj(`async:${e}`,i),a=r.entries.get(n);if(a)return a.value;let o=t(...i).catch(s=>{throw r.entries.delete(n),s});return r.entries.set(n,{value:o}),o}}var rW=IN("hookWritePolicy",async e=>(await sh(e))?.hook??{allow_paths:[]});var jN=(e,t)=>{let i=e[t];return i==null?null:String(i)};function Xo(e,t){let i=e[t];if(typeof i!="string"||i.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return i}function Yo(e,t){let i=Xo(e,t);if(Gj.isAbsolute(i)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(i)||i.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return i}function Uj(e){let t=e.run_retries??"{}",i;try{i=typeof t=="string"?JSON.parse(t):t}catch(r){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:r})}if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let r of Object.values(i))if(!Number.isInteger(r)||Number(r)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return i}function $N(e){if(!e.run_id)return null;let t=Xo(e,"run_id"),i=Xo(e,"skill"),r=Xo(e,"skill_version"),n=Xo(e,"skill_hash"),a=Yo(e,"pending_ref"),o=Yo(e,"trajectory_ref"),s=Yo(e,"context_ref"),c=Yo(e,"artifacts_ref"),l=Yo(e,"checkpoint_ref"),u=Number(e.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(e.orchestration!=="deterministic"&&e.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(e.run_status!=="running"&&e.run_status!=="waiting"&&e.run_status!=="completed"&&e.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:t,skill:i,skillVersion:r,skillHash:n,orchestration:e.orchestration,currentStep:jN(e,"current_step"),iteration:u,pending:jN(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:Uj(e)}}var ZW=256*1024;var Kj=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function Yj(e){let t={run_id:e.runId,skill:e.skill,skill_version:e.skillVersion,skill_hash:e.skillHash,orchestration:e.orchestration,current_step:e.currentStep,iteration:e.iteration,pending:e.pending,pending_ref:e.pendingRef,trajectory_ref:e.trajectoryRef,context_ref:e.contextRef,artifacts_ref:e.artifactsRef,checkpoint_ref:e.checkpointRef,run_status:e.status,run_retries:JSON.stringify(e.retries)},i=$N(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function Wl(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Run state: stored value must be an object");let t=e,i=Object.keys(t).find(r=>!Kj.has(r));if(i)throw new Error(`Invalid Run state: unknown field ${i}`);if(t.currentStep!==null&&(typeof t.currentStep!="string"||t.currentStep.length===0))throw new Error("Invalid Run state: currentStep must be a non-empty string or null");if(t.pending!==null&&(typeof t.pending!="string"||t.pending.length===0))throw new Error("Invalid Run state: pending must be a non-empty string or null");if(!t.retries||typeof t.retries!="object"||Array.isArray(t.retries))throw new Error("Invalid Run state: retries must be an object");return Yj(t)}var Je={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};function Zo(e,t){let i=bt.relative(e,t);return i===""||!bt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${bt.sep}`)}function HN(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Qo(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function Zj(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Pr(e,t,i){let r=Nt[t];if(i!==void 0&&i!==r)throw new Error(`Native Run ${t} ref must be ${r}`);let n=bt.resolve(e),a=bt.resolve(n,...r.slice(8).split("/"));if(!Zo(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function ON(e){let t=await tt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await tt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Gh(e,t){let i=bt.resolve(e),r=bt.resolve(t);if(!Zo(i,r))throw new Error("Native Run path is outside its change");let n=[await ON(i)],a=i;for(let o of bt.relative(i,r).split(bt.sep).filter(Boolean)){a=bt.join(a,o);let s;try{s=await ON(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!Zo(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function Jl(e){for(let t of e){let i=await tt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!Zj(t,i)||await tt.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function e$(e,t,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${i} exceeds ${t} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function fn(e,t,i,r,n){let a=await Gh(e,bt.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await tt.lstat(t)}catch(d){if(d.code==="ENOENT")return null;throw d}if(!o.isFile()||o.isSymbolicLink())throw new Error(`${r} must be a regular file`);if(o.size>i)throw new Error(`${r} exceeds ${i} bytes`);let s=HN(o),c=await tt.realpath(t);if(!Zo(a[0].realPath,c))throw new Error(`${r} resolves outside its change`);let l=process.platform==="win32"?zl.O_RDONLY:zl.O_RDONLY|zl.O_NOFOLLOW|zl.O_NONBLOCK,u;try{u=await tt.open(t,l)}catch(d){throw new Error(`${r} changed while opening`,{cause:d})}try{let[d,f,h]=await Promise.all([u.stat(),tt.lstat(t),tt.realpath(t)]);if(await Jl(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||h!==c||!Qo(s,d)||!Qo(s,f))throw new Error(`${r} changed while opening`);await n?.afterOpen?.();let v=await e$(u,i,r);await n?.beforeFinalCheck?.();let[m,p,b]=await Promise.all([u.stat(),tt.lstat(t),tt.realpath(t)]);if(await Jl(a),!p.isFile()||p.isSymbolicLink()||b!==c||!Qo(s,m)||!Qo(s,p))throw new Error(`${r} changed while reading`);let g;try{g=new Qj("utf-8",{fatal:!0}).decode(v)}catch(y){throw new Error(`${r} is not valid UTF-8`,{cause:y})}return{text:g,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}async function t$(e,t,i){let r=await Gh(e,bt.dirname(t));if(!r)return{exists:!1};let n;try{n=await tt.lstat(t)}catch(o){if(o.code==="ENOENT")return{exists:!1};throw o}if(!n.isFile()||n.isSymbolicLink())throw new Error(`${i} must be a regular file`);let a=await tt.realpath(t);if(!Zo(r[0].realPath,a))throw new Error(`${i} resolves outside its change`);return await Jl(r),{exists:!0,identity:HN(n),realPath:a}}async function i$(e,t,i,r){let n=await Gh(e,bt.dirname(t));if(!n){if(!i.exists)return;throw new Error(`${r} parent changed before commit`)}let a;try{a=await tt.lstat(t)}catch(o){if(o.code==="ENOENT"&&!i.exists)return;throw new Error(`${r} changed before commit`,{cause:o})}if(!i.exists||!a.isFile()||a.isSymbolicLink()||!Qo(i.identity,a)||await tt.realpath(t)!==i.realPath)throw new Error(`${r} changed before commit`);await Jl(n)}async function Gl(e){if(Buffer.byteLength(e.content,"utf8")>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);let i=e.expected??await t$(e.changeDir,e.file,e.label);if(i.exists&&i.identity.size>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);await he(e.file,e.content,{containedRoot:e.changeDir,beforeCommit:async()=>{await e.hooks?.beforeCommit?.(),await i$(e.changeDir,e.file,i,e.label)}});let r=await fn(e.changeDir,e.file,e.maxBytes,e.label);if(!r||r.text!==e.content)throw new Error(`${e.label} commit could not be verified`)}function DN(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function LN(e){return`${JSON.stringify(e,null,2)}
190
+ `}function Rr(e){return Wl(e)}async function Oe(e,t){let i=Pr(e,"stateRef"),r=await fn(e,i,Je.runStateBytes,"Native Run state",t);return r?Wl(DN(r.text,"Native Run state")):null}async function hn(e,t,i){let r=Wl(t);await Gl({changeDir:e,file:Pr(e,"stateRef"),content:LN(r),maxBytes:Je.runStateBytes,label:"Native Run state",hooks:i})}async function it(e,t,i){let r=Pr(e,"trajectoryRef",t),n=await fn(e,r,Je.trajectoryBytes,"Native Run trajectory",i);if(!n)return[];let a=n.text.split(/\r?\n/u).map((o,s)=>({line:o,number:s+1})).filter(({line:o})=>o.length>0);if(a.length>Je.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Je.trajectoryEvents} events`);return a.map(({line:o,number:s})=>{try{return JSON.parse(o)}catch(c){throw new Error(`Invalid Native Run trajectory event at line ${s}`,{cause:c})}})}async function MN(e,t,i){return(await fn(e,Pr(e,"trajectoryRef",t),Je.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function FN(e,t,i,r,n){if(!/^[a-f0-9]{64}$/u.test(r))throw new Error("Native Run trajectory expected hash is invalid");let a=Pr(e,"trajectoryRef",t),o=await fn(e,a,Je.trajectoryBytes,"Native Run trajectory");if(!o)throw new Error("Native Run trajectory disappeared before repair");if(Xj("sha256").update(o.text,"utf8").digest("hex")!==r)throw new Error("Native Run trajectory changed before repair");await Gl({changeDir:e,file:a,content:i,maxBytes:Je.trajectoryBytes,label:"Native Run trajectory",expected:o.target,hooks:n})}async function BN(e,t,i,r){let n=Pr(e,"trajectoryRef",t),a=`${JSON.stringify(i)}
191
+ `;if(Buffer.byteLength(a,"utf8")>Je.trajectoryEventBytes)throw new Error(`Native Run trajectory event exceeds ${Je.trajectoryEventBytes} bytes`);let o=await fn(e,n,Je.trajectoryBytes,"Native Run trajectory");if((o?o.text.split(/\r?\n/u).filter(c=>c.length>0).length:0)>=Je.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Je.trajectoryEvents} events`);await Gl({changeDir:e,file:n,content:`${o?.text??""}${a}`,maxBytes:Je.trajectoryBytes,label:"Native Run trajectory",expected:o?.target??{exists:!1},hooks:r})}async function pa(e,t,i){let r=await fn(e,Pr(e,"checkpointRef",t),Je.checkpointBytes,"Native Run checkpoint",i);return r?DN(r.text,"Native Run checkpoint"):null}async function VN(e,t,i,r){await Gl({changeDir:e,file:Pr(e,"checkpointRef",t),content:LN(i),maxBytes:Je.checkpointBytes,label:"Native Run checkpoint",hooks:r})}var a$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Ul=class extends Error{constructor(i){super(i.status==="repairable"?`Native trajectory has an incomplete final line at ${i.file}:${i.line}; run doctor --repair`:`Native trajectory is invalid at ${i.file}:${i.line}: ${i.message}`);this.inspection=i;this.name="NativeTrajectoryRepairRequiredError"}inspection;code="native-trajectory-tail-repair-required"};function Uh(e){return r$("sha256").update(e).digest("hex")}function o$(e,t){if(!a$.test(t))throw new Error(`Invalid Native change name: ${t}`);return n$.join(H(e,t),"trajectory.jsonl")}function s$(e){let t=e.split(/\n/u),i=0;for(let r=0;r<t.length;r+=1){let n=t[r].endsWith("\r")?t[r].slice(0,-1):t[r];if(n.length!==0){i=r+1;try{JSON.parse(n)}catch(a){return{status:"invalid",line:r+1,message:a.message}}}}return{status:"valid",count:i}}function c$(e,t){if(/Unexpected end|Unterminated string/iu.test(e.message))return!0;let i=/position (\d+)/iu.exec(e.message)?.[1];return i!==void 0&&Number(i)>=Math.max(0,t.length-1)}function l$(e,t){let i=t.lastIndexOf(10),r=t.subarray(0,i+1),n=s$(r.toString("utf8"));if(n.status==="invalid")return{status:"invalid",file:e,line:n.line,message:n.message};if(i===t.length-1)return{status:"clean",file:e};let a=t.subarray(i+1),o=a.toString("utf8"),s=n.count+1,c,l;try{JSON.parse(o.endsWith("\r")?o.slice(0,-1):o),c="missing-newline",l=Buffer.concat([t,Buffer.from(`
192
+ `)])}catch(d){if(!c$(d,o))return{status:"invalid",file:e,line:s,message:d.message};c="incomplete-json",l=r}return{inspection:{status:"repairable",file:e,reason:c,line:s,originalHash:Uh(t),targetHash:Uh(l),tailHash:Uh(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function qN(e,t){let i=o$(e,t);await T(j(e,i),i);let r=H(e,t),n=await MN(r,Nt.trajectoryRef);return n===null?{status:"clean",file:i}:l$(i,Buffer.from(n))}async function ma(e,t){let i=await qN(e,t);return"inspection"in i?i.inspection:i}async function Kl(e,t){let i=await ma(e,t);if(i.status!=="clean")throw new Ul(i)}async function WN(e,t,i){return se(e,`repair trajectory tail for ${t}`,async()=>{let r=await qN(e,t);if(!("inspection"in r)){if(r.status==="clean")return null;throw new Ul(r)}try{await FN(H(e,t),Nt.trajectoryRef,r.targetContent,r.inspection.originalHash,{beforeCommit:i?.beforeCommit})}catch(a){throw/changed (?:before|while)/iu.test(a.message)?new Error(`Native trajectory changed while preparing tail repair for ${t}; inspect it again before retrying`,{cause:a}):a}if((await ma(e,t)).status!=="clean")throw new Error(`Native trajectory tail repair did not produce a clean file for ${t}`);return r.inspection})}import{createHash as u$}from"node:crypto";import{promises as Yl}from"node:fs";import Oi from"node:path";var es=/^[a-f0-9]{64}$/u,zN=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,d$=16*1024,Yh=process.platform,f$=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function va(e){return f$.has(e)}function UN(e,t){let i=Oi.relative(e,t);return Oi.isAbsolute(i)||i===".."||i.startsWith(`..${Oi.sep}`)?null:i.replaceAll("\\","/")||"."}function KN(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function YN(e,t){if(e.length===0||KN(e)||e.includes("\\")||Oi.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let i=Oi.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function Xh(e,t){return u$("sha256").update(`${e}
193
+ ${t}`).digest("hex")}async function JN(e,t){let i=await Yl.realpath(t),r=await Yl.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Yh==="win32"?Oi.normalize(i).toLowerCase():i;return Xh(e,`${n}
194
194
  ${r.dev}
195
195
  ${r.ino}
196
- ${r.birthtimeMs}`)}async function JN(e,t){let i=await zl.realpath(t),r=await zl.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Uh==="win32"?ji.normalize(i).toLowerCase():i;return Kh(e,n)}function s$(e){if(typeof e!="string")throw new Error("Native workspace capturedAt is invalid");let t=new Date(e);if(!Number.isFinite(t.getTime())||t.toISOString()!==e)throw new Error("Native workspace capturedAt is invalid");return e}function Gh(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||UN(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function YN(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Gh(e.changeBranch,"Native workspace change branch"),Gh(e.targetBranch,"Native workspace target branch"),(e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null))throw new Error("Native isolated workspace requires change and target branches")}function c$(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,i=new Set(["provider","baseCommit","targetBranch","targetCommit"]),r=Object.keys(t).filter(n=>!i.has(n));if(r.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${r.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!WN.test(t.baseCommit)||typeof t.targetCommit!="string"||!WN.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");Gh(t.targetBranch,"Native workspace Git target branch")}function Xo(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,i=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),r=Object.keys(t).filter(o=>!i.has(o));if(r.length>0)throw new Error(`Native workspace identity has unknown field(s): ${r.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!Yo.test(String(t.projectRootId))||!Yo.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");s$(t.capturedAt),KN(t.nativeRootRef,"Native workspace root ref");let n=t.projectRootPathId!==void 0,a=t.nativeRootPathId!==void 0;if(n!==a)throw new Error("Native workspace path identities must be provided together");if(n&&!Yo.test(String(t.projectRootPathId))||a&&!Yo.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Yo.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&c$(t.git),t.schema==="comet.native.workspace.v2"){if(t.isolation!==void 0||t.changeBranch!==void 0||t.targetBranch!==void 0||t.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof t.isolation!="string"||t.changeBranch===void 0||t.targetBranch===void 0||t.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(YN(t),t.finish!==null&&!new Set(["merge","push","pull-request","keep"]).has(t.finish))throw new Error("Native workspace finish must be merge, push, pull-request, keep, or null")}function da(e,t){return ji.join(H(e,t),"workspace.json")}function l$(e,t){let i=da(e,t),r=j(e,i),n=GN(r,i);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:r,ref:KN(n,"Native workspace file ref")}}async function XN(e,t){try{let i=l$(e,t),r=await Z({root:i.root,ref:i.ref,maxBytes:a$});return JSON.parse(r.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function QN(e,t){let i=fe(e.projectRoot),r={projectRoot:ji.resolve(e.projectRoot),currentBranch:i.currentBranch,isSecondaryWorktree:i.isSecondaryWorktree};try{let n=await kt(e,t);if(n===null)return{...r,bindingState:"missing",isolation:null,changeBranch:null,targetBranch:null,finish:null};if(n.schema!=="comet.native.workspace.v3")return{...r,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:n.git?.targetBranch??null,finish:null};let a=await fa({paths:e,identity:n});return{...r,bindingState:a.state==="aligned"?"aligned":"drifted",isolation:n.isolation,changeBranch:n.changeBranch,targetBranch:n.targetBranch,finish:n.finish}}catch{return{...r,bindingState:"invalid",isolation:null,changeBranch:null,targetBranch:null,finish:null}}}async function Yh(e,t){let i=await XN(e,t);if(i===null)return!1;if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Native workspace identity must be an object");return i.schema==="comet.native.workspace.v1"?!0:(Xo(i),i.schema==="comet.native.workspace.v3"?!1:i.projectRootPathId===void 0||i.nativeRootPathId===void 0)}async function ZN(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=GN(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let i=fe(e.paths.projectRoot),r=i.isGitWorktree?xi(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??i.currentBranch,a=n==null?null:xi(e.paths.projectRoot,n),o=r!==null&&n!==null&&n!==void 0&&a!==null?{provider:"git",baseCommit:r,targetBranch:n,targetCommit:a}:void 0,[s,c,l,u]=await Promise.all([zN("comet.native.workspace-project-root.v2",e.paths.projectRoot),zN("comet.native.workspace-native-root.v2",e.paths.nativeRoot),JN("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),JN("comet.native.workspace-native-root-path.v2",e.paths.nativeRoot)]),d=(e.now??new Date).toISOString();if(e.finish&&!e.binding)throw new Error("Native workspace finish requires a workspace binding");e.binding&&YN(e.binding);let f={capturedAt:d,capturedRevision:e.revision,nativeRootRef:t,projectRootId:s,nativeRootId:c,projectRootPathId:l,nativeRootPathId:u,...o?{git:o}:{},...e.sessionId?{sessionHash:Kh("comet.native.workspace-session.v2",`${s}
196
+ ${r.birthtimeMs}`)}async function GN(e,t){let i=await Yl.realpath(t),r=await Yl.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Yh==="win32"?Oi.normalize(i).toLowerCase():i;return Xh(e,n)}function h$(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 Kh(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||KN(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function XN(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Kh(e.changeBranch,"Native workspace change branch"),Kh(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 p$(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,i=new Set(["provider","baseCommit","targetBranch","targetCommit"]),r=Object.keys(t).filter(n=>!i.has(n));if(r.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${r.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!zN.test(t.baseCommit)||typeof t.targetCommit!="string"||!zN.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");Kh(t.targetBranch,"Native workspace Git target branch")}function ts(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,i=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),r=Object.keys(t).filter(o=>!i.has(o));if(r.length>0)throw new Error(`Native workspace identity has unknown field(s): ${r.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!es.test(String(t.projectRootId))||!es.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");h$(t.capturedAt),YN(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&&!es.test(String(t.projectRootPathId))||a&&!es.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!es.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&p$(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(XN(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 ga(e,t){return Oi.join(H(e,t),"workspace.json")}function m$(e,t){let i=ga(e,t),r=j(e,i),n=UN(r,i);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:r,ref:YN(n,"Native workspace file ref")}}async function QN(e,t){try{let i=m$(e,t),r=await Z({root:i.root,ref:i.ref,maxBytes:d$});return JSON.parse(r.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function ZN(e,t){let i=fe(e.projectRoot),r={projectRoot:Oi.resolve(e.projectRoot),currentBranch:i.currentBranch,isSecondaryWorktree:i.isSecondaryWorktree};try{let n=await kt(e,t);if(n===null)return{...r,bindingState:"missing",isolation:null,changeBranch:null,targetBranch:null,finish:null};if(n.schema!=="comet.native.workspace.v3")return{...r,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:n.git?.targetBranch??null,finish:null};let a=await wa({paths:e,identity:n});return{...r,bindingState:a.state==="aligned"?"aligned":"drifted",isolation:n.isolation,changeBranch:n.changeBranch,targetBranch:n.targetBranch,finish:n.finish}}catch{return{...r,bindingState:"invalid",isolation:null,changeBranch:null,targetBranch:null,finish:null}}}async function Qh(e,t){let i=await QN(e,t);if(i===null)return!1;if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Native workspace identity must be an object");return i.schema==="comet.native.workspace.v1"?!0:(ts(i),i.schema==="comet.native.workspace.v3"?!1:i.projectRootPathId===void 0||i.nativeRootPathId===void 0)}async function eb(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=UN(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let i=fe(e.paths.projectRoot),r=i.isGitWorktree?Ai(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??i.currentBranch,a=n==null?null:Ai(e.paths.projectRoot,n),o=r!==null&&n!==null&&n!==void 0&&a!==null?{provider:"git",baseCommit:r,targetBranch:n,targetCommit:a}:void 0,[s,c,l,u]=await Promise.all([JN("comet.native.workspace-project-root.v2",e.paths.projectRoot),JN("comet.native.workspace-native-root.v2",e.paths.nativeRoot),GN("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),GN("comet.native.workspace-native-root-path.v2",e.paths.nativeRoot)]),d=(e.now??new Date).toISOString();if(e.finish&&!e.binding)throw new Error("Native workspace finish requires a workspace binding");e.binding&&XN(e.binding);let f={capturedAt:d,capturedRevision:e.revision,nativeRootRef:t,projectRootId:s,nativeRootId:c,projectRootPathId:l,nativeRootPathId:u,...o?{git:o}:{},...e.sessionId?{sessionHash:Xh("comet.native.workspace-session.v2",`${s}
197
197
  ${c}
198
- ${e.sessionId}`)}:{}},h=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return Xo(h),h}async function Jl(e){let t=await ZN(e),i=da(e.paths,e.name),r=j(e.paths,i);return await T(r,i),await ee(i,t,{containedRoot:r}),t}async function kt(e,t){let i=await XN(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(Xo(i),i)}async function eb(e){return await Yh(e.paths,e.name)?Jl(e):null}async function Qo(e){Xo(e.identity);let t=await ZN({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),i=[],r=[];return t.nativeRootRef!==e.identity.nativeRootRef&&i.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&i.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&i.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&i.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&i.push("native-root-legacy-identity")),Uh==="win32"&&i.length>0&&i.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?r.push("workspace-inspection-unavailable"):i.length>0&&r.push("workspace-root-changed"),{state:r.length===0?"aligned":r.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:r,driftComponents:i}}async function fa(e){if(Xo(e.identity),e.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await Qo(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=fe(e.paths.projectRoot);return e.identity.changeBranch===null?i.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:i.isGitWorktree?i.currentBranch!==e.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${e.identity.changeBranch}, but the current branch is ${i.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!i.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function tb(e,t){let i=await kt(e,t);if(i===null)return null;let r=await fa({paths:e,identity:i});if(r.state==="drifted")throw new Error(`${r.code}: ${r.message}`);return i}var rb=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],u$=new Set(rb),nb=new Set([...rb,"minimum_runtime_version","revision"]),d$=new Set([...nb,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),f$=new Set(["capability","operation","source","base_hash"]),h$=new Set(["shape","build","verify","archive"]),p$=new Set(["implicit","confirmed"]),m$=new Set(["pending","pass","fail"]),Te="comet-state.yaml",Qh=/^[a-f0-9]{64}$/u,ab=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,v$=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Zo=class extends Error{constructor(i,r){super(`Native change ${i} uses ${r}; run comet native doctor ${i} --repair before mutating it`);this.change=i;this.schema=r;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},fn=class extends Error{constructor(i,r){super(i!==Ne||r===null?`Unsupported Native change schema ${i} for runtime protocol ${3}`:`Native change ${i} requires runtime protocol ${r}; current protocol is ${3}`);this.schema=i;this.minimumRuntimeVersion=r;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},es=class extends Error{constructor(i,r,n){super(`Native change ${i} revision conflict: expected ${r}, actual ${n}`);this.change=i;this.expectedRevision=r;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},ts=class extends Error{constructor(i,r){super(`Native working directory already contains active change${r.length===1?"":"s"} ${r.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=i;this.activeChanges=r;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},ha=class extends Error{constructor(i,r,n,a,o,s=null,c=null){super(`Native change ${i} baseline is incomplete (${r} omitted entr${r===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=i;this.omittedCount=r;this.omittedByReason=n;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},M2=Us("en");function rs(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function ob(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Ul(e){if(!ab.test(e))throw new Error(`Invalid Native change name: ${e}`)}function g$(e){if(!ab.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function sb(e,t){if(e.length===0||mi.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function w$(e,t){let i=rs(e,`spec_changes[${t}]`);if(ob(i,f$,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(g$(i.capability),i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`Invalid spec operation for ${i.capability}`);let r=i.source,n=i.base_hash;if(r!==void 0&&typeof r!="string")throw new Error(`Spec source for ${i.capability} must be a string`);if(typeof r=="string"&&sb(r,`Spec source for ${i.capability}`),i.operation==="create"){if(!r)throw new Error(`Create spec ${i.capability} requires source`);if(n!==null)throw new Error(`Create spec ${i.capability} requires null base_hash`)}else if(i.operation==="replace"){if(!r)throw new Error(`Replace spec ${i.capability} requires source`);if(typeof n!="string"||!Qh.test(n))throw new Error(`Replace spec ${i.capability} requires a SHA-256 base_hash`)}else{if(r!==void 0)throw new Error(`Remove spec ${i.capability} forbids source`);if(typeof n!="string"||!Qh.test(n))throw new Error(`Remove spec ${i.capability} requires a SHA-256 base_hash`)}return{capability:i.capability,operation:i.operation,...typeof r=="string"?{source:r}:{},base_hash:n}}function y$(e){return/^\d{4}-\d{2}-\d{2}$/u.test(e)?new Date(`${e}T00:00:00.000Z`).toISOString().slice(0,10)===e:!1}function Zh(e,t){if(ob(e,t,Te),typeof e.name!="string")throw new Error("Native change name is required");if(Ul(e.name),e.language!=="en"&&e.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof e.phase!="string"||!h$.has(e.phase))throw new Error("Native change phase is invalid");if(e.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(e.approval!==null&&!p$.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let i=e.spec_changes.map(w$),r=i.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(r.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(r)].join(", ")}`);if(typeof e.verification_result!="string"||!m$.has(e.verification_result))throw new Error("Native verification_result is invalid");if(e.verification_report!==null&&typeof e.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof e.verification_report=="string"&&sb(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!y$(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:i,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function on(e){let t=rs(e,Te);if(t.schema!==et)throw new Error(`Expected ${et}`);return{schema:et,...Zh(t,u$)}}function is(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Xh(e,t,i){if(e===null)return null;let r=typeof e=="string"?v$.exec(e):null;if(!r||r[1]!==i)throw new Error(`${t} must be null or runtime/evidence/${i}/<sha256>.json relative to the Native change`);return e}function N$(e){if(e==null)return null;if(typeof e!="string"||!Qh.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function b$(e){if(e===void 0)return"legacy-v1";if(e!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return e}function di(e){let t=rs(e,Te);if(t.schema!==be)throw new Error(`Expected ${be}`);if(is(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${be} minimum_runtime_version must be 2`);return{schema:be,minimum_runtime_version:2,revision:is(t.revision,"Native v2 revision"),...Zh(t,nb)}}function lt(e){let t=rs(e,Te);if(t.schema!==Ne){if(t.schema===et||t.schema===be){let o=t.schema===et?on(t):di(t);throw new Zo(o.name,o.schema)}throw new fn(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=is(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new fn(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let r=is(t.revision,"Native revision"),n=Zh(t,d$),a=N$(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Ne,minimum_runtime_version:3,revision:r,verification_protocol:b$(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Xh(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Xh(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Xh(t.partial_allowance,"Native partial_allowance","allowances")}}function cb(e){let t=rs(e,Te);if(t.schema===et){let n=on(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Ne}`}}if(t.schema===be){let n=di(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Ne}`}}if(t.schema!==Ne){let n=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new fn(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let i=is(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new fn(t.schema,i).message};let r=lt(t);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function dn(e){let t=lt(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,verification_protocol:t.verification_protocol,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,approved_contract_hash:t.approved_contract_hash??null,spec_changes:t.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,implementation_scope:t.implementation_scope,verification_evidence:t.verification_evidence,partial_allowance:t.partial_allowance,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function Kl(e){let t=di(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,spec_changes:t.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function ne(e,t){Ul(t);let i=mi.join(e.changesDir,t);if(!O(e.changesDir,i))throw new Error("Native change path escaped");return i}async function pa(e,t){let i=H(e,t),r=mi.join(i,"schema-migration.json");await T(O(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await ib.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function ma(e,t){let i=H(e,t),r=mi.join(i,"checkpoint-journal.json");await T(O(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await ib.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Yl(e,t=mi.dirname(e)){let i=mi.relative(t,e).split(mi.sep).join("/"),r=await Z({root:t,ref:i,maxBytes:null,includeHash:!1}),n=(0,Gl.parseDocument)(r.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function vi(e,t){let i=mi.join(ne(e,t),Te);await T(e.nativeRoot,i);let r=cb(await Yl(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await pa(e,t)?{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimumRuntimeVersion,state:r.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(r.status==="current"&&r.state&&await k$(e,r.state),r)}async function Xl(e,t){let i=mi.join(ne(e,t),Te);await T(e.nativeRoot,i);let r=cb(await Yl(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return r}async function k$(e,t){if(await sa(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function He(e,t){let i=await vi(e,t);if(i.status==="migration-required")throw new Zo(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new fn(i.schema,i.minimumRuntimeVersion);return await tb(e,t),i.state}async function lb(e,t,i){let r={...t,schema:Ne,minimum_runtime_version:3,revision:i+1},n=await cN({expectedRevision:i,next:r,read:async()=>{let a=lt(await Yl(e));if(a.name!==t.name)throw new Error(`Native change file/name mismatch: ${t.name}`);return a},write:a=>he(e,(0,Gl.stringify)(dn(a))),equals:(a,o)=>JSON.stringify(dn(a))===JSON.stringify(dn(o)),conflict:a=>new es(t.name,i,a)});return Object.assign(t,n),n}async function Ql(e,t,i,r){if(await Wn(e.projectRoot),await pa(e,t.name))throw new Zo(t.name,t.schema);if(!r?.allowPendingCheckpointRecovery&&await ma(e,t.name))throw new Error(`Native progress checkpoint recovery is required for ${t.name} before another state write`);if((await He(e,t.name)).verification_protocol!==t.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await Wl(e,t.name);let a=mi.join(ne(e,t.name),Te);return await T(e.nativeRoot,a),lb(a,t,i)}async function ub(e,t){return lb(e,t,t.revision)}async function db(e){return lt(await Yl(e))}var hb=["outcome","scope","nonGoals","acceptanceExamples"],S$=[...hb,"constraints","decisions","openQuestions","verificationExpectations"],E$=["acceptanceEvidence","commandsAndResults","skippedChecks","specConsistency","knownLimitationsAndRisks","conclusion"],pb={maxFileBytes:So};function mb(e){let t=new Map,i=null,r=[],n=()=>{i!==null&&t.set(i,r.join(`
199
- `).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(n(),i=o[1].trim(),r=[]):i!==null&&r.push(a)}return n(),t}async function P$(e,t){let i=fb.resolve(e,...t.split(/[\\/]/u));if(!O(e,i))throw new Error(`Artifact escapes Native change: ${t}`);let r=await ep.realpath(e),n=await ep.realpath(i);if(!O(r,n))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await ep.stat(n)).isFile())throw new Error(`Artifact is not a file: ${t}`);return n}function ns(e){return{valid:e.length===0,findings:e}}async function tp(e,t){let i=[],r;try{r=(await Z({root:e,ref:t,maxBytes:pb.maxFileBytes})).text}catch(o){return ns([{code:"brief-missing",message:o.message,path:t}])}let n=new Map;for(let[o,s]of mb(r))n.set(Gs(o)??o,s);for(let o of S$)n.has(o)||i.push({code:"brief-section-missing",message:`Missing brief section: ${o}`,path:t});for(let o of hb)(n.get(o)??"").length===0&&i.push({code:"brief-section-empty",message:`Brief section is empty: ${o}`,path:t});let a=n.get("openQuestions")??"";return/^\s*-\s*\[blocking\]/imu.test(a)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),ns(i)}async function ip(e,t){let i=[],r;try{r=(await Z({root:e,ref:t,maxBytes:pb.maxFileBytes})).text}catch(a){return ns([{code:"verification-missing",message:a.message,path:t}])}let n=new Map;for(let[a,o]of mb(r))n.set(Zm(a)??a,o);for(let a of E$)n.has(a)?(n.get(a)??"").length===0&&i.push({code:"verification-section-empty",message:`Verification section is empty: ${a}`,path:t}):i.push({code:"verification-section-missing",message:`Missing verification section: ${a}`,path:t});return ns(i)}function Zl(e,t){return fb.join(e.specsDir,t,"spec.md")}async function vb(e,t){let i=[],r=ne(e,t.name);for(let n of t.spec_changes){let a=Zl(e,n.capability),o=null;try{await T(e.nativeRoot,a),o=await Zt(a)}catch(s){if(s.code!=="ENOENT"){i.push({code:"spec-canonical-unsafe",message:s.message,path:a});continue}}if(n.operation==="create"&&o!==null&&i.push({code:"spec-create-exists",message:`Canonical spec already exists: ${n.capability}`,path:a}),n.operation!=="create"&&o===null&&i.push({code:"spec-base-missing",message:`Canonical spec is missing: ${n.capability}`,path:a}),n.operation!=="create"&&o!==null&&o!==n.base_hash&&i.push({code:"spec-base-conflict",message:`Canonical spec changed for ${n.capability}: expected ${n.base_hash}, actual ${o}`,path:a}),n.source)try{await P$(r,n.source)}catch(s){i.push({code:"spec-source-invalid",message:s.message,path:n.source})}}return ns(i)}import{promises as TH}from"node:fs";import Zk from"node:path";import gb from"node:path";var R$="comet.native.archive-preflight.v1",C$="comet.native.archive-preflight.v1",x$="comet.native.archive-operation.v1",A$=/^[a-f0-9]{64}$/u,wb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,_$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function eu(e,t){return e<t?-1:e>t?1:0}function T$(e,t){if(typeof e!="string"||!A$.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function $i(e,t){return e===null?null:T$(e,t)}function I$(e,t){let i=gb.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||gb.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized Native-relative ref`);return e}function j$(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function $$(e){if(e==null)return null;if(e.schema!=="comet.native.workspace.v3")throw new Error("Native archive workspace schema is invalid");if(e.isolation!=="current"&&e.isolation!=="branch"&&e.isolation!=="worktree")throw new Error("Native archive workspace isolation is invalid");for(let[t,i]of[["change",e.changeBranch],["target",e.targetBranch]])if(i!==null&&(i.length===0||i.trim()!==i||Array.from(i).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})))throw new Error(`Native archive workspace ${t} branch is invalid`);if(e.finish!==null&&e.finish!=="merge"&&e.finish!=="push"&&e.finish!=="pull-request"&&e.finish!=="keep")throw new Error("Native archive workspace finish is invalid");if((e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null||e.finish===null))throw new Error("Native isolated archive workspace requires branches and a finish action");if(e.isolation==="current"&&e.finish!==null)throw new Error("Native current archive workspace cannot have a finish action");return{...e}}function O$(e,t){if(!wb.test(e.capability))throw new Error(`Native archive spec ${t} capability is invalid`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Native archive spec ${e.capability} operation is invalid`);let i=$i(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),r=$i(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=$i(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&i!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&i===null)throw new Error(`Native archive ${e.operation} ${e.capability} requires a base hash`);if(e.operation==="remove"!=(n===null))throw new Error(`Native archive ${e.operation} ${e.capability} proposed hash is invalid`);return{capability:e.capability,operation:e.operation,expectedBaseHash:i,actualBaseHash:r,proposedHash:n}}function H$(e){if(e.result!=="pending"&&e.result!=="pass"&&e.result!=="fail")throw new Error("Native archive verification result is invalid");if(!["missing","invalid","stale","complete","partial"].includes(e.freshness))throw new Error("Native archive verification freshness is invalid");if(!Number.isSafeInteger(e.skippedAcceptanceCount)||e.skippedAcceptanceCount<0)throw new Error("Native archive skipped acceptance count is invalid");let t={result:e.result,freshness:e.freshness,contractHash:$i(e.contractHash,"Native archive contract hash"),acceptanceHash:$i(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:$i(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:$i(e.reportHash,"Native archive report hash"),envelopeHash:$i(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:$i(e.partialAllowanceHash,"Native archive partial allowance hash"),skippedAcceptanceCount:e.skippedAcceptanceCount};if((e.freshness==="complete"||e.freshness==="partial")&&[t.contractHash,t.acceptanceHash,t.implementationScopeHash,t.reportHash,t.envelopeHash].some(i=>i===null))throw new Error("Fresh Native archive evidence requires every bound content hash");if(e.freshness==="partial"&&t.partialAllowanceHash===null||e.freshness==="complete"&&t.partialAllowanceHash!==null)throw new Error("Native archive partial evidence allowance state is invalid");return t}function D$(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(r=>{if(typeof r!="string"||!_$.test(r))throw new Error(`Native archive preflight finding code is invalid: ${String(r)}`);return r}),i=[...new Set(t)].sort(eu);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function L$(e){let t=[];e.phase!=="archive"&&t.push("archive-phase-required"),e.archived&&t.push("change-already-archived"),e.pendingJournal&&t.push("pending-journal"),e.targetExists&&t.push("archive-target-exists"),e.evidence.result!=="pass"&&t.push("verification-not-passed"),e.evidence.freshness==="missing"&&t.push("verification-evidence-missing"),e.evidence.freshness==="invalid"&&t.push("verification-evidence-invalid"),e.evidence.freshness==="stale"&&t.push("verification-evidence-stale"),e.evidence.skippedAcceptanceCount>0&&t.push("verification-acceptance-skipped");for(let i of e.specs)i.actualBaseHash!==i.expectedBaseHash&&t.push("spec-base-conflict");return[...new Set(t)].sort(eu)}function yb(e){if(!wb.test(e.change))throw new Error("Native archive change name is invalid");if(typeof e.stateSchema!="string"||e.stateSchema.length===0)throw new Error("Native archive state schema is invalid");if(!Array.isArray(e.specs)||e.specs.length>64)throw new Error("Native archive preflight exceeds its spec budget");let t=e.specs.map(O$).sort((l,u)=>eu(l.capability,u.capability));if(new Set(t.map(l=>l.capability)).size!==t.length)throw new Error("Native archive preflight contains duplicate capabilities");let i=t.map(l=>({...l,operationHash:D(x$,l)})),r=H$(e.evidence),n=$$(e.workspace),a=[...new Set([...D$(e.findingCodes??[]),...L$({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:r})])].sort(eu),o=j$(e.revision),s=I$(e.targetRef,"Native archive target");if(e.archiveConfirmation!=="automatic"&&e.archiveConfirmation!=="required")throw new Error("Native archive confirmation must be automatic or required");let c={stateSchema:e.stateSchema,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetRef:s,targetExists:e.targetExists,operations:i,evidence:r,workspace:n,findingCodes:a};return{schema:R$,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:r.freshness,operationCount:i.length,operations:i,workspace:n,findingCodes:a,preflightHash:D(C$,c)}}import{createHash as M$}from"node:crypto";import Nb from"node:path";var F$="comet.native.conflict-radar.v1",ut=Object.freeze({maxChanges:32,maxSpecsPerChange:64,maxArtifactsPerChange:128,maxTotalSpecs:512,maxTotalArtifacts:1024,maxSignalsPerRelationship:8,maxRelationships:256,maxSerializedBytes:64*1024,maxNameBytes:128,maxCapabilityBytes:128,maxArtifactPathBytes:512}),B$="comet.native.conflict-radar.v1",V$="comet.native.conflict-radar-signals.v1",q$=/^[a-f0-9]{64}$/u,Sb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,W$=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),z$=new Set(["capability","operation","baseHash"]),J$=new Set(["path","kind"]);function va(e,t){return e<t?-1:e>t?1:0}function rp(e){return Buffer.byteLength(e,"utf8")}function np(e,t,i){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${i} must be an object`);let r=e,n=Object.keys(r).filter(a=>!t.has(a));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);return r}function ap(e,t,i){if(typeof e!="string"||e.length===0||e!==e.trim())throw new Error(`${t} must be a non-empty trimmed string`);if(rp(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function G$(e,t){let i=ap(e,t,ut.maxArtifactPathBytes),r=Nb.posix.normalize(i);if(i.includes("\\")||Array.from(i).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(i)||Nb.posix.isAbsolute(r)||i.split("/").includes("..")||r!==i||r==="."||i.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return i}function Eb(e,t){if(typeof e!="string"||!q$.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function U$(e,t){let i=np(e,z$,t),r=ap(i.capability,`${t} capability`,ut.maxCapabilityBytes);if(!Sb.test(r))throw new Error(`${t} capability is invalid`);if(i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`${t} operation is invalid`);let n=i.baseHash===null?null:Eb(i.baseHash,`${t} canonical base hash`);if(i.operation==="create"&&n!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(i.operation!=="create"&&n===null)throw new Error(`${t} ${i.operation} operation requires a canonical base hash`);return{capability:r,operation:i.operation,baseHash:n}}function K$(e,t){let i=np(e,J$,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:G$(i.path,`${t} path`),kind:i.kind}}function Y$(e,t){let i=np(e,W$,`Conflict radar change ${t}`),r=ap(i.name,`Conflict radar change ${t} name`,ut.maxNameBytes);if(!Sb.test(r))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(i.revision)||i.revision<1)throw new Error(`Conflict radar change ${r} revision must be a positive safe integer`);if(!Array.isArray(i.specs))throw new Error(`Conflict radar change ${r} specs must be an array`);if(i.specs.length>ut.maxSpecsPerChange)throw new Error(`Conflict radar change ${r} exceeds the spec budget`);if(!Array.isArray(i.declaredArtifacts))throw new Error(`Conflict radar change ${r} declared artifacts must be an array`);if(i.declaredArtifacts.length>ut.maxArtifactsPerChange)throw new Error(`Conflict radar change ${r} exceeds the declared artifact budget`);let n=i.specs.map((c,l)=>U$(c,`Conflict radar change ${r} spec ${l}`)).sort((c,l)=>va(c.capability,l.capability));if(new Set(n.map(c=>c.capability)).size!==n.length)throw new Error(`Conflict radar change ${r} has duplicate capabilities`);let a=i.declaredArtifacts.map((c,l)=>K$(c,`Conflict radar change ${r} artifact ${l}`)).sort((c,l)=>va(c.path,l.path)||va(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${r} has duplicate or conflicting artifact paths`);let s=i.workspaceIdentityHash===void 0||i.workspaceIdentityHash===null?null:Eb(i.workspaceIdentityHash,`Conflict radar change ${r} workspace identity hash`);return{name:r,revision:i.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function X$(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>ut.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(Y$).sort((n,a)=>va(n.name,a.name));if(new Set(t.map(n=>n.name)).size!==t.length)throw new Error("Native conflict radar contains duplicate change names");if(t.reduce((n,a)=>n+a.specs.length,0)>ut.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>ut.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function Q$(e,t){let i=e.baseHash!==null&&e.baseHash===t.baseHash;return{kind:"capability",certainty:e.operation==="create"||t.operation==="create"||i?"definite-conflict":"possible-overlap",capability:e.capability,leftOperation:e.operation,rightOperation:t.operation,leftBaseHash:e.baseHash,rightBaseHash:t.baseHash}}function Z$(e,t){let i=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),r=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),n=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!i&&!r&&!n?null:{kind:"artifact",certainty:n?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function eO(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function tO(e,t){let i=[],r=M$("sha256").update(`${V$}
200
- [`),n=0,a=!1,o=l=>{n>0&&r.update(","),r.update(Oo(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),i.length<ut.maxSignalsPerRelationship&&i.push(l)},s=new Map(t.specs.map(l=>[l.capability,l]));for(let l of e.specs){let u=s.get(l.capability);u&&o(Q$(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=Z$(l,u);d&&o(d)}let c=a?"definite-conflict":n>0?"possible-overlap":"disjoint";return r.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:eO(e,t),signalCount:n,signalHash:r.digest("hex"),signals:i,signalsTruncated:i.length!==n}}function bb(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function iO(e,t){return bb(e.classification)-bb(t.classification)||va(e.left,t.left)||va(e.right,t.right)}function kb(e,t,i,r){let n={definiteConflict:t.filter(({classification:a})=>a==="definite-conflict").length,possibleOverlap:t.filter(({classification:a})=>a==="possible-overlap").length,disjoint:t.filter(({classification:a})=>a==="disjoint").length};return{schema:F$,workspaceIdentityAdvisoryOnly:!0,changeCount:e.length,relationshipCount:t.length,counts:n,relationships:i,relationshipsTruncated:i.length!==t.length,omittedRelationshipCount:t.length-i.length,radarHash:r}}function Pb(e){let t=X$(e),i=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)i.push(tO(t[s],t[c]));i.sort(iO);let r=i.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=D(B$,{changes:t,relationships:r}),a=i.slice(0,ut.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=kb(t,i,a,n);for(;a.length>0&&rp(JSON.stringify(o))>ut.maxSerializedBytes;)a=a.slice(0,-1),o=kb(t,i,a,n);if(rp(JSON.stringify(o))>ut.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as h0}from"node:crypto";import{promises as ri}from"node:fs";import yi from"node:path";import{createHash as jb}from"node:crypto";import Rb from"path";var op="comet.native.implementation-scope.v2",$b="comet.native.content-snapshot-projection.v1",as="comet.native.content-snapshot-projection.v1",Ob="comet.native.implementation-scope.v2",rO="comet.native.unresolved-scope-id.v1",nO="comet.native.scope-detail-overflow.v1",aO="comet.native.snapshot-projection-overflow.v2",up=/^[a-f0-9]{64}$/u,pn=1024*1024,oO=128,sO=128;function Ge(e,t){return e<t?-1:e>t?1:0}function sp(e){if(!up.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function cO(e,t){return e===t?0:e===null?-1:t===null?1:Ge(e,t)}function Rr(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a normalized project-relative path`);let i=Rb.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||Rb.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function Hb(e,t){return e==="."?e:Rr(e,t)}function ga(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function lO(e,t){if(e.type!=="file")throw new Error(`${t} must describe a file`);if(typeof e.hash!="string"||e.hash.length===0)throw new Error(`${t} hash must be non-empty`);return{path:Rr(e.path,`${t} path`),hash:e.hash,size:ga(e.size,`${t} size`),type:"file"}}function uO(e,t){return{path:Hb(e.path,`${t} path`),size:e.size===null?null:ga(e.size,`${t} size`),type:e.type,reason:e.reason}}function dO(e,t){return Ge(e.path,t.path)||Ge(e.hash,t.hash)||e.size-t.size}function fO(e,t){return Ge(e.path,t.path)||Ge(e.reason,t.reason)||Ge(e.type,t.type)||(e.size??-1)-(t.size??-1)}function ss(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
201
- `,"utf8")}function Pr(e,t,i){let r=`${t}
202
- ${Oo(i)}`;e.update(`${Buffer.byteLength(r,"utf8")}:`),e.update(r)}function hO(e){if(ss(e)<=pn)return e;let t=[...e.entries],i=[...e.omitted],r=e.omittedCount,n=e.omissionOverflow?.count??0,a=jb("sha256");a.update(`${aO}
203
- `),e.omissionOverflow&&Pr(a,"existing-overflow",e.omissionOverflow);let o=(f,h)=>{h||(r+=1),n+=1,Pr(a,"omission",f)},s=f=>{r+=1,n+=1,Pr(a,"entry",f)},c=()=>{for(let f=i.length-1;f>=0;f-=1){let h=i[f];if(!(h.reason==="git-enumeration-limit"||h.reason==="git-selection-changed"||h.reason==="physical-enumeration-limit"||h.reason==="physical-selection-changed"))return i.splice(f,1),h}return null},l=()=>({...e,complete:r===0,entries:t,omitted:i,omittedCount:r,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:n}}),u=l();for(;ss(u)>pn;){if(i.filter(h=>h.reason!=="git-enumeration-limit"&&h.reason!=="git-selection-changed"&&h.reason!=="physical-enumeration-limit"&&h.reason!=="physical-selection-changed").length>0){let h=Math.max(1,Math.ceil(i.length/4));for(let v=0;v<h;v+=1){let m=c();if(m===null)break;o(m,!0)}}else if(t.length>0){let h=Math.max(1,Math.ceil(t.length/4));for(let v of t.splice(-h))s(v)}else throw new Error("Native snapshot projection metadata exceeds its evidence byte budget");u=l()}let d=a.digest("hex");return{...u,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${d}`,hash:d,count:n}}}function cp(e){let t=Ii(e),i=t.entries.map((n,a)=>lO(n,`Snapshot entry ${a}`));if(i.sort(dO),new Set(i.map(n=>n.path)).size!==i.length)throw new Error("Snapshot entries must not contain duplicate paths");let r=t.omitted.map((n,a)=>uO(n,`Snapshot omission ${a}`));return r.sort(fO),hO({schema:$b,origin:t.origin,...t.capture?{capture:t.capture}:{},complete:t.complete,limits:{maxFiles:t.limits.maxFiles,maxFileBytes:t.limits.maxFileBytes,maxTotalBytes:t.limits.maxTotalBytes,maxManifestBytes:t.limits.maxManifestBytes,...t.limits.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},...t.policy?{policy:t.policy}:{},entries:i,omitted:r,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:{ref:t.omissionOverflow.ref,hash:t.omissionOverflow.hash,count:t.omissionOverflow.count}}:{}})}function cs(e){let t=new Map;for(let[i,r]of e.entries()){if(r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${i} kind is invalid`);let n={path:Rr(r.path,`Declared artifact ${i} path`),kind:r.kind},a=t.get(n.path);if(a&&a.kind!==n.kind)throw new Error(`Declared artifact path has conflicting kinds: ${n.path}`);t.set(n.path,n)}return[...t.values()].sort((i,r)=>Ge(i.path,r.path)||Ge(i.kind,r.kind))}function ls(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function Cb(e){return e?{hash:e.hash,size:e.size}:null}function dp(e,t,i){let r=0,n=0;for(;r<e.entries.length||n<t.entries.length;){let a=e.entries[r],o=t.entries[n],s=a===void 0?1:o===void 0?-1:Ge(a.path,o.path),c=s<=0?a:void 0,l=s>=0?o:void 0;if(s<=0&&(r+=1),s>=0&&(n+=1),c&&l&&c.hash===l.hash&&c.size===l.size||c&&!l&&!t.complete)continue;let u=c?.path??l?.path;u!==void 0&&i({path:u,kind:c?l?"modified":"removed":"added",before:Cb(c),after:Cb(l)})}}function Db(e,t){return{...e,attributedTo:t.filter(i=>ls(i,e.path))}}function fp(e){let t=cs(e.declaredArtifacts),i=[];return dp(e.baseline,e.current,r=>{i.push(Db(r,t))}),i}function Oi(e,t){return{id:`scope:${D(rO,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function pO(e,t){let i=t.omitted.map(r=>Oi({kind:"snapshot-omission",source:e,path:r.path,evidence:{reason:r.reason,size:r.size,type:r.type}},`${e} snapshot omitted ${r.path}: ${r.reason}`));return t.complete||i.push(Oi({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&i.push(Oi({kind:"snapshot-omission-overflow",source:e,path:null,evidence:{count:t.omissionOverflow.count,hash:t.omissionOverflow.hash,ref:t.omissionOverflow.ref}},`${e} snapshot has ${t.omissionOverflow.count} unlisted omissions`)),i}function xb(e,t){return pO(e,{...t,omitted:[]}).filter(i=>i.kind!=="snapshot-omission")}function lp(e,t){return Ge(e.kind,t.kind)||Ge(e.source,t.source)||cO(e.path,t.path)||Ge(e.id,t.id)}function mO(e){return[...new Map(e.map(i=>[i.id,i])).values()].sort(lp)}function Lb(e){return[...new Set(e.map((t,i)=>Rr(t,`Git path ${i}`)))].sort(Ge)}function Ab(e,t){if(typeof e!="string"||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(e))throw new Error(`${t} must be a Git commit object id`);return e}function vO(e,t){if(typeof e!="string"||e.length===0||e.trim()!==e||e.includes("\\")||e.includes("\0")||e.startsWith("-"))throw new Error(`${t} must be a valid Git branch name`);return e}function Mb(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=Lb(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:Ab(e.baseCommit,"Native external drift base commit"),targetBranch:vO(e.targetBranch,"Native external drift target branch"),targetCommit:Ab(e.targetCommit,"Native external drift target commit"),paths:t}}function Fb(e){if(typeof e.contractHash!="string"||!up.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:cs(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:Lb(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:Mb(e.externalDrift)}}}function gO(e,t,i,r,n){let a=[],o=r===void 0?null:new Set(r),s=[],c=[],l=0,u=!1,d=0,f=0;return dp(e,t,h=>{let v=i.some(m=>ls(m,h.path));if(d+=1,c.push(h.path),!v&&!n?.has(h.path)&&(f+=1),o?.has(h.path)&&s.push(h.path),!u&&a.length<oO){let m=Db(h,i),p=ss(m);l+p<=pn?(a.push(m),l+=p):u=!0}}),{candidates:a,gitPathsPresentInChanges:s,changePaths:c,totalChanges:d,totalUnattributed:f}}function Bb(e,t){return Oi({kind:"scope-detail-overflow",source:"implementation-scope",path:null,evidence:{changeCount:t.changes,hash:e,unattributedCount:t.unattributed,unresolvedCount:t.unresolved}},`Implementation scope summarized ${t.changes} additional change details and ${t.unresolved} unresolved details (${t.unattributed} unattributed); overflow hash ${e}`)}function wO(e){let t=/^Implementation scope summarized ([0-9]+) additional change details and ([0-9]+) unresolved details \(([0-9]+) unattributed\); overflow hash ([a-f0-9]{64})$/u.exec(e.reason);if(!t)throw new Error("Implementation scope detail overflow is invalid");let i={changes:ga(Number(t[1]),"Scope overflow change count"),unresolved:ga(Number(t[2]),"Scope overflow unresolved count"),unattributed:ga(Number(t[3]),"Scope overflow unattributed count")},r=hn(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(Bb(r,i)))throw new Error("Implementation scope detail overflow is inconsistent");return{...i,hash:r}}function yO(e){let t=jb("sha256");t.update(`${nO}
204
- `);let i=0;dp(e.baseline,e.current,n=>{if(i>=e.detailedChangeCount){Pr(t,"change",n);let a=0;for(let o of e.declaredArtifacts)ls(o,n.path)&&(a+=1,Pr(t,"change-attribution",o));Pr(t,"change-end",{attributionCount:a}),a===0&&Pr(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}i+=1});let r=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)r>=e.detailedOmissionCount&&Pr(t,"snapshot-omission",{source:n,...o}),r+=1;return t.digest("hex")}function Vb(e,t,i){let{contractHash:r,declaredArtifacts:n,noCodeReason:a}=i,o=gO(e,t,n,i.gitChangedPaths,i.externalDrift?new Set(i.externalDrift.paths):void 0);if(i.externalDrift){let R=new Set(i.externalDrift.paths),N=new Set(o.changePaths),w=i.externalDrift.paths.filter(P=>!N.has(P)||n.some(F=>ls(F,P)));if(w.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${w.slice(0,8).join(", ")}`);if(R.size!==i.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=D(as,e),c=D(as,t),l=[],u=new Set(i.externalDrift?.paths??[]);for(let[R,N]of[["baseline",e],["current",t]])for(let w of N.omitted){if(l.length>=sO)break;l.push(Oi({kind:"snapshot-omission",source:R,path:w.path,evidence:{reason:w.reason,size:w.size,type:w.type}},`${R} snapshot omitted ${w.path}: ${w.reason}`))}let d=e.omitted.length+t.omitted.length,f=[...xb("baseline",e),...xb("current",t),...o.totalChanges===0&&a===null?[Oi({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:s,currentProjectionHash:c}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],h=()=>{if(i.gitChangedPaths===void 0)return;let R=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:i.gitChangedPaths,pathsPresentInSnapshotChanges:i.gitChangedPaths.filter(N=>R.has(N)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(N=>!R.has(N))}},v=R=>{let N=o.candidates.slice(0,R.detailedChangeCount),w=N.filter(Vt=>Vt.attributedTo.length===0&&!u.has(Vt.path)),P=o.totalChanges-N.length,F=o.totalUnattributed-w.length,$=d-R.detailedOmissionCount,Fe=F+$,ue=[...w.map(Vt=>Oi({kind:"unattributed-change",source:"implementation-scope",path:Vt.path,evidence:{after:Vt.after,before:Vt.before,changeKind:Vt.kind}},`Changed path is not covered by a declared artifact: ${Vt.path}`)),...l.slice(0,R.detailedOmissionCount),...f,...Fe>0?[Bb(R.overflowHash,{changes:P,unattributed:F,unresolved:Fe})]:[]],te=mO(ue),ai=R.includeGitAdvisory?h():void 0;return{schema:op,contractHash:r,baselineProjectionRef:sp(s),baselineProjectionHash:s,currentProjectionRef:sp(c),currentProjectionHash:c,complete:te.length===0,declaredArtifacts:n,changes:N,unattributed:w,unresolvedScopes:te,noCodeReason:a,...ai?{gitAdvisory:ai}:{},...i.externalDrift?{externalDrift:i.externalDrift}:{}}},m=o.candidates.length,p=l.length,b=i.gitChangedPaths!==void 0,g="0".repeat(64);for(;;){let R=v({detailedChangeCount:m,detailedOmissionCount:p,includeGitAdvisory:b,overflowHash:g});if(ss({...R,scopeHash:g})<=pn)break;if(b){b=!1;continue}if(p>0){p-=Math.max(1,Math.ceil(p/4));continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let E=o.totalChanges>m||d>p?yO({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:m,detailedOmissionCount:p}):g,k=v({detailedChangeCount:m,detailedOmissionCount:p,includeGitAdvisory:b,overflowHash:E}),S={...k,scopeHash:D(Ob,k)};if(ss(S)>pn)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return S}function hp(e){let t=cp(e.baseline),i=cp(e.current),r=Fb(e);return{authority:r,baseline:t,current:i,scope:Vb(t,i,r)}}var NO=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"]);function gi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function wi(e,t,i,r){let n=new Set([...t,...i]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${r} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${r} is missing field(s): ${o.join(", ")}`)}function hn(e,t){if(typeof e!="string"||!up.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function _b(e,t,i){let r=sp(t);if(e!==r)throw new Error(`${i} ref/hash mismatch`);return r}function wa(e,t){let i=gi(e,"Native snapshot projection");if(wi(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==$b)throw new Error("Native snapshot projection schema is invalid");let r=Ii({schema:"comet.native.content-snapshot.v1",origin:i.origin,...i.capture===void 0?{}:{capture:i.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:i.complete,limits:i.limits,...i.policy===void 0?{}:{policy:i.policy},entries:i.entries,omitted:i.omitted,omittedCount:i.omittedCount,...i.omissionOverflow===void 0?{}:{omissionOverflow:i.omissionOverflow}}),n=cp(r);if(D(as,i)!==D(as,n))throw new Error("Native snapshot projection is not canonical");let a=D(as,n);if(t!==void 0&&hn(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function pp(e,t){let i=gi(e,`Declared artifact ${t}`);if(wi(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:Rr(i.path,`Declared artifact ${t} path`),kind:i.kind}}function Tb(e,t){if(e===null)return null;let i=gi(e,t);return wi(i,["hash","size"],[],t),{hash:hn(i.hash,`${t} hash`),size:ga(i.size,`${t} size`)}}function Ib(e,t){let i=gi(e,`Implementation change ${t}`);if(wi(i,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),i.kind!=="added"&&i.kind!=="modified"&&i.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(i.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let r=i.attributedTo.map(pp),n=cs(r);if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=Tb(i.before,`Implementation change ${t} before`),o=Tb(i.after,`Implementation change ${t} after`);if(i.kind==="added"&&(a!==null||o===null)||i.kind==="removed"&&(a===null||o!==null)||i.kind==="modified"&&(a===null||o===null||JSON.stringify(a)===JSON.stringify(o)))throw new Error(`Implementation change ${t} before/after state is invalid`);return{path:Rr(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:r}}function bO(e,t){let i=gi(e,`Unresolved scope ${t}`);wi(i,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let r=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof i.kind!="string"||!r.has(i.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(i.source!=="baseline"&&i.source!=="current"&&i.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof i.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(i.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(i.path!==null&&typeof i.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof i.reason!="string"||i.reason.length===0||i.reason.trim()!==i.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:i.id,kind:i.kind,source:i.source,path:i.path===null?null:i.kind==="snapshot-omission"?Hb(i.path,`Unresolved scope ${t} path`):Rr(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function os(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of paths`);let i=e.map((n,a)=>Rr(n,`${t} ${a}`)),r=[...new Set(i)].sort(Ge);if(JSON.stringify(i)!==JSON.stringify(r))throw new Error(`${t} must be sorted and unique`);return i}function qb(e){let t=gi(e,"Native implementation external drift");if(wi(t,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),t.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let i=os(t.paths,"Native external drift paths");return Mb({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:i})}function ya(e){let t=gi(e,"Native implementation scope"),i=[...NO].filter(w=>w!=="gitAdvisory"&&w!=="externalDrift");if(wi(t,i,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==op)throw new Error("Native implementation scope schema is invalid");let r=hn(t.contractHash,"Implementation scope contractHash"),n=hn(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=_b(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=hn(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=_b(t.currentProjectionRef,o,"Implementation scope current projection");if(typeof t.complete!="boolean")throw new Error("Implementation scope complete flag is invalid");if(!Array.isArray(t.declaredArtifacts)||!Array.isArray(t.changes)||!Array.isArray(t.unattributed)||!Array.isArray(t.unresolvedScopes))throw new Error("Implementation scope collections are invalid");let c=t.declaredArtifacts.map(pp);if(JSON.stringify(c)!==JSON.stringify(cs(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(Ib),u=[...l].sort((w,P)=>Ge(w.path,P.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(w=>w.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(w=>`${w.kind}:${w.path}`));if(l.some(w=>w.attributedTo.some(P=>!d.has(`${P.kind}:${P.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(w=>JSON.stringify(w.attributedTo)!==JSON.stringify(c.filter(P=>ls(P,w.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(Ib),h=t.externalDrift===void 0?void 0:qb(t.externalDrift),v=new Set(h?.paths??[]),m=l.filter(w=>w.attributedTo.length===0&&!v.has(w.path));if(JSON.stringify(f)!==JSON.stringify(m))throw new Error("Implementation scope unattributed changes are inconsistent");let p=t.unresolvedScopes.map(bO),b=p.filter(w=>w.kind==="scope-detail-overflow");if(b.length>1)throw new Error("Implementation scope has multiple detail overflow records");let g=b[0]===void 0?null:wO(b[0]);if(g&&(g.changes+g.unresolved===0||g.unattributed>g.changes||g.unattributed>g.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let y=t.noCodeReason,E=[...m.map(w=>Oi({kind:"unattributed-change",source:"implementation-scope",path:w.path,evidence:{after:w.after,before:w.before,changeKind:w.kind}},`Changed path is not covered by a declared artifact: ${w.path}`)),...l.length+(g?.changes??0)===0&&y===null?[Oi({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:n,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],k=p.filter(w=>w.kind==="unattributed-change"||w.kind==="missing-no-code-reason");if(JSON.stringify(p)!==JSON.stringify([...p].sort(lp))||new Set(p.map(w=>w.id)).size!==p.length||JSON.stringify(k)!==JSON.stringify(E.sort(lp))||t.complete!==(p.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let S;if(t.gitAdvisory!==void 0){let w=gi(t.gitAdvisory,"Implementation scope Git advisory");if(wi(w,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),w.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let P=os(w.changedPaths,"Git changed paths"),F=os(w.pathsPresentInSnapshotChanges,"Git present paths"),$=os(w.pathsAbsentFromSnapshotChanges,"Git absent paths"),Fe=[...F,...$].sort(Ge);if(JSON.stringify(Fe)!==JSON.stringify(P)||$.some(ue=>l.some(te=>te.path===ue)))throw new Error("Implementation scope Git advisory partition is invalid");S={advisoryOnly:!0,changedPaths:P,pathsPresentInSnapshotChanges:F,pathsAbsentFromSnapshotChanges:$}}let R={schema:op,contractHash:r,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:p,noCodeReason:y,...S?{gitAdvisory:S}:{},...h?{externalDrift:h}:{}},N=hn(t.scopeHash,"Implementation scope scopeHash");if(D(Ob,R)!==N)throw new Error("Implementation scope content hash mismatch");return{...R,scopeHash:N}}function kO(e){let t=gi(e,"Native implementation scope authority");if(wi(t,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths","externalDrift"],"Native implementation scope authority"),!Array.isArray(t.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let i=t.declaredArtifacts.map(pp);if(JSON.stringify(i)!==JSON.stringify(cs(i)))throw new Error("Native implementation scope authority declarations must be canonical");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let r;t.gitChangedPaths!==void 0&&(r=os(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:qb(t.externalDrift),a=Fb({contractHash:t.contractHash,declaredArtifacts:i,noCodeReason:t.noCodeReason,...r===void 0?{}:{gitChangedPaths:r},...n===void 0?{}:{externalDrift:n}});if(a.contractHash!==t.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return a}function us(e){let t=gi(e,"Native implementation scope bundle");wi(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=kO(t.authority),r=wa(t.baseline),n=wa(t.current),a=ya(t.scope),o=Vb(r,n,i);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:i,baseline:r,current:n,scope:o}}function Wb(e){let t=ya(e.scope);return us({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{},...t.externalDrift?{externalDrift:t.externalDrift}:{}},baseline:e.baseline,current:e.current,scope:t})}import zb from"node:path";var SO=/\b(Bearer|Basic)\s+[^\s"']+/giu,EO=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,PO=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,RO=/\b(?:sk-(?:proj-)?[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{16,}|AKIA[A-Z0-9]{16}|AIza[A-Za-z0-9_-]{20,})\b/gu,CO=/("(?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie)"\s*:\s*)"(?:\\[\s\S]|[^"\\\r\n])*"/giu,xO=/(["'])((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\1(\s*:\s*)(["'])[^\r\n]*?\4/giu,AO=/\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\b(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)/giu;function $t(e){return e.replace(SO,"$1 [REDACTED]").replace(EO,"[REDACTED PRIVATE KEY]").replace(PO,"$1[REDACTED]@").replace(RO,"[REDACTED TOKEN]").replace(CO,'$1"[REDACTED]"').replace(xO,"$1$2$1$3$4[REDACTED]$4").replace(AO,"$1$2[REDACTED]")}var Gb=/^[a-f0-9]{64}$/u;var _O="comet.native.acceptance-trace.v2",TO="comet.native.partial-allowance.v1",IO="comet.native.verification-evidence.v2";function Hi(e,t){if(!Gb.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ub(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function Kb(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native evidence change name: ${e}`);return e}function mp(e,t,i=2e3){let r=$t(e).trim();if(r.length===0||r.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return r}function ds(e,t){let i=zb.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||zb.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function jO(e,t,i){let r=ds(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(r))return r;let n=ci(r),a=r.toLowerCase(),o=i?ds(i,"Native root ref").toLowerCase():null;if(n||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${t} is excluded as sensitive (${n??"native-runtime"}): ${r}`);return r}function vp(e){let t=ds(e,"Verification typed receipt ref");if(!/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u.test(t))throw new Error("Verification receipt ref must identify a typed v3 receipt");return t}function Na(e,t){return e<t?-1:e>t?1:0}function tu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function iu(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function Yb(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function Jb(e,t,i){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let r=`runtime/evidence/${t}/${i}.json`;if(e!==r)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function $O(e){let t=tu(e,"Native acceptance trace");if(iu(t,["schema","nativeRootRef","criteriaHash","total","evidenced","skipped","entries","traceHash"],"Native acceptance trace"),t.schema!=="comet.native.acceptance-trace.v2"||typeof t.nativeRootRef!="string"||typeof t.criteriaHash!="string"||!Gb.test(t.criteriaHash)||!Number.isSafeInteger(t.total)||!Number.isSafeInteger(t.evidenced)||!Number.isSafeInteger(t.skipped)||!Array.isArray(t.entries))throw new Error("Native acceptance trace is invalid");let i=ds(t.nativeRootRef,"Native root ref"),r=t.entries.map((o,s)=>{let c=tu(o,`Native acceptance trace entry ${s}`);if(iu(c,["acceptanceId","status","kind","source","evidenceRefs","skippedReason"],`Native acceptance trace entry ${s}`),typeof c.acceptanceId!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(c.acceptanceId)||c.kind!=="brief-example"&&c.kind!=="spec-scenario"&&c.kind!=="spec-must"||typeof c.source!="string"||!Array.isArray(c.evidenceRefs)||c.status!=="passed"&&c.status!=="failed"&&c.status!=="missing"||c.evidenceRefs.some(d=>typeof d!="string")||c.skippedReason!==null&&(typeof c.skippedReason!="string"||c.skippedReason.length===0||c.skippedReason.trim()!==c.skippedReason))throw new Error(`Native acceptance trace entry ${s} is invalid`);let l=c.evidenceRefs.map(d=>vp(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Na))||u==="passed"&&(l.length===0||c.skippedReason!==null)||u==="failed"&&l.length===0&&c.skippedReason===null||u==="missing"&&(l.length>0||c.skippedReason!==null))throw new Error(`Native acceptance trace entry ${s} evidence state is invalid`);return{acceptanceId:c.acceptanceId,status:u,kind:c.kind,source:ds(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:mp(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(r)!==JSON.stringify([...r].sort((o,s)=>Na(o.acceptanceId,s.acceptanceId)))||new Set(r.map(o=>o.acceptanceId)).size!==r.length||t.total!==r.length||t.evidenced!==r.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==r.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let n={schema:"comet.native.acceptance-trace.v2",nativeRootRef:i,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:r},a=Hi(t.traceHash,"Native acceptance trace hash");if(D(_O,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function ru(e){let t=tu(e,"Native partial allowance");if(iu(t,["schema","change","scopeHash","scopeIds","reason","confirmedSummary","sourceRevision","confirmedAt","allowanceHash"],"Native partial allowance"),t.schema!=="comet.native.partial-allowance.v1"||typeof t.change!="string"||typeof t.scopeHash!="string"||!Array.isArray(t.scopeIds)||t.scopeIds.length===0||t.scopeIds.some(n=>typeof n!="string"||!/^scope:[a-f0-9]{64}$/u.test(n))||JSON.stringify(t.scopeIds)!==JSON.stringify([...new Set(t.scopeIds)].sort(Na))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let i={schema:"comet.native.partial-allowance.v1",change:Kb(t.change),scopeHash:Hi(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:mp(t.reason,"Partial allowance reason"),confirmedSummary:mp(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:Ub(t.sourceRevision),confirmedAt:Yb(t.confirmedAt,"Native partial allowance timestamp")};if(i.reason!==t.reason||i.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let r=Hi(t.allowanceHash,"Native partial allowance hash");if(D(TO,i)!==r)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:r}}function fs(e){let t=tu(e,"Native verification evidence");if(iu(t,["schema","change","sourceRevision","result","freshness","contractHash","acceptanceCriteriaHash","implementationScopeRef","implementationScopeHash","reportRef","reportHash","acceptanceTrace","partialAllowanceRef","partialAllowanceHash","requiredReceiptRefs","receiptRefs","createdAt","envelopeHash"],"Native verification evidence"),t.schema!=="comet.native.verification-evidence.v2"||typeof t.change!="string"||t.result!=="pass"&&t.result!=="fail"||t.freshness!=="complete"&&t.freshness!=="partial"||typeof t.implementationScopeHash!="string"||typeof t.reportRef!="string"||!Array.isArray(t.requiredReceiptRefs)||!Array.isArray(t.receiptRefs))throw new Error("Native verification evidence is invalid");let i=Hi(t.implementationScopeHash,"Native verification implementation scope hash"),r=$O(t.acceptanceTrace),n=Hi(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(r.criteriaHash!==n)throw new Error("Native verification acceptance trace does not match its criteria hash");let a=t.partialAllowanceRef!==null||t.partialAllowanceHash!==null;if(t.partialAllowanceRef===null!=(t.partialAllowanceHash===null)||t.freshness==="complete"&&a||t.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=t.partialAllowanceHash===null?null:Hi(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>vp(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(Na)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(r.entries.flatMap(f=>f.evidenceRefs))].sort(Na);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=t.requiredReceiptRefs.map(f=>vp(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Na)))throw new Error("Native required receipt refs must be canonical");if(t.result==="pass"&&l.length===0)throw new Error("Passing verification has no current static receipt");let u={schema:"comet.native.verification-evidence.v2",change:Kb(t.change),sourceRevision:Ub(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:Hi(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:Jb(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:jO(t.reportRef,"Native verification report ref"),reportHash:Hi(t.reportHash,"Native verification report hash"),acceptanceTrace:r,partialAllowanceRef:o===null?null:Jb(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:Yb(t.createdAt,"Native verification timestamp")},d=Hi(t.envelopeHash,"Native verification envelope hash");if(D(IO,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}import Xb from"node:path";var Qb="comet.native.check-receipt.v1",OO="comet.native.check-receipt.v1",ba="scoped-text-safety",gp=1,dt=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),HO=/^[a-f0-9]{64}$/u,DO=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,LO="comet.native.checker-policy.v1",MO="comet.native.check-input.v1",FO=2048,Zb=D(LO,{policy:ba,version:gp,limits:dt,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),BO=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),ek=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],ik=["contract-before-does-not-match-scope","implementation-before-does-not-match-scope","contract-changed-during-check","implementation-changed-during-check","contract-after-does-not-match-scope","implementation-after-does-not-match-scope"],VO=new Set(ik);function Cr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function xr(e,t,i,r=[]){let n=new Set([...t,...r]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${i} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${i} is missing field(s): ${o.join(", ")}`)}function Di(e,t){if(typeof e!="string"||!HO.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function St(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function rk(e,t){let i=St(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function tk(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(!Number.isFinite(i.getTime())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function qO(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>FO||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a bounded normalized project-relative path`);let i=Xb.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||Xb.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function WO(e){let t=Cr(e,"Native check receipt checker");xr(t,["policy","version","hash","limits"],"Native check receipt checker");let i=Cr(t.limits,"Native check receipt limits");if(xr(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==ba||t.version!==gp||t.hash!==Zb||i.maxFiles!==dt.maxFiles||i.maxFileBytes!==dt.maxFileBytes||i.maxTotalBytes!==dt.maxTotalBytes||i.maxIssues!==dt.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:ba,version:gp,hash:Zb,limits:{...dt}}}function zO(e){let t=Cr(e,"Native check receipt contract");return xr(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:Di(t.expectedHash,"Native check expected contract hash"),beforeHash:Di(t.beforeHash,"Native check before contract hash"),afterHash:Di(t.afterHash,"Native check after contract hash")}}function JO(e){let t=Cr(e,"Native check receipt implementation");return xr(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:Di(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:Di(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:Di(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:Di(t.afterSnapshotHash,"Native check after snapshot hash")}}function GO(e,t){let i=Cr(e,`Native check batch ${t}`);xr(i,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let r={filesSelected:St(i.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:St(i.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:St(i.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:St(i.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:St(i.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:St(i.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(r.filesSelected>dt.maxFiles||r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.bytesScanned>dt.maxTotalBytes||r.recordedIssueCount>r.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return r}function UO(e){let t=Cr(e,"Native check receipt counts");xr(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let i={filesSelected:St(t.filesSelected,"Native check filesSelected"),filesScanned:St(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:St(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:St(t.bytesScanned,"Native check bytesScanned"),issueCount:St(t.issueCount,"Native check issueCount"),recordedIssueCount:St(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(GO):(()=>{throw new Error("Native check receipt batches must be an array")})()}},r=i.batches;if(r!==void 0){if(r.length===0)throw new Error("Native check receipt batches must not be empty");let n=r.reduce((a,o)=>({filesSelected:a.filesSelected+o.filesSelected,filesScanned:a.filesScanned+o.filesScanned,binaryFilesSkipped:a.binaryFilesSkipped+o.binaryFilesSkipped,bytesScanned:a.bytesScanned+o.bytesScanned,issueCount:a.issueCount+o.issueCount,recordedIssueCount:a.recordedIssueCount+o.recordedIssueCount}),{filesSelected:0,filesScanned:0,binaryFilesSkipped:0,bytesScanned:0,issueCount:0,recordedIssueCount:0});if(JSON.stringify(n)!==JSON.stringify({...i,batches:void 0}))throw new Error("Native check receipt batch totals are inconsistent")}if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>dt.maxIssues||r===void 0&&(i.filesScanned+i.binaryFilesSkipped>dt.maxFiles||i.bytesScanned>dt.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return i}function KO(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||ek.indexOf(e.kind)-ek.indexOf(t.kind)}function YO(e){if(!Array.isArray(e)||e.length>dt.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((r,n)=>{let a=Cr(r,`Native check issue ${n}`);if(xr(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!BO.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:qO(a.path,`Native check issue ${n} path`),line:rk(a.line,`Native check issue ${n} line`),kind:a.kind}}),i=[...t].sort(KO);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function XO(e){if(!Array.isArray(e)||e.some(r=>typeof r!="string"||!VO.has(r)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=ik.filter(r=>t.includes(r));if(new Set(t).size!==t.length||JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function QO(e){return D(MO,e)}function nu(e){let t=Cr(e,"Native check receipt");if(xr(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==Qb)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!DO.test(t.change))throw new Error("Native check receipt change name is invalid");let i=rk(t.sourceRevision,"Native check source revision"),r=WO(t.checker),n=zO(t.contract),a=JO(t.implementation),o=QO({change:t.change,sourceRevision:i,checkerHash:r.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(Di(t.inputHash,"Native check input hash")!==o)throw new Error("Native check receipt input hash mismatch");if(t.status!=="passed"&&t.status!=="failed")throw new Error("Native check receipt status is invalid");let s=tk(t.startedAt,"Native check receipt startedAt"),c=tk(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=UO(t.counts),u=YO(t.issues);if(l.recordedIssueCount!==u.length)throw new Error("Native check receipt recorded issue count is inconsistent");if(typeof t.issuesTruncated!="boolean"||t.issuesTruncated!==l.issueCount>u.length)throw new Error("Native check receipt issue truncation flag is inconsistent");let d=XO(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let f=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==f)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.batches===void 0&&l.filesSelected>dt.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.batches===void 0&&l.filesSelected>dt.maxFiles&&!u.some(m=>m.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let h={schema:Qb,change:t.change,sourceRevision:i,checker:r,inputHash:o,status:t.status,startedAt:s,endedAt:c,contract:n,implementation:a,counts:l,issues:u,issuesTruncated:t.issuesTruncated,stale:t.stale,staleReasons:d},v=Di(t.receiptHash,"Native check receipt content hash");if(D(OO,h)!==v)throw new Error("Native check receipt content hash mismatch");return{...h,receiptHash:v}}var yp="comet.native.verification-receipt.v3",ZO=yp,e0="comet.native.declared-artifacts.v1",t0=/^[a-f0-9]{64}$/u,i0=/^acceptance-[a-f0-9]{64}$/u,r0=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,n0=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,a0=4096,o0=256,s0=1024;function ka(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function Ar(e,t,i){let r=Object.keys(e).sort(),n=[...t].sort();if(r.length!==n.length||r.some((a,o)=>a!==n[o]))throw new Error(`${i} fields are invalid`)}function Li(e,t){if(typeof e!="string"||!t0.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function ii(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=$t(e).trim();if(!i||i.length>a0||i!==e.trim())throw new Error(`${t} is invalid`);return i}function wp(e,t){let i=ii(e,t),r=new Date(i);if(Number.isNaN(r.getTime())||r.toISOString()!==i)throw new Error(`${t} must be a canonical timestamp`);return i}function hs(e,t,i=ii,r=!1,n=o0){if(!Array.isArray(e)||e.length>n||!r&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>i(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function c0(e,t){if(typeof e!="string"||!i0.test(e))throw new Error(`${t} is invalid`);return e}function l0(e){let t=ka(e,"Native verification receipt bindings");if(Ar(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!r0.test(t.change)||!Number.isSafeInteger(t.sourceRevision)||t.sourceRevision<1)throw new Error("Native verification receipt bindings are invalid");return{change:t.change,sourceRevision:t.sourceRevision,contractHash:Li(t.contractHash,"Native verification receipt contract hash"),scopeHash:Li(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:Li(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:Li(t.artifactHash,"Native verification receipt artifact hash")}}function u0(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=n0.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function d0(e,t,i,r){let n=ka(t,`Native ${e} evidence`);if(e==="automated-check"){if(Ar(n,["executable","args","cwd","exitCode","signal","timedOut","timeoutMs","startedAt","endedAt","worktree","afterFence","outputHash","outputSummary","outputTruncated"],"Native automated-check evidence"),!Number.isSafeInteger(n.exitCode)||!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<1||n.timeoutMs>3600*1e3||typeof n.timedOut!="boolean"||typeof n.outputTruncated!="boolean"||n.signal!==null&&typeof n.signal!="string")throw new Error("Native automated-check exit code is invalid");let a=wp(n.startedAt,"Native automated-check start time"),o=wp(n.endedAt,"Native automated-check end time");if(Date.parse(o)<Date.parse(a))throw new Error("Native automated-check time range is invalid");if(i==="passed"&&n.exitCode!==0||i==="failed"&&n.exitCode===0||i==="passed"&&(n.timedOut||n.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=ka(n.worktree,"Native automated-check worktree");if(Ar(s,["provider","root","beforeCommit","afterCommit"],"Native automated-check worktree"),s.provider!=="git"&&s.provider!=="none"||s.beforeCommit!==null&&(typeof s.beforeCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.beforeCommit))||s.afterCommit!==null&&(typeof s.afterCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.afterCommit)))throw new Error("Native automated-check worktree identity is invalid");let c=ka(n.afterFence,"Native automated-check after fence");if(Ar(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(i==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:ii(n.executable,"Native automated-check executable"),args:hs(n.args,"Native automated-check arguments",ii,!0),cwd:ii(n.cwd,"Native automated-check cwd"),exitCode:n.exitCode,signal:n.signal,timedOut:n.timedOut,timeoutMs:n.timeoutMs,startedAt:a,endedAt:o,worktree:{provider:s.provider,root:ii(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:Li(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:Li(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:Li(n.outputHash,"Native automated-check output hash"),outputSummary:ii(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){Ar(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=u0(n.checkReceiptRef);if(Li(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:hs(n.subjects,"Native static inspection subjects",ii,r==="required-check"),rule:ii(n.rule,"Native static inspection rule"),resultSummary:ii(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return Ar(n,["steps","observations"],"Native manual-evidence evidence"),{steps:hs(n.steps,"Native manual evidence steps"),observations:hs(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function f0(e){let t=ka(e,"Native verification receipt");if(Ar(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence"],"Native verification receipt input"),!["automated-check","static-inspection","manual-evidence"].includes(t.kind)||t.role!=="required-check"&&t.role!=="acceptance-evidence"||!["passed","failed","skipped","blocked"].includes(t.status))throw new Error("Native verification receipt kind or status is invalid");let i=t.kind,r=t.role,n=t.status,a=ii(t.actor,"Native verification receipt actor"),o=hs(t.acceptanceIds,"Native receipt acceptance IDs",c0,r==="required-check",s0).sort();if(r==="required-check"&&o.length!==0||r==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(r==="required-check"&&i!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:yp,kind:i,role:r,status:n,bindings:l0(t.bindings),acceptanceIds:o,actor:a,issuedAt:wp(t.issuedAt,"Native verification receipt issue time"),evidence:d0(i,t.evidence,n,r)};if(r==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==ba||s.actor!==`native-runtime:${ba}`))throw new Error("Native required check policy identity is invalid");return s}function au(e){let t=ka(e,"Native verification receipt");if(Ar(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==yp)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...r}=t,n=f0(r),a=Li(t.receiptHash,"Native verification receipt hash");if(D(ZO,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function Np(e){return D(e0,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}var sk=/^[a-f0-9]{64}$/u,_r=pn,_z=3*_r;function bp(e,t){let i=yi.relative(e,t);return i===""||!yi.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${yi.sep}`)}function p0(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ou(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return vt(i,r)?z(i,r):z(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function nk(e){let t=await ri.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await ri.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function m0(e,t){let i=yi.resolve(e),r=yi.resolve(t);if(!bp(i,r))throw new Error("Native evidence path is outside its change");let n=[await nk(i)],a=i;for(let o of yi.relative(i,r).split(yi.sep).filter(Boolean)){a=yi.join(a,o);let s=await nk(a);if(!bp(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function ak(e){for(let t of e){let i=await ri.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!p0(t,i)||await ri.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function v0(e,t,i={}){let r=await m0(t,yi.dirname(e));await i.afterParentChainCaptured?.();let n=await ri.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await ri.realpath(e);if(!bp(r[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await ri.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),ri.lstat(e),ri.realpath(e)]);if(await ak(r),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!ou(s,n)||!ou(s,c))throw new Error("Native evidence document changed while opening");if(s.size>_r)throw new Error(`Native evidence document exceeds ${_r} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let p=_r+1-d,b=await o.read(f,0,Math.min(f.length,p),null);if(b.bytesRead===0)break;if(d+=b.bytesRead,d>_r)throw new Error(`Native evidence document exceeds ${_r} bytes`);u.push(Buffer.from(f.subarray(0,b.bytesRead)))}await i.beforeFinalCheck?.();let[h,v,m]=await Promise.all([o.stat(),ri.lstat(e),ri.realpath(e)]);if(await ak(r),!v.isFile()||v.isSymbolicLink()||m!==a||!ou(s,h)||!ou(s,v))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function Ea(e,t){if(!sk.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}function ck(e){return Ea("reports",e)}async function g0(e,t,i,r,n){if(!sk.test(i))throw new Error("Native report evidence hash is invalid");let a=await mn({paths:e,name:t,kind:"reports",hash:i,hooks:r,changeDir:n});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==i||typeof o.content!="string"||h0("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==i)throw new Error("Native report evidence does not match its hash");return o.content}function Sa(e,t){let i=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!i||i[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return i[2]}function w0(e,t,i,r,n){let a=Ea(i,r);return n?yi.join(n,...a.split("/")):lr(H(e,t),a)}async function mn(e){let t=w0(e.paths,e.name,e.kind,e.hash,e.changeDir),i=e.changeDir??j(e.paths,t);return await T(i,t),v0(t,i,e.hooks)}function ok(e,t){return wa(e,t)}function y0(e,t){let i=ya(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function N0(e,t,i){let r=ru(e);if(r.change!==t||r.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return r}function b0(e,t,i){let r=fs(e);if(r.change!==t||r.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return r}async function k0(e,t,i,r=!1,n){let a=await su(e,t,i.implementationScopeRef,void 0,n);if(r&&await g0(e,t,i.reportHash,void 0,n),a.scopeHash!==i.implementationScopeHash||a.contractHash!==i.contractHash||(a.complete?"complete":"partial")!==i.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(i.partialAllowanceRef===null)return;let o=await lk(e,t,i.partialAllowanceRef,void 0,n);if(o.allowanceHash!==i.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=i.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function ps(e,t,i,r,n){let a=Sa(i,"scopes"),o=y0(await mn({paths:e,name:t,kind:"scopes",hash:a,hooks:r,changeDir:n}),a),s=Sa(o.baselineProjectionRef,"snapshots"),c=Sa(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([mn({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>ok(d,s)),mn({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>ok(d,c))]);return Wb({baseline:l,current:u,scope:o})}async function su(e,t,i,r,n){return(await ps(e,t,i,r,n)).scope}async function lk(e,t,i,r,n){let a=Sa(i,"allowances");return N0(await mn({paths:e,name:t,kind:"allowances",hash:a,hooks:r,changeDir:n}),t,a)}async function ms(e,t,i,r,n){let a=Sa(i,"receipts"),o=au(await mn({paths:e,name:t,kind:"receipts",hash:a,hooks:r,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function Pa(e,t,i,r,n){let a=Sa(i,"verifications"),o=b0(await mn({paths:e,name:t,kind:"verifications",hash:a,hooks:r,changeDir:n}),t,a);return await k0(e,t,o,!1,n),o}var S0=4096;async function E0(e,t=ut.maxChanges){try{let i=await wt({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:t});return await i.verify(),i.entries}catch(i){if(i.code==="ENOENT")return[];throw i}}async function uk(e,t){let i=await He(e,t),[r,n]=await Promise.all([i.implementation_scope?su(e,t,i.implementation_scope):null,kt(e,t).catch(()=>null)]);return{name:i.name,revision:i.revision,specs:i.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:r?.declaredArtifacts??[],workspaceIdentityHash:n?.nativeRootId??null}}async function cu(e,t,i={}){let n=(await E0(e,S0)).filter(c=>c.isDirectory()&&!c.isSymbolicLink()).map(c=>c.name).sort();if(!n.includes(t))throw new Error(`Native conflict target is not visible: ${t}`);let a=await uk(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await uk(e,c).catch(d=>{if(i.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=Pb([a,l]).relationships[0];u.classification==="definite-conflict"&&(o+=1),u.classification==="possible-overlap"&&(s+=1)}return{definiteConflictCount:o,possibleOverlapCount:s,findingCodes:[...o>0?["native-change-conflict"]:[],...s>0?["native-change-overlap"]:[]]}}import{promises as B0}from"fs";import V0 from"path";import{isDeepStrictEqual as uu}from"util";var Ra={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var P0=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function R0(e,t){return e<t?-1:e>t?1:0}function C0(e,t,i,r){if(!Array.isArray(e)||e.length>i||!r&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let n=e.map(a=>{if(typeof a!="string"||!P0.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(R0)}function kp(e=[]){return C0(e,"Native repair failed check IDs",Ra.maxFailedCheckIds,!0)}function dk(e,t){let i=new Set(t);return e.every(r=>i.has(r))}function x0(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:dk(e.failedAcceptanceIds,t.failedAcceptanceIds)&&dk(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function Sp(e,t){let i=1,r=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if(x0(r,a))break;i+=1,r=a}return i}function Ep(e,t){if(typeof e!="string"||e.trim().length===0||e.length>4096)throw new Error(`${t} must be between 1 and 4096 characters`)}var fk="repairStagnation",Et={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},_0=/^[a-f0-9]{64}$/u;var T0=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),I0=["data","runId","sequence","timestamp","type"],hk=["disposition","overrideSummaryHash","signatureHash"],j0=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],pk=12;function Rp(e,t){return e<t?-1:e>t?1:0}function mk(e,t,i){let r=Object.keys(e).sort(Rp);if(r.length!==t.length||r.some((n,a)=>n!==t[a]))throw new Error(`${i} fields are invalid`)}function lu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function vs(e,t){if(typeof e!="string"||!_0.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function $0(e){if(!Array.isArray(e)||e.length>Ra.maxFailedAcceptanceIds||e.some(t=>typeof t!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(t)))throw new Error("Native repair trajectory failed acceptance IDs are invalid");return[...new Set(e)].sort(Rp)}function vk(e){if(typeof e!="string"||e.length===0||e.length>Et.maxRunIdCharacters||Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function Pp(e,t,i,r,n=!1){if(i.nodes+=1,i.nodes>Et.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Et.maxDataDepth)throw new Error("Native repair trajectory event data exceeds its depth boundary");if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${r} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>Et.maxTextCharacters&&(!n||e.length>Et.maxEventDataCharacters))throw new Error(`${r} contains oversized text`);if(i.characters+=e.length,i.characters>Et.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${r} contains a non-JSON value`);if(i.ancestors.has(e))throw new Error(`${r} contains a cycle`);i.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>Et.maxArrayEntries)throw new Error(`${r} contains an oversized array`);e.forEach((s,c)=>Pp(s,t+1,i,`${r}[${c}]`));return}let a=lu(e,r),o=Object.keys(a);if(o.length>Et.maxObjectFields)throw new Error(`${r} contains too many fields`);for(let s of o){if(s.length===0||s.length>Et.maxKeyCharacters)throw new Error(`${r} contains an invalid field name`);if(i.characters+=s.length,i.characters>Et.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");Pp(a[s],t+1,i,`${r}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function O0(e){if(typeof e!="string"||e.length>64)throw new Error("Native repair trajectory timestamp is invalid");let t=new Date(e);if(!Number.isFinite(t.valueOf())||t.toISOString()!==e)throw new Error("Native repair trajectory timestamp is invalid");return e}function H0(e,t,i){let r=lu(e,`Native repair trajectory event ${t+1}`);if(mk(r,I0,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(r.sequence)||r.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(O0(r.timestamp),typeof r.type!="string"||!T0.has(r.type))throw new Error("Native repair trajectory event type is invalid");if(vk(r.runId)!==i)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let n={nodes:0,characters:0,ancestors:new Set};return Pp(r.data,0,n,"Native trajectory event data"),lu(r.data,"Native repair trajectory event data"),{event:r,dataNodes:n.nodes,dataCharacters:n.characters}}function Cp(e){let t=lu(e,"Native repair trajectory projection"),i=Object.keys(t).sort(Rp),r=i.length===hk.length&&i.every((l,u)=>l===hk[u]);r||mk(t,j0,"Native repair trajectory projection");let n=vs(t.signatureHash,"Native repair trajectory signature hash");if(t.disposition!=="continue"&&t.disposition!=="warn"&&t.disposition!=="manual-stop"&&t.disposition!=="hard-stop")throw new Error("Native repair trajectory disposition is invalid");let a=t.overrideSummaryHash===null?null:vs(t.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&t.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(r)return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=vs(t.contractHash,"Native repair trajectory contract hash"),s=$0(t.failedAcceptanceIds),c=kp(t.failedCheckIds);if(!Number.isSafeInteger(t.maxVerifyFailures)||t.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:o,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:t.maxVerifyFailures}}function D0(e,t){if(t.overrideSummaryHash===null){if(e.previousPhase!=="verify"||e.nextPhase!=="build"||e.verificationResult!=="fail")throw new Error("Native repair failure projection is only valid on a failed Verify-to-Build transition");return}if(t.disposition!=="continue"||e.previousPhase!=="build"||e.nextPhase!=="verify"||e.verificationResult!==null)throw new Error("Native repair override projection is only valid on a Build-to-Verify transition")}function L0(e,t){let i=t.filter(s=>s.kind==="failure"),r=i.length+1,n=e.maxVerifyFailures??pk;if(r>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=Sp({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=r>=n?"hard-stop":a<Ra.warningAtConsecutiveFailures?"continue":a<Ra.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function M0(e,t,i){let r=t.filter(a=>a.kind==="failure"),n=i?.maxVerifyFailures??pk;if(r.length>=n)throw new Error("Native repair trajectory cannot override a hard stop");if(i?.disposition!=="manual-stop"||i.signatureHash!==e.signatureHash||r.at(-1)?.signatureHash!==e.signatureHash)throw new Error("Native repair trajectory override does not match the latest manual stop");if(t.some(a=>a.kind==="override"&&a.signatureHash===e.signatureHash))throw new Error("Native repair trajectory signature was already overridden")}function gk(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Et.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=vk(e.runId);if(!Number.isSafeInteger(e.committedTrajectoryOffset)||e.committedTrajectoryOffset<0||e.committedTrajectoryOffset>e.trajectory.length)throw new Error("Native repair committed trajectory offset is invalid");let i=[],r=null,n=null,a=null,o=0,s=0,c=0;for(let l=0;l<e.committedTrajectoryOffset;l+=1){let u=H0(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>Et.maxTotalDataNodes||c>Et.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,h=Object.hasOwn(f,"repairScopeHash")?vs(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?vs(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,fk)){if(r?.contractHash===null&&d.type==="state_transitioned"&&f.previousPhase==="build"&&f.nextPhase==="verify"&&(h!==null&&n!==null&&h!==n||h===null&&(r?.disposition==="manual-stop"||r?.disposition==="hard-stop"))){i.length=0,r=null,n=h,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let v=Cp(f[fk]);if(D0(f,v),v.overrideSummaryHash===null)v.contractHash!==null&&a!==null&&v.contractHash!==a&&(i.length=0,o=0),v.contractHash!==null&&(a=v.contractHash),v.contractHash===null&&h!==null&&n!==null&&h!==n&&(i.length=0,o=0),h!==null&&(n=h),L0(v,i),o+=1,i.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:v.signatureHash,...v.contractHash===null?{}:{failedAcceptanceIds:[...v.failedAcceptanceIds],failedCheckIds:[...v.failedCheckIds]}});else{if(r?.contractHash===null&&h!==null&&n!==null&&h!==n)throw new Error("Native repair override cannot cross implementation scope progress");M0(v,i,r);let m=i.at(-1);if(!m||m.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");i.push({kind:"override",revision:d.sequence,iteration:m.iteration,signatureHash:v.signatureHash,summaryHash:v.overrideSummaryHash})}if(r=v,i.length>Ra.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:r}}function wk(e){return gk(e).history}function yk(e){let t=gk(e).latestProjection;return t?{...t}:null}var Ni={root:"/comet/native-runtime",packageKind:"runtime",definition:{apiVersion:"comet/v1alpha1",kind:"Skill",metadata:{name:"comet-native-runtime",version:"3",description:"Comet-owned state runtime for the Native workflow."},goal:{statement:"Advance a Native change only after its current guard passes.",inputs:[],outputs:[],success:["The Native change and Run state agree on the next phase."]},orchestration:{mode:"deterministic",entry:"shape",steps:[{id:"shape",action:{type:"checkpoint"},next:"build"},{id:"build",action:{type:"checkpoint"},next:"verify"},{id:"verify",action:{type:"checkpoint"},next:"archive"},{id:"archive",action:{type:"checkpoint"}}]},skills:[],agents:[],tools:[]},guardrails:{allowedSkills:[],allowedAgents:[],allowedTools:[],maxIterations:Number.MAX_SAFE_INTEGER,maxRetriesPerAction:2,confirmationRequiredFor:[]},evals:[]},gs=L("comet-native-runtime:v3:scope-reopen"),F0=[{skillVersion:"3",skillHash:L("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:L("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:L("comet-native-runtime:v1")}];function Nk(e){return e.skillVersion===Ni.definition.metadata.version&&e.skillHash===gs||F0.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}var xp={resolveStep({pkg:e,state:t}){return e.definition.orchestration.steps?.find(i=>i.id===t.currentStep)},resolveNext({step:e,outcome:t}){return e.id==="verify"&&t.state?.verification_result==="fail"?"build":e.next??null}};async function Tr(e){let i={sequence:(await it(e.changeDir,e.run.trajectoryRef)).length+1,timestamp:(e.now??new Date).toISOString(),type:e.type,runId:e.run.runId,data:e.data};return await FN(e.changeDir,e.run.trajectoryRef,i),i}async function vn(e){let t={runId:e.run.runId,stateVersion:e.run.iteration,trajectoryOffset:e.trajectoryOffset,contextHash:null,artifactsHash:L(e.evidenceHash),createdAt:(e.now??new Date).toISOString()};return await BN(e.changeDir,e.run.checkpointRef,t),t}function bk(e){return L(JSON.stringify({summary:e.summary,returnToBuild:e.returnToBuild??!1,confirmed:e.confirmed??!1,artifacts:[...e.artifacts??[]].sort(),noCodeReason:e.noCodeReason??null,verificationResult:e.verificationResult??null,verificationReport:e.verificationReport??null,allowPartialScopeHash:e.allowPartialScopeHash??null,partialReason:e.partialReason??null,repairOverrideSignature:e.repairOverrideSignature??null,repairOverrideSummary:e.repairOverrideSummary??null}))}var Ak=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],q0=new Set(Ak),_k=new Set([...Ak,"minimum_runtime_version","revision"]),W0=new Set([..._k,"operation"]),z0=512*1024,Ap=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),J0=new Set([...Ap,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),ws=class extends Error{constructor(i){super(`Native transition for ${i} requires doctor migration before recovery`);this.change=i;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function Ue(e,t){return V0.join(H(e,t),"transition.json")}function G0(e){return`transition-${e}`}async function U0(e,t,i){let r=G0(t);return dr(e,r,i)}async function gn(e,t,i,r){let n=await U0(e,t,i);try{return await r()}finally{await fr(n)}}function fu(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function Tp(e,t){let i=Object.keys(e).find(r=>!t.has(r));if(i)throw new Error(`Native transition journal contains unknown field: ${i}`)}function du(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function bi(e,t){return uu(e,t)}function _p(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let i=e,r=Object.keys(i),n=r.find(u=>!J0.has(u)),a=[...Ap].find(u=>!Object.hasOwn(i,u)),o=Ap.size+(Object.hasOwn(i,"implementationScopeHash")?1:0)+(Object.hasOwn(i,"repairScopeHash")?1:0)+(Object.hasOwn(i,"repairStagnation")?1:0)+(Object.hasOwn(i,"returnToBuild")?1:0);if(n||a||r.length!==o)throw new Error(`Native transition journal event data keys are invalid${n?`: ${n}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(i.previousPhase)||!["shape","build","verify","archive"].includes(i.nextPhase))throw new Error("Native transition journal event phases are invalid");if(i.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if(i.returnToBuild!==void 0&&typeof i.returnToBuild!="boolean")throw new Error("Native transition journal returnToBuild flag is invalid");if(Ep(i.summary,"Native transition journal event summary"),$t(i.summary)!==i.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(i.artifacts)||i.artifacts.length>128||i.artifacts.some(u=>typeof u!="string"||u.length===0||Buffer.byteLength(u,"utf8")>512))throw new Error("Native transition journal event artifacts are invalid");if(i.noCodeReason!==null&&(Ep(i.noCodeReason,"Native transition journal event no-code reason"),$t(i.noCodeReason)!==i.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(i.verificationResult!==null&&i.verificationResult!=="pass"&&i.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(i,"implementationScopeHash")?i.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||i.previousPhase!=="build"&&i.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(i,"repairStagnation")?Cp(i.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(i.previousPhase!=="verify"||i.nextPhase!=="build"||i.verificationResult!=="fail")||!u&&(i.previousPhase!=="build"||i.nextPhase!=="verify"||i.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(i,"repairScopeHash")?i.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||i.previousPhase!=="build"&&i.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:t,summary:i.summary,artifacts:[...i.artifacts],noCodeReason:i.noCodeReason,verificationResult:i.verificationResult,...i.returnToBuild===!0?{returnToBuild:!0}:{},...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function K0(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let i=e,r=Object.keys(i),n=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(r.length===n.size&&r.every(a=>n.has(a))&&i.reason==="spec-rebase")return _p({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return _p(e,t)}function Ip(e,t,i=!1){if(e.change!==t)throw new Error("Native transition journal change mismatch");if(typeof e.id!="string"||e.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof e.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(e.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native transition journal timestamp is invalid");let r=i?K0(e.eventData,e.evidenceHash):_p(e.eventData,e.evidenceHash),n=Er(e.nextRun),a=e.previousRun===null?null:Er(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:r}}function kk(e,t,i=!1){if(e.skill!==Ni.definition.metadata.name||(i?!Nk(e):e.skillVersion!==Ni.definition.metadata.version||e.skillHash!==gs)||e.orchestration!==Ni.definition.orchestration.mode||e.pendingRef!==Nt.pendingRef||e.trajectoryRef!==Nt.trajectoryRef||e.contextRef!==Nt.contextRef||e.artifactsRef!==Nt.artifactsRef||e.checkpointRef!==Nt.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function Sk(e){return{runId:e.runId,skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash,orchestration:e.orchestration,pendingRef:e.pendingRef,trajectoryRef:e.trajectoryRef,contextRef:e.contextRef,artifactsRef:e.artifactsRef,checkpointRef:e.checkpointRef,retries:e.retries}}function Ek(e,t){if(e.status!=="running")throw new Error(`Native transition journal ${t} status must be running`);if(e.pending!==null)throw new Error(`Native transition journal ${t} pending action must be null`)}function jp(e,t,i,r=!1,n="advance"){let{previousRun:a,nextRun:o}=i;if(kk(o,"next Run",r||a!==null),Ek(o,"next Run"),o.runId!==t.run_id||o.currentStep!==t.phase)throw new Error("Native transition journal next Run does not match the next change state");if(n==="runtime-rebuild"){if(a!==null||e.phase==="shape"||t.phase!=="build"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native Runtime rebuild Run transition is invalid");return}if(a===null){if(e.run_id!==null||e.phase!=="shape"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native transition journal first Run transition is invalid");return}if(kk(a,"previous Run",!0),Ek(a,"previous Run"),e.run_id!==a.runId||a.currentStep!==e.phase||t.run_id!==a.runId)throw new Error("Native transition journal previous Run does not match the change state");if(o.iteration!==a.iteration+1)throw new Error("Native transition journal next Run iteration must advance exactly once");if(!uu(Sk(a),Sk(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function Y0(e,t,i){return L(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function Tk(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function Pk(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function $p(e,t,i,r,n=!1){let a=i.eventData,o=Pk(e),s=Pk(t);if(a.previousPhase!==e.phase||a.nextPhase!==t.phase)throw new Error("Native transition journal event phases do not match its states");if(e.archived||t.archived)throw new Error("Native transition journal cannot mutate an archived change");if(r==="runtime-rebuild"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&uu(e.spec_changes,t.spec_changes);if(e.phase==="shape"||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||!c||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native Runtime rebuild transition semantics are invalid");return}if(r==="evidence-retreat"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&e.run_id===t.run_id&&uu(e.spec_changes,t.spec_changes),l=bk({summary:a.summary,...a.returnToBuild?{returnToBuild:!0}:{}});if(!(e.phase==="archive"&&e.verification_result==="pass"||e.phase==="verify"&&e.verification_result==="pending")||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||i.evidenceHash!==l||!c||o===null||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native transition journal evidence retreat semantics are invalid");return}if(r==="spec-rebase"){let c=Y0(e.name,a.summary,t.spec_changes),l=L(`spec-rebase:${e.name}:${a.summary}`);if(e.phase==="shape"||t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||t.verification_report!==null||!n&&i.evidenceHash!==c||n&&i.evidenceHash!==c&&i.evidenceHash!==l||"implementation_scope"in t&&(t.implementation_scope!==null||t.verification_evidence!==null||t.partial_allowance!==null))throw new Error("Native transition journal spec rebase semantics are invalid");return}if(e.phase==="shape"){if(t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!=="pending"||t.verification_result!=="pending"||e.verification_report!==null||t.verification_report!==null||o!==null&&s!==null&&(o.implementation_scope!==null||o.verification_evidence!==null||o.partial_allowance!==null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null))throw new Error("Native transition journal Shape to Build semantics are invalid");return}if(e.phase==="build"){if(t.phase!=="verify"||a.verificationResult!==null||a.artifacts.length===0&&a.noCodeReason===null||t.verification_result!=="pending"||t.verification_report!==null||o!==null&&s!==null&&(s.implementation_scope===null||s.verification_evidence!==null||s.implementation_scope!==o.implementation_scope&&s.partial_allowance!==null&&s.partial_allowance===o.partial_allowance))throw new Error("Native transition journal Build to Verify semantics are invalid");return}if(e.phase==="verify"){let c=a.verificationResult==="pass"?"archive":"build";if(a.verificationResult!=="pass"&&a.verificationResult!=="fail"||t.phase!==c||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!==a.verificationResult||t.verification_report===null||o!==null&&s!==null&&(o.implementation_scope===null||s.implementation_scope!==o.implementation_scope||s.partial_allowance!==o.partial_allowance||o.verification_evidence!==null||s.verification_evidence===null))throw new Error("Native transition journal Verify outcome semantics are invalid");return}throw new Error("Native transition journal cannot advance from Archive")}function Op(e,t){let i=fu(e);if(Tp(i,W0),i.schema!==pr)throw new Error(`Expected Native transition schema ${pr}`);let r=du(i.minimum_runtime_version,"Native transition minimum_runtime_version");if(r>3)throw new Error(`Native transition requires runtime protocol ${r}; current protocol is ${3}`);if(r!==3)throw new Error(`Native transition ${pr} minimum_runtime_version must be ${3}`);let n=du(i.revision,"Native transition revision");if(n!==1)throw new Error("Native transition journal revision must be 1");if(i.operation!=="advance"&&i.operation!=="spec-rebase"&&i.operation!=="evidence-retreat"&&i.operation!=="runtime-rebuild")throw new Error("Native transition journal operation is invalid");let a=Ip(i,t),o=lt(i.previousState),s=lt(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if($p(o,s,a,i.operation),jp(o,s,a,!1,i.operation),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:pr,minimum_runtime_version:3,revision:n,operation:i.operation,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function X0(e,t){let i=fu(e);if(Tp(i,q0),i.schema!==an)throw new Error(`Expected Native transition schema ${an}`);let r=Ip(i,t,!0),n=on(i.previousState),a=on(i.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return $p(n,a,r,Tk(n,a,r.eventData),!0),jp(n,a,r,!0),{schema:an,id:r.id,change:t,evidenceHash:r.evidenceHash,createdAt:r.createdAt,previousState:n,nextState:a,previousRun:r.previousRun,nextRun:r.nextRun,eventData:r.eventData}}function Hp(e,t){let i=fu(e);if(Tp(i,_k),i.schema!==Ti)throw new Error(`Expected Native transition schema ${Ti}`);if(du(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${Ti} minimum_runtime_version must be 2`);let n=du(i.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=Ip(i,t,!0),o=di(i.previousState),s=di(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if($p(o,s,a,Tk(o,s,a.eventData),!0),jp(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:Ti,minimum_runtime_version:2,revision:n,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function Q0(e,t){let i=fu(e);if(i.schema===pr)return{status:"current",journal:Op(i,t)};if(i.schema===an)return{status:"migration-required",journal:X0(i,t)};if(i.schema===Ti)return{status:"migration-required",journal:Hp(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function Dp(e,t){let i=Ue(e,t),r=j(e,i);await T(r,i);try{let n=await re({root:r,file:i,maxBytes:z0,label:`Native transition journal ${t}`});return Q0(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Mi(e,t){let i=await Dp(e,t);if(!i)return null;if(i.status==="migration-required")throw new ws(t);return i.journal}function Rk(e,t){if(bi(e,t.nextRun))return"next";if(t.previousRun===null){if(e===null)return"previous"}else if(bi(e,t.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${t.change}; recovery journal was preserved`)}function Ck(e,t){if(bi(e,t.nextState))return"next";if(bi(e,t.previousState))return"previous";throw new Error(`Native transition change content changed for ${t.change}; recovery journal was preserved`)}function Z0(e){let{journal:t}=e;return Ik({sequence:e.sequence,timestamp:t.createdAt,type:e.type,runId:t.nextRun.runId,data:e.type==="run_started"?{runtime:"comet-native",phase:t.previousState.phase,transitionId:t.id}:{...t.eventData,transitionId:t.id}})}function Ik(e){return{sequence:e.sequence,timestamp:e.timestamp,type:e.type,runId:e.runId,data:e.data}}function xk(e,t){let i=e.map((a,o)=>({event:a,index:o})).filter(({event:a})=>a.data.transitionId===t.id),r=i.filter(({event:a})=>a.type==="run_started"),n=i.filter(({event:a})=>a.type==="state_transitioned");if(i.length!==r.length+n.length||r.length>(t.previousRun===null?1:0)||n.length>1||t.previousRun===null&&n.length===1&&(r.length!==1||r[0].index>=n[0].index))throw new Error(`Native trajectory transition id collision for ${t.change}; recovery journal was preserved`);for(let a of[...r,...n]){let o=Z0({sequence:a.index+1,journal:t,type:a.event.type});if(!bi(Ik(a.event),o))throw new Error(`Native trajectory event changed for transition ${t.id}; recovery journal was preserved`)}return{started:r[0]?.event??null,transitioned:n[0]?.event??null}}async function hu(e,t,i){if(await pa(e,t))throw new Error(`Native schema migration is incomplete for ${t}; run doctor --repair`);await Wl(e,t);let r=await Mi(e,t);if(!r)return null;let n=H(e,t),a=xk(await it(n,r.nextRun.trajectoryRef),r),[o,s]=await Promise.all([$e(n),He(e,t)]),c=Rk(o,r),l=Ck(s,r);if((a.started||a.transitioned)&&(c!=="next"||l!=="next"))throw new Error(`Native trajectory is ahead of transition state for ${r.change}; recovery journal was preserved`);if(c==="previous"&&(await un(n,r.nextRun),await i?.afterRunStateWritten?.(r)),!bi(await $e(n),r.nextRun))throw new Error(`Native transition Run content changed while continuing ${r.change}; recovery journal was preserved`);if(l==="previous"){let p=await Ql(e,r.nextState,r.previousState.revision);if(!bi(p,r.nextState))throw new Error(`Native transition change write diverged for ${r.change}; recovery journal was preserved`);await i?.afterChangeStateWritten?.(r)}if(!bi(await He(e,t),r.nextState))throw new Error(`Native transition change content changed while continuing ${r.change}; recovery journal was preserved`);let u=await Mi(e,t);if(!u||!bi(u,r))throw new Error(`Native transition journal changed while continuing ${r.change}; it was preserved`);let d=xk(await it(n,r.nextRun.trajectoryRef),r);r.previousRun===null&&(d.started||await Tr({changeDir:n,run:r.nextRun,type:"run_started",data:{runtime:"comet-native",phase:r.previousState.phase,transitionId:r.id},now:new Date(r.createdAt)}));let f=d.transitioned;f||(f=await Tr({changeDir:n,run:r.nextRun,type:"state_transitioned",data:{...r.eventData,transitionId:r.id},now:new Date(r.createdAt)})),await vn({changeDir:n,run:r.nextRun,trajectoryOffset:f.sequence,evidenceHash:r.evidenceHash,now:new Date(r.createdAt)});let[h,v]=await Promise.all([$e(n),He(e,t)]);Rk(h,{...r,previousRun:r.nextRun}),Ck(v,{...r,previousState:r.nextState});let m=await Mi(e,t);if(!m||!bi(m,r))throw new Error(`Native transition journal changed while continuing ${r.change}; it was not removed`);return await B0.rm(Ue(e,t),{force:!0}),r.nextState}async function jk(e,t,i){return se(e,`continue transition ${t}`,()=>gn(e,t,`continue transition ${t}`,()=>hu(e,t,i)))}import $k from"node:path";var eH="comet.native.contract.v1",tH="comet.native.acceptance-set.v1",Ok=/^[a-f0-9]{64}$/u,ys={maxAcceptanceCriteria:Do.maxCriteria};function Hk(e,t){let i=$k.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||$k.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized project-relative ref`);return e}function Dk(e){return D("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
205
- `))}function iH(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.capability))throw new Error(`Invalid Native contract capability: ${e.capability}`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Invalid Native contract operation for ${e.capability}`);if(e.operation==="remove"){if(e.source!==null||e.markdown!==null||!e.baseHash?.match(Ok))throw new Error(`Remove contract ${e.capability} requires only a base hash`);return{snapshot:{capability:e.capability,operation:"remove",source:null,baseHash:e.baseHash,contentHash:null},markdown:null}}if(e.source===null||e.markdown===null)throw new Error(`${e.operation} contract ${e.capability} requires source content`);if(e.operation==="create"&&e.baseHash!==null)throw new Error(`Create contract ${e.capability} requires a null base hash`);if(e.operation==="replace"&&!e.baseHash?.match(Ok))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=Hk(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:Dk(e.markdown)},markdown:e.markdown}}function rH(e,t){return Lk(e.id,t.id)}function Lk(e,t){return e<t?-1:e>t?1:0}function Mk(e){let t=Hk(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(iH).sort((d,f)=>Lk(d.snapshot.capability,f.snapshot.capability)),r=i.map(({snapshot:d})=>d.capability);if(new Set(r).size!==r.length)throw new Error("Native contract contains duplicate capabilities");let n=[t,...i.flatMap(({snapshot:d})=>d.source===null?[]:[d.source])];if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate artifact sources");let a=dl(e.briefMarkdown,t,ys.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(...fl(f,d.source,ys.maxAcceptanceCriteria-a.length)),a.push(...Ay(f,d.source,ys.maxAcceptanceCriteria-a.length)));if(a.sort(rH),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>ys.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${ys.maxAcceptanceCriteria}-criterion acceptance budget`);let o=a.map(({id:d})=>d);if(new Set(o).size!==o.length)throw new Error("Native contract contains duplicate acceptance criteria");let s={source:t,contentHash:Dk(e.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=D(tH,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:D(eH,u)}}var pu={maxSpecs:64,maxFileBytes:So,maxTotalBytes:4*1024*1024};async function Ca(e){if(e.specChanges.length>pu.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await Z({root:e.changeDir,ref:e.briefRef,maxBytes:pu.maxFileBytes}),i=t.size,r=[];for(let n of e.specChanges){if(n.operation==="remove"){r.push({capability:n.capability,operation:"remove",source:null,baseHash:n.base_hash,markdown:null});continue}if(!n.source)throw new Error(`Native contract ${n.capability} has no proposed spec source`);let a=await Z({root:e.changeDir,ref:n.source,maxBytes:pu.maxFileBytes});if(i+=a.size,i>pu.maxTotalBytes)throw new Error("Native contract exceeds its total byte budget");r.push({capability:n.capability,operation:n.operation,source:a.ref,baseHash:n.base_hash,markdown:a.text})}return{contract:Mk({briefSource:t.ref,briefMarkdown:t.text,specs:r}),sourceCount:r.filter(n=>n.source!==null).length+1,totalBytes:i}}import{execFile as kH}from"node:child_process";import{promisify as SH}from"node:util";var IJ=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");import{promises as uH}from"fs";import xa from"path";var jr={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},Aa=/^[a-f0-9]{64}$/u;function mu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function vu(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function Ir(e,t,i=2e3){if(typeof e!="string"||e.length===0||e.length>i)throw new Error(`${t} must be a non-empty string of at most ${i} characters`);return e}function Fk(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Lp(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function nH(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||xa.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=xa.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function Mp(e,t){return xa.join(H(e,t),"checkpoints","progress.json")}function $r(e,t){return xa.join(H(e,t),"checkpoint-journal.json")}function Fp(e,t,i){if(!Aa.test(i))throw new Error("Native checkpoint manifest hash is invalid");return xa.join(H(e,t),"checkpoints","manifests",`${i}.json`)}function aH(e){if(!Aa.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function Bp(e,t,i){let r=await re({root:e,file:t,maxBytes:jr.maxDocumentBytes,label:i});return JSON.parse(r.bytes.toString("utf8"))}function oH(e,t){let i=mu(e,`checkpoint manifest artifact ${t}`);vu(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let r=nH(Ir(i.path,`checkpoint artifact ${t} path`,4096)),n=ci(r);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${r}`);if(typeof i.hash!="string"||!Aa.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:r,hash:i.hash,size:Lp(i.size,`checkpoint artifact ${t} size`)}}function gu(e,t){let i=mu(e,"Native checkpoint manifest");if(vu(i,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),i.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(i.change!==t)throw new Error("Native checkpoint manifest change mismatch");if(!Array.isArray(i.artifacts))throw new Error("Native checkpoint manifest artifacts must be an array");if(i.artifacts.length>jr.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let r=i.artifacts.map(oH),n=[...r].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(r)!==JSON.stringify(n))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(r.map(o=>o.path)).size!==r.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=Lp(i.totalBytes,"checkpoint manifest totalBytes");if(r.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");if(a>jr.maxTotalBytes)throw new Error("Native checkpoint manifest totalBytes exceeds its budget");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:r,totalBytes:a}}function Vp(e){return L(JSON.stringify(gu(e,e.change)))}function qp(e,t){let i=mu(e,"Native progress checkpoint");if(vu(i,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),i.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(i.change!==t)throw new Error("Native checkpoint change mismatch");let r=i.phase;if(r!=="shape"&&r!=="build"&&r!=="verify"&&r!=="archive")throw new Error("Native checkpoint phase is invalid");let n=Fk(i.previousRevision,"Native checkpoint previousRevision"),a=Fk(i.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=Ir(i.manifestHash,"Native checkpoint manifestHash",64);if(!Aa.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=aH(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=Ir(i.inputHash,"Native checkpoint inputHash",64);if(!Aa.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=Ir(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=Lp(i.artifactCount,"Native checkpoint artifactCount");if(u>jr.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=Ir(i.summary,"Native checkpoint summary"),f=Ir(i.nextAction,"Native checkpoint nextAction");if($t(d)!==d||$t(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:Ir(i.id,"Native checkpoint id",128),change:t,phase:r,previousRevision:n,stateRevision:a,summary:d,nextAction:f,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function sH(e,t){let i=mu(e,"Native checkpoint journal");if(vu(i,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),i.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(i.change!==t)throw new Error("Native checkpoint journal change mismatch");let r=lt(i.previousState),n=lt(i.nextState),a=qp(i.checkpoint,t),o=gu(i.manifest,t),s=Ir(i.inputHash,"Native checkpoint journal inputHash",64),c=L(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!Aa.test(s)||s!==a.inputHash||s!==c||i.id!==a.id||i.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(r.name!==t||n.name!==t||n.revision!==r.revision+1||a.previousRevision!==r.revision||a.stateRevision!==n.revision||a.phase!==n.phase||a.manifestHash!==Vp(o)||a.artifactCount!==o.artifacts.length)throw new Error("Native checkpoint journal state mismatch");return{schema:"comet.native.checkpoint-journal.v1",id:a.id,change:t,inputHash:s,createdAt:a.createdAt,previousState:r,nextState:n,checkpoint:a,manifest:o}}async function cH(e,t,i){let r=xa.resolve(e.projectRoot,...t.split("/"));if(!O(e.projectRoot,r)||O(e.nativeRoot,r)||O(e.runtimeDir,r))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=Kf(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await re({root:e.projectRoot,file:r,maxBytes:jr.maxFileBytes,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot,e.runtimeDir],hooks:{afterParentChainCaptured:()=>i?.afterParentChainCaptured?.(t),afterOpen:()=>i?.afterOpen?.(t),beforeRead:()=>i?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function lH(e,t){let i=Mp(e,t),r=j(e,i);await T(r,i);try{return qp(await Bp(r,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Wp(e,t,i){let r=Fp(e,t,i),n=j(e,r);await T(n,r);let a=await Bp(n,r,"Native checkpoint manifest"),o=gu(a,t);if(zp(e,o),Vp(o)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function Or(e,t){let i=$r(e,t),r=j(e,i);await T(r,i);try{let n=sH(await Bp(r,i,"Native checkpoint journal"),t);return zp(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Bk(e,t,i,r){let n=gu(i,t);zp(e,n);let a=Vp(n),o=Fp(e,t,a),s=j(e,o);await T(s,o);try{let c=await Wp(e,t,a);if(JSON.stringify(c)!==JSON.stringify(n))throw new Error("Native checkpoint manifest hash collision")}catch(c){if(c.code!=="ENOENT")throw c}return await ee(o,n,{containedRoot:s,beforeCommit:r?.beforeCommit}),a}function zp(e,t){for(let i of t.artifacts){let r=Kf(e,i.path);if(r)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${r}): ${i.path}`)}}async function Vk(e,t){let i=qp(t,t.change),r=await Wp(e,i.change,i.manifestHash),n=L(JSON.stringify({summary:i.summary,nextAction:i.nextAction,artifacts:r.artifacts}));if(i.inputHash!==n||i.artifactCount!==r.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");let a=Mp(e,t.change),o=j(e,a);await T(o,a),await ee(a,i,{containedRoot:o})}async function qk(e){let t;try{t=await lH(e.paths,e.name)}catch(a){return{checkpoint:null,manifest:null,freshness:"stale",reasons:["checkpoint-progress-invalid"],findings:[{code:"checkpoint-progress-invalid",message:`Native progress checkpoint is invalid: ${a.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint file aside before retrying`,path:Mp(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let i=[],r=[];t.stateRevision!==e.stateRevision&&i.push("state-revision-changed");let n=null;try{n=await Wp(e.paths,e.name,t.manifestHash);let a=L(JSON.stringify({summary:t.summary,nextAction:t.nextAction,artifacts:n.artifacts}));if(t.inputHash!==a||t.artifactCount!==n.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");for(let o of n.artifacts)try{let s=await cH(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&i.push(`artifact-changed:${o.path}`)}catch{i.push(`artifact-unavailable:${o.path}`)}}catch(a){i.push("checkpoint-manifest-invalid"),r.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:Fp(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:i.length===0?"fresh":"stale",reasons:i,findings:r}}async function Wk(e,t,i){let r=await Or(e,t);if(!r)return null;if(await Bk(e,r.change,r.manifest)!==r.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await Ql(e,r.nextState,r.previousState.revision,{allowPendingCheckpointRecovery:!0}),await i?.afterStateWritten?.(r),await Vk(e,r.checkpoint),await i?.afterProgressWritten?.(r),await uH.rm($r(e,t),{force:!0}),r}async function zk(e,t,i){return se(e,`continue checkpoint ${t}`,()=>gn(e,t,`continue checkpoint ${t}`,async()=>(await hu(e,t),Wk(e,t,i))))}import{constants as Jp,promises as Ot}from"node:fs";import _a from"node:path";var dH=/^[a-f0-9]{64}$/u,fH=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,Ns=512*1024;function hH(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function wu(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return vt(i,r)?z(i,r):z(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function pH(e,t){let i=_a.resolve(e),r=_a.resolve(t);if(!O(i,r))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=i;for(let o of["",..._a.relative(i,r).split(_a.sep).filter(Boolean)]){o&&(a=_a.join(a,o));let s=await Ot.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await Ot.realpath(a);if(n.length>0&&!O(n[0].realPath,c))throw new Error("Native check receipt parent resolves outside the Native root");n.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs})}return n}async function Jk(e){for(let t of e){let i=await Ot.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!hH(t,i)||await Ot.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function mH(e){if(!dH.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function vH(e){let t=fH.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function gH(e,t,i){return lr(H(e,t),mH(i))}async function wH(e,t,i){let r=await pH(i,_a.dirname(e)),n=await Ot.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(n.size>Ns)throw new Error(`Native check receipt exceeds ${Ns} bytes`);let[a,o]=await Promise.all([Ot.realpath(t),Ot.realpath(e)]);if(!O(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":Jp.O_RDONLY|Jp.O_NOFOLLOW|Jp.O_NONBLOCK,c=await Ot.open(e,s).catch(l=>{throw l.code==="ELOOP"||l.code==="ENXIO"?new Error("Native check receipt became unsafe while opening"):l});try{let[l,u,d]=await Promise.all([c.stat(),Ot.lstat(e),Ot.realpath(e)]);if(await Jk(r),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!wu(n,l)||!wu(l,u))throw new Error("Native check receipt changed while opening");let f=[],h=0,v=Buffer.allocUnsafe(16*1024);for(;;){let g=Ns+1-h,y=await c.read(v,0,Math.min(v.length,g),null);if(y.bytesRead===0)break;if(h+=y.bytesRead,h>Ns)throw new Error(`Native check receipt exceeds ${Ns} bytes`);f.push(Buffer.from(v.subarray(0,y.bytesRead)))}let[m,p,b]=await Promise.all([c.stat(),Ot.lstat(e),Ot.realpath(e)]);if(await Jk(r),!p.isFile()||p.isSymbolicLink()||b!==o||!O(a,b)||!wu(l,m)||!wu(l,p))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,h).toString("utf8"))}finally{await c.close()}}async function Gk(e,t,i){let r=vH(i),n=H(e,t),a=gH(e,t,r),o=j(e,a);await T(o,a);let s=nu(await wH(a,n,o));if(s.change!==t||s.receiptHash!==r)throw new Error("Native check receipt ref/hash/change mismatch");return s}var bs=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var CG=64*1024;var xG=3600*1e3;var AG=SH(kH);var EH=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function Uk(e,t){let i=[];for(let r of EH){let n=e.bindings[r],a=t[r];n!==a&&i.push(`${r}: expected ${JSON.stringify(a)}, got ${JSON.stringify(n)}`)}return{ok:i.length===0,mismatches:i}}async function Kk(e){if(e.receipt.kind!=="static-inspection")return null;let t=await Gk(e.paths,e.state.name,e.receipt.evidence.checkReceiptRef);if(t.receiptHash!==e.receipt.evidence.checkReceiptHash)throw new Error("Native static receipt dependency hash mismatch");return t}var Hr=class extends Error{details;constructor(t){let i=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(r=>`${r.ref}${r.acceptanceId?`[${r.acceptanceId}]`:""} -> ${r.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=t}};function PH(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}async function RH(e){let t=PH(e.bundle.baseline),i=await qh(e.paths,t,{origin:"explicit",now:e.now});return hp({baseline:t,current:i,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason,externalDrift:e.bundle.authority.externalDrift}).scope.currentProjectionHash}async function Xk(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await ps(e.paths,e.state.name,e.state.implementation_scope),i=await Ca({changeDir:ne(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),r=await RH({paths:e.paths,bundle:t,now:e.now}),n=[];return i.contract.contractHash!==t.scope.contractHash&&n.push("verification-contract-stale"),r!==t.scope.currentProjectionHash&&n.push("verification-implementation-stale"),{bundle:t,contract:i.contract,contractHash:i.contract.contractHash,acceptanceHash:i.contract.acceptanceHash,findingCodes:n}}async function Qk(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await Xk(e),i=[...new Set(t.findingCodes)].sort();return{freshness:i.length===0?"fresh":"stale",findingCodes:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"]}}}async function CH(e){let t=await Z({root:ne(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:Ty(t.text)}}function xH(e){let{receipt:t,implementationScope:i}=e,r=[],n=fp({baseline:i.baseline,current:i.current,declaredArtifacts:i.scope.declaredArtifacts}).filter(o=>o.attributedTo.length>0&&o.after!==null),a=n.reduce((o,s)=>o+s.after.size,0);return(t.stale||t.sourceRevision!==e.sourceRevision||t.contract.expectedHash!==e.contractHash||t.contract.beforeHash!==e.contractHash||t.contract.afterHash!==e.contractHash||t.implementation.scopeHash!==i.scope.scopeHash||t.implementation.expectedSnapshotHash!==i.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==i.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==i.scope.currentProjectionHash||t.counts.filesSelected!==n.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==n.length||t.counts.bytesScanned!==a))&&r.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&r.push("verification-receipt-outcome-mismatch"),r}function AH(e){return{change:e.state.name,sourceRevision:e.sourceRevision??e.state.revision,contractHash:e.contractHash,scopeHash:e.implementationScope.scope.scopeHash,snapshotHash:e.implementationScope.scope.currentProjectionHash,artifactHash:Np(e.implementationScope.scope.declaredArtifacts)}}async function Yk(e){let t=await ms(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let r=Uk(t,e.expectedBindings);if(i.push(...r.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&i.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),i.length>0)throw new Hr([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:i}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let n=await Kk({paths:e.paths,state:e.state,receipt:t});if(n){let a=xH({receipt:n,sourceRevision:e.expectedBindings.sourceRevision,result:e.result,contractHash:e.contractHash,implementationScope:e.implementationScope});if(a.length>0)throw new Error(`Native static receipt dependency is invalid: ${a.join(", ")}`)}return t}async function _H(e){let t=AH({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let r of e.requiredReceiptRefs){let n=await Yk({...e,ref:r,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof Hr)return i.push(...a.details),null;throw a});if(n!==null&&n.kind!=="static-inspection")throw new Error("Native required-check evidence must be a static-inspection receipt")}for(let r of e.trace.entries)if(r.status!=="missing")for(let n of r.evidenceRefs){let a=await Yk({...e,result:r.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:r.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof Hr)return i.push(...o.details),null;throw o});if(a!==null){if(a.kind!=="automated-check"&&a.kind!=="manual-evidence")throw new Error("Native acceptance evidence must be automated-check or manual-evidence");if(r.status==="failed"&&a.status==="passed")throw new Error("Native failed acceptance evidence must reference a non-passing receipt")}}if(i.length>0)throw new Hr(i)}function Gp(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function yu(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:Gp(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([Xk(e),Pa(e.paths,e.state.name,e.state.verification_evidence)]);if(i.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:Gp(e.state.verification_result,"stale"),envelope:null};let r=await CH({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),n=[...t.findingCodes];(r.hash!==i.reportHash||r.ref!==i.reportRef)&&n.push("verification-report-stale"),(i.result!==e.state.verification_result||i.implementationScopeRef!==e.state.implementation_scope||i.partialAllowanceRef!==e.state.partial_allowance||i.sourceRevision>=e.state.revision||i.contractHash!==t.bundle.scope.contractHash||i.acceptanceCriteriaHash!==t.acceptanceHash)&&n.push("verification-state-mismatch");try{await _H({paths:e.paths,state:e.state,result:i.result,trace:i.acceptanceTrace,requiredReceiptRefs:i.requiredReceiptRefs,contractHash:i.contractHash,implementationScope:t.bundle,sourceRevision:i.sourceRevision})}catch{n.push("verification-receipt-invalid")}let a=[...new Set(n)].sort(),o=a.length>0?"stale":i.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:i.contractHash,acceptanceHash:i.acceptanceCriteriaHash,implementationScopeHash:i.implementationScopeHash,reportHash:i.reportHash,envelopeHash:i.envelopeHash,partialAllowanceHash:i.partialAllowanceHash,skippedAcceptanceCount:i.acceptanceTrace.skipped},envelope:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:Gp(e.state.verification_result,"invalid"),envelope:null}}}function IH(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function eS(e){try{return await TH.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function jH(e,t){try{return(await Z({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function $H(e,t,i){let r=Zl(e,i.capability);if(!O(e.nativeRoot,r))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let n=Zk.relative(e.nativeRoot,r).replaceAll("\\","/"),a=await jH(e.nativeRoot,n),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await Z({root:ne(e,t),ref:i.source})).hash}return{capability:i.capability,operation:i.operation,expectedBaseHash:i.operation==="create"?null:i.base_hash,actualBaseHash:a,proposedHash:o}}async function OH(e,t){return eS(Ue(e,t))}async function Nu(e){let t=e.now??new Date,i=await He(e.paths,e.name),r=await kt(e.paths,e.name),n=await ye(e.paths.projectRoot),a=IH(i.name,t),o=Zk.resolve(e.paths.nativeRoot,...a.split("/"));if(!O(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,f,h]=await Promise.all([Promise.all(i.spec_changes.map(v=>$H(e.paths,i.name,v))),yu({paths:e.paths,state:i,now:t}),cu(e.paths,i.name),pa(e.paths,i.name),ma(e.paths,i.name),OH(e.paths,i.name),eS(o)]);return yb({change:i.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:i.schema,revision:i.revision,phase:i.phase,archived:i.archived,pendingJournal:u||d||f,targetRef:a,targetExists:h,specs:s,evidence:c.evidence,workspace:r?.schema==="comet.native.workspace.v3"?{schema:r.schema,isolation:r.isolation,changeBranch:r.changeBranch,targetBranch:r.targetBranch,finish:r.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}import{promises as Up}from"node:fs";import Fi from"node:path";var HH="comet.native.archive-tree.v1",DH={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};function rS(e){let t={...DH,...e};for(let[i,r]of Object.entries(t))if(!Number.isSafeInteger(r)||r<=0)throw new Error(`Native Archive content limit ${i} must be a positive safe integer`);return t}function tS(e){return JSON.stringify(e.map(t=>({name:t.name,kind:t.isDirectory()?"directory":t.isFile()?"file":t.isSymbolicLink()?"symlink":"other"})).sort((t,i)=>t.name.localeCompare(i.name)))}function iS(e,t,i,r){if(i.entryCount+=1,i.entryCount>r.maxEntries)throw new Error(`Native Archive content exceeds ${r.maxEntries} entries`);if(Buffer.byteLength(t.ref,"utf8")>r.maxRefBytes)throw new Error(`Native Archive content ref exceeds ${r.maxRefBytes} bytes: ${t.ref}`);let n=Buffer.byteLength(JSON.stringify(t),"utf8");if(i.manifestBytes+=n+(e.length===0?0:1),i.manifestBytes+2>r.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${r.maxManifestBytes} bytes`);e.push(t)}async function nS(e,t,i,r,n,a){if(a>n.maxDepth)throw new Error(`Native Archive content exceeds depth ${n.maxDepth}`);let o=await wt({root:e,directory:t,label:`Native Archive content directory ${Fi.relative(e,t)||"."}`,maxEntries:n.maxEntries}),s=tS(o.entries),c=[...o.entries];c.sort((u,d)=>u.name.localeCompare(d.name));for(let u of c){await o.verify();let d=Fi.join(t,u.name),f=Fi.relative(e,d).replaceAll("\\","/"),h=await Up.lstat(d);if(u.isSymbolicLink()||h.isSymbolicLink())throw new Error(`Native Archive content must not contain symlinks or junctions: ${f}`);if(u.isDirectory()&&h.isDirectory()){iS(i,{ref:f,kind:"directory"},r,n),await nS(e,d,i,r,n,a+1);continue}if(!u.isFile()||!h.isFile())throw new Error(`Native Archive content must contain only files and directories: ${f}`);let v=await re({root:e,file:d,maxBytes:n.maxFileBytes,label:`Native Archive content file ${f}`});if(r.totalBytes+=v.size,r.totalBytes>n.maxTotalBytes)throw new Error(`Native Archive content exceeds ${n.maxTotalBytes} total file bytes`);iS(i,{ref:f,kind:"file",hash:v.hash,size:v.size},r,n),await o.verify()}await o.verify();let l=await wt({root:e,directory:t,label:`Native Archive content directory ${Fi.relative(e,t)||"."}`,maxEntries:n.maxEntries});if(tS(l.entries)!==s)throw new Error(`Native Archive content directory changed while reading: ${Fi.relative(e,t)||"."}`);await Promise.all([o.verify(),l.verify()])}async function aS(e,t={}){let i=rS(t);e=Fi.resolve(e);let r=await Up.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`Native Archive move source must be a real directory: ${e}`);let n=[];await nS(e,e,n,{entryCount:0,totalBytes:0,manifestBytes:0},i,0);let o=JSON.stringify(n);if(Buffer.byteLength(o,"utf8")>i.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${i.maxManifestBytes} bytes`);return L(`${HH}\0${o}`)}async function ni(e,t={}){let i=rS(t);e=Fi.resolve(e);let r;try{r=await Up.lstat(e)}catch(n){if(n.code==="ENOENT")return null;throw n}if(r.isSymbolicLink())throw new Error(`Native Archive transaction path must not be a symlink or junction: ${e}`);if(r.isFile())return{kind:"file",hash:(await re({root:Fi.dirname(e),file:e,maxBytes:i.maxFileBytes,label:`Native Archive transaction file ${Fi.basename(e)}`})).hash};if(r.isDirectory())return{kind:"directory",hash:await aS(e,i)};throw new Error(`Native Archive transaction path has an unsupported file type: ${e}`)}import{promises as rt}from"node:fs";import xe from"node:path";var Yp=16*1024*1024,LH=256*1024,MH=16*1024,ks="comet.native.archive-cas.v1";function FH(e,t){let i="runtime/",r=t.startsWith(i),n=r?e.runtimeDir:e.nativeRoot,a=r?t.slice(i.length):t,o=xe.resolve(n,...a.split("/"));if(!O(n,o))throw new Error(`Unsafe Native Archive transaction ref: ${t}`);return o}async function De(e,t){let i=FH(e,t);return T(j(e,i),i)}function Dr(e,t,i="file"){return t===null?e===null:e?.kind===i&&e.hash===t}function Ta(e){return e===null?"missing":`${e.kind}:${e.hash}`}async function ft(e){let t=await ni(e.target);if(!Dr(t,e.expectedHash,e.expectedKind))throw new Error(`${e.label} content changed: expected ${e.expectedHash??"missing"}, got ${Ta(t)}`);return t}async function Xp(e,t){let i=await hi(e,t),r=await re({root:e.runtimeDir,file:i.journal,maxBytes:LH,label:`Native Archive transaction journal ${t}`}),n=xl(JSON.parse(r.bytes.toString("utf8")));if(n.id!==t)throw new Error(`Invalid Native Archive transaction journal: ${t}`);return n}async function bu(e,t,i){let r=xl({...t,status:i}),n=await hi(e,r.id);return await ee(n.journal,r,{containedRoot:e.runtimeDir}),r}function ku(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}function oS(e){return{...ku(e),ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Lr(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs}function BH(e,t){return Lr(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function ie(e){try{return await rt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function ki(e){let t=await rt.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let i=oS(t),r=await re({root:j(e.paths,e.file),file:e.file,maxBytes:Yp,label:e.label}),n=await rt.lstat(e.file);if(!n.isFile()||n.isSymbolicLink()||!BH(i,oS(n))||r.hash!==e.expectedHash)throw new Error(`${e.label} content changed or object identity changed while binding`);return{identity:ku(n),size:r.size}}function VH(e,t,i,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Archive CAS ${t.id} ${i} record must be an object`);let n=e;if(Object.keys(n).sort().join(",")!=="hash,identity,operationId,role,schema")throw new Error(`Archive CAS ${t.id} ${i} record has an invalid shape`);let o=n.identity;if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`Archive CAS ${t.id} ${i} identity must be an object`);let s=o;if(Object.keys(s).sort().join(",")!=="birthtimeMs,dev,ino")throw new Error(`Archive CAS ${t.id} ${i} identity has an invalid shape`);for(let c of["dev","ino","birthtimeMs"])if(typeof s[c]!="number"||!Number.isFinite(s[c])||s[c]<0)throw new Error(`Archive CAS ${t.id} ${i} identity ${c} is invalid`);if(n.schema!==ks||n.operationId!==t.id||n.role!==i||n.hash!==r)throw new Error(`Archive CAS ${t.id} ${i} record is not transaction-bound`);return{schema:ks,operationId:t.id,role:i,hash:r,identity:{dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs}}}async function Si(e,t,i,r){let n=await hi(e,t.id),a=xe.join(n.backups,".cas"),o=`.${xe.basename(r)}.comet-archive-cas-${t.id}-${i.id}`,s={directory:a,originalRecord:xe.join(a,`${i.id}.original.json`),postRecord:xe.join(a,`${i.id}.post.json`),candidate:xe.join(a,`${i.id}.candidate`),originalQuarantine:xe.join(xe.dirname(r),`${o}.original`),rollbackQuarantine:xe.join(xe.dirname(r),`${o}.rollback`)};return await Promise.all(Object.values(s).map(c=>T(j(e,c),c))),s}async function Ht(e){if(!await ie(e.file))return null;let t=await re({root:e.paths.runtimeDir,file:e.file,maxBytes:MH,label:`Archive CAS ${e.operation.id} ${e.role} record`});return VH(JSON.parse(t.bytes.toString("utf8")),e.operation,e.role,e.expectedHash)}async function Su(e){let t=await Ht(e);if(t){if(!Lr(t.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} object identity changed`);return t}await fi({root:e.paths.runtimeDir,directory:xe.dirname(e.file),label:`Archive CAS ${e.operation.id} records`});let i={schema:ks,operationId:e.operation.id,role:e.role,hash:e.expectedHash,identity:e.identity};try{await ee(e.file,i,{containedRoot:e.paths.runtimeDir,exclusive:!0})}catch(n){if(n.code!=="EEXIST")throw n}let r=await Ht(e);if(!r||!Lr(r.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} record changed`);return r}async function Re(e){let t=await ki({paths:e.paths,file:e.file,expectedHash:e.record.hash,label:e.label});if(!Lr(e.record.identity,t.identity))throw new Error(`${e.label} object identity changed`)}async function qH(e){let t=await ki({paths:e.paths,file:e.file,expectedHash:e.expectedHash,label:e.label}),i=await Su({paths:e.paths,file:e.recordFile,operation:e.operation,role:e.role,expectedHash:e.expectedHash,identity:t.identity});return await Re({paths:e.paths,file:e.file,operation:e.operation,record:i,label:e.label}),i}async function WH(e){if(!await ie(e.quarantine)||await ie(e.target))return;let t=await Qt({root:j(e.paths,e.target),directory:xe.dirname(e.target),label:`Archive CAS ${e.operation.id} quarantine restoration`});await t.verify();try{await rt.link(e.quarantine,e.target)}catch(n){if(n.code==="EEXIST")return;throw n}await t.verify();let[i,r]=await Promise.all([rt.lstat(e.quarantine),rt.lstat(e.target)]);if(!Lr(ku(i),ku(r)))throw new Error(`Archive CAS ${e.operation.id} could not restore quarantined content`);await rt.unlink(e.quarantine),await t.verify()}async function uS(e){if(await ie(e.quarantine)){await Re({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`});return}let t=await Qt({root:j(e.paths,e.target),directory:xe.dirname(e.target),label:`Archive ${e.phase} target ${e.operation.target}`});await Re({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`}),await e.hooks?.afterArchiveTargetBound?.(e.phase,e.operation,e.target),await t.verify(),await Re({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`});try{await rt.rename(e.target,e.quarantine),await t.verify(),await Re({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`})}catch(i){throw await WH(e),new Error(`Archive ${e.phase} target ${e.operation.target} changed during quarantine`,{cause:i})}await e.hooks?.afterArchiveTargetQuarantined?.(e.phase,e.operation,e.quarantine)}async function wn(e){if(!await ie(e.file))return;await Re(e);let t=await Qt({root:j(e.paths,e.file),directory:xe.dirname(e.file),label:e.label});await t.verify(),await Re(e),await rt.unlink(e.file),await t.verify()}async function sS(e,t,i){if(!t.backup||t.expectedTargetHash===null)return;let r=await De(e,t.target),n=await De(e,t.backup),a=await ni(n);if(a!==null){if(!Dr(a,t.expectedTargetHash))throw new Error(`Archive transaction backup content changed: ${t.backup}`);return}await ft({target:r,expectedHash:t.expectedTargetHash,label:`Archive transaction target ${t.target}`}),await wr({sourceRoot:j(e,r),source:r,targetRoot:j(e,n),target:n,maxBytes:Yp,label:`Archive transaction backup ${t.backup}`,expectedHash:t.expectedTargetHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>i?.afterProtectedCopySourceParentCaptured?.("backup",t.target)}}),await ft({target:n,expectedHash:t.expectedTargetHash,label:`Archive transaction backup ${t.backup}`})}async function dS(e){let t=e.operation.expectedTargetHash;if(t===null)throw new Error(`Archive operation ${e.operation.id} has no original target to quarantine`);let i=await Si(e.paths,e.journal,e.operation,e.target),r=await Ht({paths:e.paths,file:i.originalRecord,operation:e.operation,role:"original",expectedHash:t});if(await ie(i.originalQuarantine)){if(!r)throw new Error(`Archive apply quarantine ${e.operation.target} has no bound object identity`);return await Re({paths:e.paths,file:i.originalQuarantine,operation:e.operation,record:r,label:`Archive apply quarantine ${e.operation.target}`}),await sS(e.paths,e.operation,e.hooks),{record:r,quarantine:i.originalQuarantine}}if(!await ie(e.target))throw new Error(`Archive apply target ${e.operation.target} disappeared before quarantine`);return r??=await qH({paths:e.paths,file:e.target,recordFile:i.originalRecord,operation:e.operation,role:"original",expectedHash:t,label:`Archive apply target ${e.operation.target}`}),await Re({paths:e.paths,file:e.target,operation:e.operation,record:r,label:`Archive apply target ${e.operation.target}`}),await sS(e.paths,e.operation,e.hooks),await uS({paths:e.paths,operation:e.operation,phase:"apply",target:e.target,quarantine:i.originalQuarantine,record:r,hooks:e.hooks}),{record:r,quarantine:i.originalQuarantine}}async function cS(e){let t=await Si(e.paths,e.journal,e.operation,e.target);return await ie(t.candidate)?(await ki({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`}),t.candidate):(await fi({root:e.paths.runtimeDir,directory:t.directory,label:`Archive CAS ${e.operation.id} records`}),await wr({sourceRoot:j(e.paths,e.staged),source:e.staged,targetRoot:e.paths.runtimeDir,target:t.candidate,maxBytes:Yp,label:`Archive transaction staged file ${e.operation.staged}`,expectedHash:e.operation.stagedHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>e.hooks?.afterProtectedCopySourceParentCaptured?.("apply",e.operation.staged)}}),t.candidate)}async function zH(e){let t=e.operation.stagedHash,i=await Si(e.paths,e.journal,e.operation,e.target),r=await Ht({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t});if(r&&await ie(e.target))return await Re({paths:e.paths,file:e.target,operation:e.operation,record:r,label:`Archive write target ${e.operation.target}`}),await ie(i.candidate)&&await wn({paths:e.paths,file:i.candidate,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r;if(await ie(e.target)){let c=await cS(e),l=await ki({paths:e.paths,file:c,expectedHash:t,label:`Archive write candidate ${e.operation.target}`}),u=await ki({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!Lr(l.identity,u.identity))throw new Error(`Archive write target ${e.operation.target} is occupied by an external object`);return r=await Su({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:u.identity}),await wn({paths:e.paths,file:c,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r}let n=await cS(e),a=await ki({paths:e.paths,file:n,expectedHash:t,label:`Archive write candidate ${e.operation.target}`});await fi({root:j(e.paths,e.target),directory:xe.dirname(e.target),label:`Archive write target ${e.operation.target}`});let o=await Qt({root:j(e.paths,e.target),directory:xe.dirname(e.target),label:`Archive write target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("apply",e.operation,e.target),await o.verify(),await Re({paths:e.paths,file:n,operation:e.operation,record:{schema:ks,operationId:e.operation.id,role:"post",hash:t,identity:a.identity},label:`Archive write candidate ${e.operation.target}`});try{await rt.link(n,e.target)}catch(c){throw c.code==="EEXIST"?new Error(`Archive write target ${e.operation.target} was created before exclusive install`,{cause:c}):c}await o.verify(),await e.hooks?.afterArchiveTargetInstalled?.("apply",e.operation,e.target);let s=await ki({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!Lr(a.identity,s.identity))throw new Error(`Archive write target ${e.operation.target} changed during install`);return r=await Su({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:s.identity}),await wn({paths:e.paths,file:n,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r}async function JH(e,t,i,r){let n=await De(e,i.target),a=await De(e,i.staged);if(await ft({target:a,expectedHash:i.stagedHash,label:`Archive transaction staged file ${i.staged}`}),i.expectedTargetHash!==null){let o=await Si(e,t,i,n);(!await Ht({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash})||!await ie(n))&&await dS({paths:e,journal:t,operation:i,target:n,hooks:r})}else{let o=await ni(n);if(o!==null&&!Dr(o,i.stagedHash))throw new Error(`Archive transaction target ${i.target} changed before create: ${Ta(o)}`)}await zH({paths:e,journal:t,operation:i,staged:a,target:n,hooks:r}),await ft({target:n,expectedHash:i.stagedHash,label:`Archive transaction target ${i.target}`})}async function GH(e,t,i,r){let n=await De(e,i.target);await dS({paths:e,journal:t,operation:i,target:n,hooks:r}),await ft({target:n,expectedHash:null,label:`Archive transaction target ${i.target}`})}async function UH(e,t){let i=await De(e,t.source),r=await De(e,t.target),[n,a]=await Promise.all([ni(i),ni(r)]);if(!(n===null&&Dr(a,t.expectedSourceHash,"directory"))){if(!Dr(n,t.expectedSourceHash,"directory")||a!==null)throw new Error(`Archive transaction move ${t.id} content changed: source=${Ta(n)}, target=${Ta(a)}`);await rt.mkdir(xe.dirname(r),{recursive:!0}),await rt.rename(i,r),await ft({target:r,expectedHash:t.expectedSourceHash,expectedKind:"directory",label:`Archive transaction move target ${t.target}`})}}async function KH(e,t,i,r){return i.type==="write"?JH(e,t,i,r):i.type==="remove"?GH(e,t,i,r):UH(e,i)}function YH(e){let t=0,i=!1,r=[];for(let n of e.events){if(n.type!=="operation-started"&&n.type!=="operation-completed")continue;let a=e.journal.operations[t];if(!a||n.operationId!==a.id)throw new Error(`Native Archive transaction ${e.journal.id} operation events are out of order`);if(n.type==="operation-started"){i=!0;continue}if(!i)throw new Error(`Native Archive transaction ${e.journal.id} completed an operation before it started`);r.push(a.id),t+=1,i=!1}return r}async function XH(e,t,i,r){let n=await De(e,i.target);if(i.type==="write"){let a=await De(e,i.staged);await ft({target:a,expectedHash:i.stagedHash,label:`Completed Archive staged file ${i.staged}`});let o=await Si(e,t,i,n),s=await Ht({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!s)throw new Error(`Completed Archive target ${i.target} has no CAS identity`);if(await Re({paths:e,file:n,operation:i,record:s,label:`Completed Archive target ${i.target}`}),i.expectedTargetHash!==null){await ft({target:await De(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let c=await Ht({paths:e,file:o.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!c)throw new Error(`Completed Archive target ${i.target} has no original CAS identity`);if(await ie(o.originalQuarantine))await Re({paths:e,file:o.originalQuarantine,operation:i,record:c,label:`Completed Archive original quarantine ${i.target}`});else if(!r)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`)}return}if(i.type==="remove"){await ft({target:n,expectedHash:null,label:`Completed Archive target ${i.target}`}),await ft({target:await De(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let a=await Si(e,t,i,n),o=await Ht({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!o)throw new Error(`Completed Archive remove ${i.target} has no original CAS identity`);if(await ie(a.originalQuarantine))await Re({paths:e,file:a.originalQuarantine,operation:i,record:o,label:`Completed Archive original quarantine ${i.target}`});else if(!r)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`);return}r||(await ft({target:await De(e,i.source),expectedHash:null,label:`Completed Archive move source ${i.source}`}),await ft({target:n,expectedHash:i.expectedSourceHash,expectedKind:"directory",label:`Completed Archive move target ${i.target}`}))}async function fS(e,t,i){let r=t.status==="prepared"?await bu(e,t,"applying"):t;if(r.status!=="applying")throw new Error(`Native Archive transaction ${r.id} cannot apply from ${r.status}`);let n=await Nr(e,r.id),a=YH({journal:r,events:n}),o=new Set(a),s=n.some(l=>l.type==="archive-finalization-started");for(let l of r.operations.slice(0,a.length))await XH(e,r,l,s);let c=o.size;for(let l of r.operations)o.has(l.id)||(l.id==="archive-change"&&await i?.beforeArchiveChangeMove?.(l),await Tt(e,r.id,"operation-started",l.id),await KH(e,r,l,i),await Tt(e,r.id,"operation-completed",l.id),c+=1,await i?.afterOperation?.(l,c));return r=await Xp(e,r.id),r}async function QH(e){try{return await Re(e),!0}catch{return!1}}async function ZH(e){await Re({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});let t=await Qt({root:j(e.paths,e.target),directory:xe.dirname(e.target),label:`Archive rollback target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("rollback",e.operation,e.target),await t.verify(),await Re({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});try{await rt.link(e.quarantine,e.target)}catch(i){throw i.code==="EEXIST"?new Error(`Archive rollback target ${e.operation.target} was created before exclusive restore`,{cause:i}):i}await t.verify(),await e.hooks?.afterArchiveTargetInstalled?.("rollback",e.operation,e.target),await Re({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive rollback target ${e.operation.target}`})}async function Kp(e){if(e.operation.type!=="write")return;let t=await Si(e.paths,e.journal,e.operation,e.target);if(!await ie(t.candidate))return;let i=await ki({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`});await wn({paths:e.paths,file:t.candidate,operation:e.operation,record:{schema:ks,operationId:e.operation.id,role:"post",hash:e.operation.stagedHash,identity:i.identity},label:`Archive write candidate ${e.operation.target}`})}async function eD(e,t,i,r){let n=await De(e,i.target),a=await Si(e,t,i,n),o=i.expectedTargetHash,s=o===null?null:await Ht({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:o}),c=i.type==="write"?await Ht({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash}):null;if(i.type==="write"&&!c&&await ie(a.candidate)&&await ie(n)){let l=await ki({paths:e,file:a.candidate,expectedHash:i.stagedHash,label:`Archive write candidate ${i.target}`}),u=await ki({paths:e,file:n,expectedHash:i.stagedHash,label:`Archive rollback target ${i.target}`});Lr(l.identity,u.identity)&&(c=await Su({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash,identity:u.identity}))}if(await ie(a.rollbackQuarantine)){if(!c)throw new Error(`Archive rollback quarantine ${i.target} has no CAS identity`);await Re({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`})}if(await ie(n)&&!(s!==null&&await QH({paths:e,file:n,operation:i,record:s,label:`Archive rollback target ${i.target}`}))){if(!c){if(!s){let u=await ni(n);if(Dr(u,o)){await Kp({paths:e,journal:t,operation:i,target:n});return}}throw new Error(`Archive rollback target ${i.target} is occupied by an external object`)}await uS({paths:e,operation:i,phase:"rollback",target:n,quarantine:a.rollbackQuarantine,record:c,hooks:r})}if(o===null){if(await ie(n))throw new Error(`Archive rollback create target ${i.target} could not be removed`)}else if(!await ie(n)){if(!s||!await ie(a.originalQuarantine))throw new Error(`Archive rollback original target ${i.target} cannot be recovered safely`);await ZH({paths:e,operation:i,target:n,quarantine:a.originalQuarantine,record:s,hooks:r})}s&&await ie(a.originalQuarantine)&&await wn({paths:e,file:a.originalQuarantine,operation:i,record:s,label:`Archive rollback original quarantine ${i.target}`}),c&&await ie(a.rollbackQuarantine)&&await wn({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`}),await Kp({paths:e,journal:t,operation:i,target:n}),await ft({target:n,expectedHash:o,label:`Archive rollback target ${i.target}`})}async function tD(e,t){let i=await De(e,t.source),r=await De(e,t.target),[n,a]=await Promise.all([ni(i),ni(r)]);if(!(Dr(n,t.expectedSourceHash,"directory")&&a===null)){if(n!==null||!Dr(a,t.expectedSourceHash,"directory"))throw new Error(`Archive rollback move ${t.id} content changed: source=${Ta(n)}, target=${Ta(a)}`);await rt.mkdir(xe.dirname(i),{recursive:!0}),await rt.rename(r,i)}}async function hS(e,t,i){let r=await Nr(e,t.id);if(r.some(o=>o.type==="archive-finalization-started"||o.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let n=await bu(e,t,"rolling-back");await Tt(e,n.id,"rollback-started");let a=new Set(r.filter(o=>o.type==="operation-started"||o.type==="operation-completed").map(o=>o.operationId));for(let o of[...n.operations].reverse())a.has(o.id)&&(o.type==="move"?await tD(e,o):await eD(e,n,o,i));return await Tt(e,n.id,"rollback-completed"),n=await bu(e,n,"rolled-back"),n}async function lS(e,t,i){let r=await De(e,i.target);if(i.type==="write"){let n=await Si(e,t,i,r),a=await Ht({paths:e,file:n.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!a)throw new Error(`Archive commit target ${i.target} has no CAS identity`);await Re({paths:e,file:r,operation:i,record:a,label:`Archive commit target ${i.target}`});return}await ft({target:r,expectedHash:null,label:`Archive commit target ${i.target}`})}async function iD(e,t){for(let i of t.operations){if(i.type==="move")continue;let r=await De(e,i.target),n=await Si(e,t,i,r);if(await ie(n.rollbackQuarantine))throw new Error(`Archive commit found an unfinished rollback for ${i.target}`);if(await lS(e,t,i),i.expectedTargetHash!==null){let a=await Ht({paths:e,file:n.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!a)throw new Error(`Archive commit target ${i.target} has no original CAS identity`);await ie(n.originalQuarantine)&&await wn({paths:e,file:n.originalQuarantine,operation:i,record:a,label:`Archive commit original quarantine ${i.target}`})}await Kp({paths:e,journal:t,operation:i,target:r})}for(let i of t.operations)i.type!=="move"&&await lS(e,t,i)}async function Eu(e,t,i){return i==="commit"&&await iD(e,t),await Tt(e,t.id,i),i==="commit"?bu(e,t,"committed"):t}var SU=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});import{promises as rD}from"fs";import nD from"path";var Qp="comet.selection.v2",aD=16*1024;function Pu(e){return nD.join(e,".comet","current-change.json")}function oD(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function pS(e){return e===null||typeof e=="string"}function sD(e){let t;try{t=JSON.parse(e)}catch(i){throw new Error(`current change selection contains invalid JSON: ${i instanceof Error?i.message:String(i)}`,{cause:i})}if(!oD(t))throw new Error("current change selection must be a JSON object");if(t.version===1){if(typeof t.change!="string")throw new Error("legacy current change selection change must be a string");if(t.branch!==void 0&&!pS(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Qp,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Qp)throw new Error(`current change selection schema must be ${Qp}`);if(t.workflow!=="native"&&t.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof t.change!="string")throw new Error("current change selection change must be a string");if(!pS(t.branch))throw new Error("current change selection branch must be a string or null");if(t.workflow==="native"&&t.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:t,legacy:!1}}async function Zp(e){let t;try{let r=Pu(e),{bytes:n}=await en(r,aD,{label:"current change selection"});t=n.toString("utf8")}catch(r){if(r.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${r instanceof Error?r.message:String(r)}`,{cause:r})}return{status:"selected",...sD(t)}}async function mS(e){await rD.rm(Pu(e),{force:!0})}async function vS(e,t,i){let r=await Zp(e);return r.status!=="selected"||r.selection.workflow!==t||r.selection.change!==i?!1:(await mS(e),!0)}import{promises as _s}from"node:fs";import Vr from"node:path";var om=Rn(Qr(),1);import{promises as HS}from"node:fs";import Dt from"node:path";import{execFileSync as cD}from"node:child_process";var lD=3e4,uD=8*1024*1024,em=class extends Error{constructor(i,r,n){super(`git ${r.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=i;this.args=r;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr};function dD(e,t){try{return cD("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:lD,maxBuffer:uD,windowsHide:!0})}catch(i){let r=typeof i.stderr=="string"?i.stderr.trim():Buffer.isBuffer(i.stderr)?i.stderr.toString("utf8").trim():"";throw new em(e,t,r)}}function Ae(e,t){return dD(e,t).trim()}function Ss(e){return Ae(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}import Le from"node:path";import{promises as xu}from"node:fs";import Ru from"node:path";function gS(...e){if(e.length===0)return Ru.resolve();if(Ru.win32.isAbsolute(e[0])){let t=Ru.win32.resolve(...e);return process.platform==="win32"?t:t.replace(/\\/gu,"/")}return Ru.resolve(...e)}var Cu=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var im="comet.native.supervisor.v2",fD=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function hD(e,t){let i=Le.relative(Le.resolve(e),Le.resolve(t));return i===""||!Le.isAbsolute(i)&&!i.startsWith(`..${Le.sep}`)}function pD(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native Supervisor parent name: ${e}`);return`comet/supervisor/${e}/integration`}function mD(e,t,i){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(i))throw new Error("Native Supervisor parent and child names are invalid");return gS(e,".worktrees",`${t}-${i}`)}function bS(e,t){return Le.join(We(e,t),"supervisor")}function kS(e,t){return Le.join(bS(e,t),"state.json")}function SS(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native Supervisor state must be an object");let t=e;if(t.schema!==im)throw new Error(`Native Supervisor state schema must be ${im}`);if(!Number.isSafeInteger(t.stateVersion)||typeof t.stateVersion!="number"||t.stateVersion<1)throw new Error("Native Supervisor state version is invalid");if(typeof t.parent!="string"||!t.parent)throw new Error("Native Supervisor state parent is invalid");if(!t.integration||typeof t.integration!="object")throw new Error("Native Supervisor integration state is missing");for(let[n,a]of Object.entries(t.integration))if(typeof a!="string"||a.length===0)throw new Error(`Native Supervisor integration field ${n} is invalid`);if(Es(t.integration.targetCommit,"Native Supervisor target commit"),Es(t.integration.headCommit,"Native Supervisor integration head commit"),!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let i=new Set,r=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(i.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(i.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.projectRoot!==void 0&&n.projectRoot!==null&&(typeof n.projectRoot!="string"||n.projectRoot.length===0))throw new Error(`Native Supervisor child ${n.name} projectRoot is invalid`);for(let[a,o]of[["base",n.baseCommit],["candidate",n.candidateCommit],["verified",n.verifiedCommit],["integration",n.integrationCommit]])o!==null&&Es(o,`Native Supervisor child ${n.name} ${a} commit`);if(!Array.isArray(n.checks)||!Array.isArray(n.verification?.checks??[]))throw new Error(`Native Supervisor child ${n.name} evidence is invalid`);if(n.task!==null){if(!n.task||typeof n.task!="object")throw new Error(`Native Supervisor child ${n.name} task is invalid`);if(!["builder","verifier"].includes(n.task.role)||n.task.child!==n.name||typeof n.task.projectRoot!="string"||n.task.projectRoot.length===0||typeof n.task.runId!="string"||n.task.runId.length===0)throw new Error(`Native Supervisor child ${n.name} task identity is invalid`);if(Es(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),r.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(r.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.role==="builder"&&n.status!=="active"||n.task.role==="verifier"&&!["active","needs-reverify"].includes(n.status))throw new Error(`Native Supervisor child ${n.name} task status is invalid`)}}}async function Mr(e,t){try{let i=await xu.readFile(kS(e,t),"utf8"),r=JSON.parse(i);return SS(r),r}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Ia(e,t){SS(t),await xu.mkdir(e.changesRuntimeDir,{recursive:!0}),await ee(kS(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function Es(e,t){if(!fD.test(e))throw new Error(`${t} must be a Git commit`)}function rm(e){return structuredClone(e)}function ES(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function PS(e){Es(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:r})=>r)),i=e.contract.children.map(r=>({name:r.name,summary:r.summary,dependsOn:[...r.depends_on],status:r.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null}));for(let r of i)for(let n of r.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${r.name} depends on unknown child ${n}`);return{schema:im,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:i,history:[],finalVerification:{status:"pending",summary:null}}}async function nm(e){let t=pD(e.parent),i=xi(e.paths.projectRoot,t);if(!i)return null;let r=xi(e.paths.projectRoot,e.targetBranch);if(!r)return null;let n=Jt(e.paths.projectRoot).map(o=>Le.resolve(o)).find(o=>fe(o).currentBranch===t);if(!n)return null;let a=PS({parent:e.parent,targetBranch:e.targetBranch,targetCommit:r,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(i!==r){for(let o of a.children)o.status=o.dependsOn.length===0?"blocked":"pending",o.blocker=o.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;a.integration.headCommit=i}return ES(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function RS(e){if(!Ss(e.integration.worktree))throw new Error("Native Supervisor integration worktree must be clean");let t=Ae(e.integration.worktree,["rev-parse","--show-toplevel"]);if(Le.resolve(t)!==Le.resolve(e.integration.worktree))throw new Error("Native Supervisor integration worktree identity is invalid");let i=Ae(e.integration.worktree,["branch","--show-current"]);if(i!==e.integration.branch)throw new Error(`Native Supervisor integration branch mismatch: expected ${e.integration.branch}, got ${i||"(detached)"}`);return Ae(e.integration.worktree,["rev-parse","HEAD"])}async function vD(e){let t=xi(e.paths.projectRoot,e.state.integration.targetBranch);if(!t||t===e.state.integration.targetCommit)return null;let i=e.state;if(RS(i)!==i.integration.headCommit)throw new Error("Native Supervisor integration head changed before target refresh");try{Ae(i.integration.worktree,["merge","--no-edit",i.integration.targetBranch])}catch(o){throw new Error(`Native Supervisor target drift requires conflict resolution in ${i.integration.worktree}`,{cause:o})}let n=Ae(i.integration.worktree,["rev-parse","HEAD"]),a=rm(i);return a.integration.headCommit=n,a.finalVerification={status:"pending",summary:null},ES(a,{kind:"target-refreshed",child:null,runId:null,summary:`Target ${i.integration.targetBranch} was refreshed before delivery`}),a.stateVersion+=1,await Ia(e.paths,a),a}async function Ps(e){let i=await Mr(e.paths,e.state.parent)??e.state;if(i.stateVersion!==e.state.stateVersion)throw new Error("Native Supervisor state changed before delivery; reload status first");if(i.finalVerification.status!=="passed")throw new Error("Native Supervisor delivery requires a passed final verification");if(!i.children.every(({status:v})=>v==="integrated"||v==="archived"))throw new Error("Native Supervisor delivery requires every child to be integrated");let n=Jt(e.paths.projectRoot).map(v=>Le.resolve(v)).find(v=>fe(v).currentBranch===i.integration.targetBranch);if(!n)throw new Error(`Native Supervisor target branch worktree is unavailable: ${i.integration.targetBranch}`);if(!Ss(n))throw new Error(`Native Supervisor target worktree is not clean: ${n}`);let a=Ae(n,["rev-parse","HEAD"]);if((()=>{try{return Ae(n,["merge-base","--is-ancestor",i.integration.headCommit,a]),!0}catch{return!1}})()){let v=await yS({paths:e.paths,state:i,targetCommit:a});if(await NS({paths:e.paths,plan:v}),i.children.every(({status:p})=>p==="archived"))return await tm(e.paths,i.parent),{state:i,targetRoot:n,targetCommit:a};let m=rm(i);for(let p of m.children)p.status="archived";return m.stateVersion+=1,await Ia(e.paths,m),await tm(e.paths,i.parent),{state:m,targetRoot:n,targetCommit:a}}let c=RS(i);if(c!==i.integration.headCommit)throw new Error("Native Supervisor integration head changed after final verification");let l=xi(e.paths.projectRoot,i.integration.targetBranch),u=(()=>{if(!l)return!1;try{return Ae(i.integration.worktree,["merge-base","--is-ancestor",l,c]),!0}catch{return!1}})();if(l!==c&&!u&&l!==i.integration.targetCommit&&await vD({paths:e.paths,state:i}))throw new Error("Native Supervisor target changed; parent integration checks must be rerun before delivery");let d=await yS({paths:e.paths,state:i,targetCommit:c});l!==c&&Ae(n,["merge","--ff-only",i.integration.branch]);let f=Ae(n,["rev-parse","HEAD"]);if(f!==c)throw new Error("Native Supervisor target did not receive the verified integration head");let h=rm(i);for(let v of h.children)v.status="archived";return await NS({paths:e.paths,plan:d}),h.stateVersion+=1,await Ia(e.paths,h),await tm(e.paths,i.parent),{state:h,targetRoot:n,targetCommit:f}}function CS(e,t){return Le.join(bS(e,t),"cleanup.json")}function wS(e){let t=Jt(e.paths.projectRoot).map(s=>Le.resolve(s)),i=Le.resolve(process.cwd()),r=[{root:e.state.integration.worktree,branch:e.state.integration.branch},...e.state.children.map(({name:s})=>({root:mD(e.paths.projectRoot,e.state.parent,s),branch:`comet/supervisor/${e.state.parent}/${s}`}))].map(s=>({...s,root:Le.resolve(s.root)})),n=e.targetCommit,a=[e.state.integration.branch,...e.state.children.map(({name:s})=>`comet/supervisor/${e.state.parent}/${s}`)],o=r.flatMap(s=>{let c=t.find(l=>l===s.root);return c?[{...s,root:c}]:[]});for(let s of o){if(hD(s.root,i))throw new Error(`Native Supervisor cannot clean the current worktree: ${s.root}`);if(!Ss(s.root))throw new Error(`Native Supervisor cleanup requires a clean worktree: ${s.root}`);let c=fe(s.root).currentBranch;if(!c)throw new Error(`Native Supervisor worktree is detached: ${s.root}`);if(c!==s.branch)throw new Error(`Native Supervisor cleanup found unexpected branch ${c} for ${s.root}; expected ${s.branch}`);try{Ae(e.paths.projectRoot,["merge-base","--is-ancestor",c,n])}catch{throw new Error(`Native Supervisor cleanup found unintegrated branch ${c}`)}}for(let s of a)if(ko(e.paths.projectRoot,s))try{Ae(e.paths.projectRoot,["merge-base","--is-ancestor",s,n])}catch{throw new Error(`Native Supervisor cleanup found unintegrated branch ${s}`)}return{parent:e.state.parent,targetCommit:e.targetCommit,worktrees:o.map(({root:s})=>s),expectedBranches:Object.fromEntries(o.map(({root:s,branch:c})=>[s,c])),branches:a}}async function yS(e){let t=CS(e.paths,e.state.parent);try{let r=JSON.parse(await xu.readFile(t,"utf8"));if(r.parent===e.state.parent&&r.targetCommit===e.targetCommit&&Array.isArray(r.worktrees)&&r.expectedBranches&&typeof r.expectedBranches=="object"&&Array.isArray(r.branches)){let n=wS(e);return{parent:r.parent,targetCommit:r.targetCommit,worktrees:[...new Set([...r.worktrees,...n.worktrees])],expectedBranches:{...r.expectedBranches,...n.expectedBranches},branches:[...new Set([...r.branches,...n.branches])]}}}catch(r){if(r.code!=="ENOENT")throw r}let i=wS(e);return await ee(t,i,{containedRoot:e.paths.changesRuntimeDir}),i}async function NS(e){for(let t of e.plan.worktrees){if(!Jt(e.paths.projectRoot).map(a=>Le.resolve(a)).includes(Le.resolve(t)))continue;let r=e.plan.expectedBranches[t];if(!r)throw new Error(`Native Supervisor cleanup has no expected branch for ${t}`);let n=fe(t).currentBranch;if(n!==r)throw new Error(`Native Supervisor cleanup found unexpected branch ${n??"(detached)"} for ${t}; expected ${r}`);Ae(e.paths.projectRoot,["worktree","remove",t])}for(let t of e.plan.branches)ko(e.paths.projectRoot,t)&&Ae(e.paths.projectRoot,["branch","-d",t])}async function tm(e,t){await xu.rm(CS(e,t),{force:!0})}function xS(e){let t=e.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.dependsOn],covers:[],status:i.status,phase:null,projectRoot:i.projectRoot??i.task?.projectRoot??null,message:i.blocker}));return{contractHash:null,confirmed:!0,parentBranch:e.integration.branch,children:t,readyChildren:t.filter(({status:i})=>i==="ready").map(({name:i})=>i),allDone:t.every(({status:i})=>i==="integrated"||i==="archived")}}var AS="children.yaml",Rs="comet.native.children.v1",ja="comet.native.children.v2",DS=ja,gD=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,_S=new Set(["schema","children"]),wD=new Set(["schema","acceptance_index","children"]),yD=new Set(["name","depends_on","covers"]),ND=new Set(["name","summary","depends_on"]),bD=new Set(["name","depends_on","covers"]);function _u(e,t,i=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${i}`);return e}function Au(e,t,i){let r=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(r.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...r.length>0?[`unexpected ${r.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${i} fields are invalid: ${a.join("; ")}`)}}function TS(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((i,r)=>i.localeCompare(r,"en"))}function am(e,t){let i=Dt.normalize(Dt.resolve(e)),r=Dt.normalize(Dt.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function kD(e){let t=new Map(e.map(a=>[a.name,a])),i=new Set,r=new Set,n=a=>{if(!r.has(a)){if(i.has(a))throw new Error(`Native children dependency cycle includes ${a}`);i.add(a);for(let o of t.get(a).depends_on)n(o);i.delete(a),r.add(a)}};for(let a of e)n(a.name)}function IS(e,t,i=t){let r=new Set(t);for(let o of e){let s=o.covers.filter(c=>!r.has(c));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=i.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function SD(e,t,i){let r={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===DS&&e.acceptance_index){let n=i.requiredAcceptanceIds??t??[],a=Object.keys(e.acceptance_index);r.missing=n.filter(c=>!(c in e.acceptance_index)),r.extra=a.filter(c=>!n.includes(c));let o=new Map((i.acceptanceCatalog??[]).map(c=>[c.id,c]));for(let c of n){let l=o.get(c),u=e.acceptance_index[c];l&&u&&(u.source!==l.source||u.text!==l.text)&&r.mismatched.push(c)}let s=new Set(a);for(let c of e.children)r.unknownCovers.push(...c.covers.filter(l=>!s.has(l)));return r.uncovered=a.filter(c=>!jS(e.children,c)),$S(r)?r:null}if(e.schema===Rs&&t){let n=new Set(t);for(let a of e.children)r.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return r.uncovered=t.filter(a=>!jS(e.children,a)),$S(r)?r:null}return null}function jS(e,t){return e.some(i=>i.covers.includes(t))}function $S(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function sm(e){let t=new Set(e.acceptance.filter(({source:i})=>i===e.brief).map(({id:i})=>i));if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let i=[...e.history].reverse().find(({outcome:r})=>r==="fail");for(let r of i?.unresolved_ids??[])t.add(r)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...t]}}function ED(e){let t=_u(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),i={};for(let[r,n]of Object.entries(t)){let a=_u(n,`Native children acceptance_index.${r}`);if(Au(a,new Set(["source","text"]),`Native children acceptance_index.${r}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${r}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${r}.text must be a non-empty string`);i[r]={source:a.source,text:a.text}}return i}function PD(e,t,i){let r=i.requiredAcceptanceIds??t??[],n=Object.keys(e),a=r.filter(c=>!(c in e)),o=n.filter(c=>!r.includes(c));if(a.length>0||o.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${a.join(", ")||"none"}; extra ${o.join(", ")||"none"}`);let s=new Map((i.acceptanceCatalog??[]).map(c=>[c.id,c]));for(let c of r){let l=s.get(c);if(!l)continue;let u=e[c];if(u.source!==l.source||u.text!==l.text){let d=["source","text"].filter(f=>u[f]!==l[f]);throw new Error(`Native children acceptance_index.${c} does not match the acceptance catalog: copy ${d.join(", ")} exactly from the current acceptance catalog`)}}}function RD(e,t,i={}){let r=(0,om.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${r.errors[0].message}`);let n=_u(r.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==Rs&&a!==ja)throw Au(n,_S,"Native children contract"),new Error(`Native children schema must be ${Rs} or ${ja}`);let o=a===Rs?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(Au(n,o==="indexed-v2"?wD:_S,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let c=n.children.map((f,h)=>{let v=_u(f,`Native child ${h}`);if(Au(v,o==="indexed-v2"?bD:o==="summary-v2"?ND:yD,`Native ${s} child fields (child ${h})`),typeof v.name!="string"||!gD.test(v.name))throw new Error(`Native child ${h} name is invalid`);let m=o==="summary-v2";if(m){if(typeof v.summary!="string"||v.summary.trim().length===0)throw new Error(`Native child ${v.name} summary must be a non-empty string`);if(v.summary.length>2e3)throw new Error(`Native child ${v.name} summary exceeds 2000 characters`)}return{name:v.name,summary:m?v.summary:null,depends_on:TS(v.depends_on,`Native child ${v.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?TS(v.covers,`Native child ${v.name} covers`):[]}}),l=c.map(({name:f})=>f);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let u=new Set(l);for(let f of c){let h=f.depends_on.filter(v=>!u.has(v));if(h.length>0)throw new Error(`Native child ${f.name} depends on unknown child: ${h.join(", ")}`)}kD(c);let d=i.policy==="advisory";if(a===DS){if(o==="indexed-v2"){let f=ED(n.acceptance_index);d||PD(f,t,i);let h=Object.keys(f);return d||IS(c,h,h),{schema:ja,acceptance_index:f,children:c}}return{schema:ja,children:c}}return t&&!d&&IS(c,t),{schema:Rs,children:c}}async function cm(e){let t=Dt.join(e.changeDir,AS);try{await HS.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let i=await Z({root:e.changeDir,ref:AS}),r=e.policy==="advisory",n=r?{...e.validation,policy:"advisory"}:e.validation??{},a=RD(i.text,e.acceptanceIds,n);return{contract:a,size:i.size,drift:r?SD(a,e.acceptanceIds,e.validation??{}):null}}function CD(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let i=e.slice(t.index+t[0].length);return i.split(/^#\s+/mu,1)[0]??i}function xD(e){let t=CD(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let i=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),r=t.match(/\bChild\s+\d+\b/giu);return Math.max(i?.length??0,r?.length??0)>=2}async function LS(e){try{let t=await Z({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return xD(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function lm(e){return D("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:i,text:r})=>({id:t,source:i,text:r})),children:e.children})}async function AD(e){let t=Jt(e.projectRoot);t.some(r=>am(r,e.projectRoot))||t.push(e.projectRoot);let i=[];for(let r of[...new Set(t.map(n=>Dt.resolve(n)))]){let n=await ye(r);n&&i.push({projectRoot:r,paths:await qe(r,n.native.artifact_root),parent:am(r,e.projectRoot)})}return i.some(({parent:r})=>r)||i.push({projectRoot:e.projectRoot,paths:e,parent:!0}),i}async function _D(e,t){let i=Dt.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Ze(i)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function TD(e,t){let i;try{i=await HS.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[];for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=Dt.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await Ze(o);t.has(s.name)&&r.push({file:o,state:s})}catch{}return r}function ID(e,t,i){let r=Dt.relative(e.projectRoot,t);if(!r||r===".."||r.startsWith(`..${Dt.sep}`))return null;let n=r.split(Dt.sep).join("/");try{let a=(0,om.parseDocument)(Ae(e.projectRoot,["show",`${i}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:ct(a.toJS({mapAsMap:!1}))}catch{return null}}function jD(e,t,i){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==i||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${i??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function OS(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Cs(e){let t=Dt.join(e.paths.changesDir,e.state.name),i=await LS(t),r=await cm({changeDir:t,validation:sm(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:p})=>p)}:{},policy:"advisory"});if(!r)return e.state.children_contract_hash?{...i?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:i?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null;let n=lm({acceptance:e.state.acceptance,children:r.contract}),a=e.state.workspace.change_branch,o=e.state.phase!=="shape"&&e.state.children_contract_hash===n&&!r.drift;if(r.contract.schema===ja){let p=await Mr(e.paths,e.state.name);if(!p){let y=e.state.workspace.target_branch??e.state.workspace.change_branch;if(y){let E=await nm({paths:e.paths,parent:e.state.name,targetBranch:y,contract:r.contract});E&&(p=E,await Ia(e.paths,E))}}if(p){let y=xS(p);return e.state.children_contract_hash!==n||r.drift?{...y,schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:!1,readyChildren:[],allDone:!1,children:y.children.map(E=>({...E,message:r.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...y,schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o}}let b=new Map(r.contract.children.map(y=>[y.name,y])),g=r.contract.children.map(y=>({name:y.name,summary:y.summary,dependsOn:[...y.depends_on],covers:[],status:o&&y.depends_on.every(E=>r.contract.children.filter(({name:k})=>k!==y.name).every(({name:k})=>k!==E))?"ready":"pending",phase:null,projectRoot:null,message:o?null:"Parent Shape confirmation is required"}));for(let y of g){if(y.status!=="ready")continue;b.get(y.name).depends_on.length>0&&(y.status="pending")}return{schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:g,readyChildren:g.filter(({status:y})=>y==="ready").map(({name:y})=>y),allDone:!1}}let s=await AD(e.paths),c=new Set(r.contract.children.map(({name:p})=>p)),l=new Map,u=new Map;for(let p of s){let b=p.parent&&a?`refs/heads/${a}`:"HEAD";for(let g of await TD(p,c)){let y={...g,source:p,committedState:ID(p,g.file,b)};l.set(g.state.name,[...l.get(g.state.name)??[],y])}for(let g of c){let y=await _D(p,g);y&&u.set(g,[...u.get(g)??[],{source:p,state:y}])}}let d=new Map;for(let p of r.contract.children){let b=(l.get(p.name)??[]).find(({source:E,committedState:k})=>E.parent&&k?.name===p.name&&OS(k,a));if(b){d.set(p.name,{kind:"done",phase:b.state.phase,projectRoot:b.source.projectRoot,message:null});continue}let g=l.get(p.name)?.[0];if(g){d.set(p.name,{kind:"blocked",phase:g.state.phase,projectRoot:g.source.projectRoot,message:`Native child ${p.name} is archived but not merged into parent branch ${a??"(missing)"}`});continue}let y=u.get(p.name)??[];y.length>1?d.set(p.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${p.name} has multiple active workspace owners`}):y[0]&&d.set(p.name,jD(y[0].state,y[0].source,a))}let f=new Map(r.contract.children.map(p=>[p.name,p])),h=new Map,v=p=>{let b=h.get(p);if(b)return b;let g=f.get(p),E=g.depends_on.map(v).every(({status:P})=>P==="done"),k=d.get(p),S=k?.kind==="active"&&E?g.depends_on.filter(P=>!(l.get(P)??[]).some(({source:F,committedState:$})=>am(F.projectRoot,k.projectRoot)&&$?.name===P&&OS($,a))):[],R,N=k?.message??null;k?.kind==="done"?(R=E?"done":"blocked",E||(N=`Native child ${p} was merged before its dependencies`)):k?.kind==="active"?(R=E&&S.length===0?"active":"blocked",E?S.length>0&&(N=`Native child ${p} does not include merged dependencies: ${S.join(", ")}`):N=`Native child ${p} started before its dependencies merged`):k?.kind==="blocked"?R="blocked":(R=o&&E?"ready":"pending",o||(N="Parent Shape confirmation is required"));let w={name:p,summary:g.summary,dependsOn:[...g.depends_on],covers:[...g.covers],status:R,phase:k?.phase??null,projectRoot:k?.projectRoot??null,message:N};return h.set(p,w),w},m=r.contract.children.map(({name:p})=>v(p));return{schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:m,readyChildren:m.filter(({status:p})=>p==="ready").map(({name:p})=>p),allDone:m.every(({status:p})=>p==="done")}}var xs="skill-coordinated";function OD(e){return e.state_version+1}function HD(e){return e.map(t=>({...t,result:"pending",reason:null}))}function DD(e){return{goal_cycle:e.state.loop.goal_cycle,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,outcome:e.outcome,unresolved_ids:e.unresolvedIds??[],summary:hr(e.summary),completed_at:e.completedAt}}function um(e){let t=ct(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let i=(e.now??new Date).toISOString(),r=Yn(t,DD({state:t,outcome:"recovery",summary:e.reason,completedAt:i})),n=new Set(t.loop.previous_unresolved_ids),a=n.size===0?HD(t.acceptance):t.acceptance.map(o=>n.has(o.id)?{...o,result:"pending",reason:null}:o);return ct({...r,phase:"build",status:"active",state_version:OD(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:t.builder_handoff,blockers:[],acceptance:a,loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,stop_reason:void 0,next_action:"submit-builder-candidate"}})}import{promises as FS}from"node:fs";import As from"node:path";function Tu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Iu(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Ei(e,t,i=!1){if(typeof e!="string"||!i&&e.length===0)throw new Error(`${t} must be ${i?"a string":"a non-empty string"}`);return e}function MS(e,t){return e===null?null:Ei(e,t)}function $u(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function LD(e,t){if(e===null)return null;if(!Number.isSafeInteger(e))throw new Error(`${t} must be null or a safe integer`);return e}function MD(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function ju(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function dm(e,t){if(e===null)return null;let i=Ei(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO timestamp`);return i}function fm(e,t){let i=Ei(e,t);if(!As.isAbsolute(i))throw new Error(`${t} must be absolute`);return As.resolve(i)}function FD(e,t){let i=`Native local checks[${t}]`,r=Tu(e,i);if(Iu(r,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),i),!Array.isArray(r.argv)||r.argv.length===0)throw new Error(`${i}.argv must be a non-empty array`);let n=r.argv.map((l,u)=>Ei(l,`${i}.argv[${u}]`,!0)),a=ju(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=dm(r.startedAt,`${i}.startedAt`),s=dm(r.completedAt,`${i}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${i} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${i} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${i} completed check requires startedAt and completedAt`);let c=$u(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:Ei(r.id,`${i}.id`),name:Ei(r.name,`${i}.name`),operationId:Ei(r.operationId,`${i}.operationId`),status:a,repeatable:MD(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:$u(r.executionCount,`${i}.executionCount`),argv:n,cwd:fm(r.cwd,`${i}.cwd`),exitCode:LD(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:Ei(r.log,`${i}.log`)}}function hm(e){let t="Native local execution state",i=Tu(e,t);if(Iu(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),i.schema!==Lo)throw new Error(`Native local execution schema must be ${Lo}`);let r=Tu(i.workspace,"Native local workspace");Iu(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=Tu(i.execution,"Native local execution");Iu(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=dm(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Ei(o.operationId,"Native local execution.operationId"),stage:ju(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:ju(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:MS(o.executionId,"Native local execution.executionId"),status:ju(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:$u(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(i.checks))throw new Error("Native local checks must be an array");let a=i.checks.map(FD);if(new Set(a.map(o=>o.id)).size!==a.length)throw new Error("Native local check IDs must be unique");if(n&&a.some(o=>o.operationId!==n.operationId))throw new Error("Native local checks must belong to the current operation");return{schema:Lo,change:Ei(i.change,"Native local change"),basedOnStateVersion:$u(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:fm(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:fm(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:MS(r.branch,"Native local workspace.branch")},execution:n,checks:a}}function yn(e){return hm({schema:Lo,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:As.resolve(e.projectRoot),worktreeRoot:As.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function Ou(e){let t;try{t=await FS.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}let i;try{i=JSON.parse(t)}catch(r){throw new Error(`Native local execution state is invalid JSON: ${r.message}`,{cause:r})}return hm(i)}async function Fr(e,t,i={}){let r=hm(t);await FS.mkdir(As.dirname(e),{recursive:!0}),await ee(e,r,i)}import{promises as BD}from"node:fs";function Br(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
206
- `).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function Bi(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function VD(e){return e.archived?qt(e.language,"Archived","已归档"):e.phase==="verify"&&e.loop.next_action==="confirm-skill-coordinated-pass"?qt(e.language,"Verification passed; your confirmation is required","验收通过,需要你确认"):e.phase==="archive"&&e.loop.next_action==="archive"?qt(e.language,"Verification passed; ready to archive","验收通过,可归档"):qt(e.language,"Verification passed","验收通过")}function qD(e){let t=e.language;return e.verification?.assurance==="semantic-verification-unavailable"?qt(t,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查"):e.verification_result==="pass"?VD(e):e.verification_result==="blocked"?qt(t,"Blocked","已阻塞"):e.verification_result==="fail"?qt(t,"Failed","未通过"):qt(t,"Pending","待处理")}function WD(e){let t=e.verification?.assurance??(e.builder_handoff?.identity_provider===xs?xs:"host-attested"),i=t===xs&&(e.archived||e.phase==="archive"&&e.loop.next_action==="archive");return(e.language==="en"?{"host-attested":"Host independently verified","skill-coordinated":i?"Checks completed; result confirmed":"Checks completed, but your confirmation is required","semantic-verification-unavailable":"Full verification was unavailable; only automatic checks completed","user-confirmed-degraded":"You accepted the incomplete verification result"}:{"host-attested":"已完成独立验证","skill-coordinated":i?"已完成检查,验证结果已确认":"已完成检查,但需要你确认验证结果","semantic-verification-unavailable":"无法完成完整验证,只完成了自动检查","user-confirmed-degraded":"你已确认接受不完整验证结果"})[t]??t}function zD(e,t){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let i=e.language,r=d=>fd(i,d),n=(d,f)=>qt(i,d,f),a=e.acceptance.map(d=>`| ${Bi(d.id)} | ${Bi(d.result)} | ${Bi(d.source)} | ${Bi(d.text)} | ${Bi(Br(d.reason))} |`).join(`
207
- `),o=e.verification.checks.length===0?`_${n("No Runtime checks were recorded.","没有记录 Runtime 检查。")}_`:[`| ${n("Check","检查")} | ${n("Command","命令")} | ${n("Working directory","工作目录")} | ${n("Status","状态")} | ${n("Exit","退出码")} | ${n("Duration","耗时")} |`,"| --- | --- | --- | --- | ---: | ---: |",...e.verification.checks.map(d=>{let f=d.argv_display.map(Br).join(" ");return`| ${Bi(Br(d.name))} | ${Bi(f||"—")} | ${Bi(d.cwd_ref)} | ${d.status} | ${d.exit_code??"—"} | ${d.duration_ms} ms |`})].join(`
208
- `),s=e.blockers.length===0?`_${n("None.","无。")}_`:e.blockers.map(d=>`- **${d.owner}**: ${Br(d.reason)}${d.acceptance_ids.length>0?` (acceptance: ${d.acceptance_ids.join(", ")})`:""} — next: \`${d.resolution_action}\``).join(`
209
- `),c=e.verification.risks.length===0?`_${n("None reported.","未报告风险。")}_`:e.verification.risks.map(d=>`- ${Br(d)}`).join(`
210
- `),l=e.history.length===0?`_${n("No previous iterations.","没有之前的迭代。")}_`:[`| ${n("Goal cycle","目标周期")} | ${n("Iteration","迭代")} | ${n("Attempt","尝试")} | ${n("Outcome","结果")} | ${n("Unresolved","未解决项")} | ${n("Summary","摘要")} | ${n("Completed","完成时间")} |`,"| ---: | ---: | ---: | --- | --- | --- | --- |",...e.history.map(d=>`| ${d.goal_cycle} | ${d.iteration} | ${d.attempt} | ${d.outcome} | ${d.unresolved_ids.join(", ")||"—"} | ${Bi(Br(d.summary))} | ${d.completed_at} |`)].join(`
198
+ ${e.sessionId}`)}:{}},h=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return ts(h),h}async function Xl(e){let t=await eb(e),i=ga(e.paths,e.name),r=j(e.paths,i);return await T(r,i),await ee(i,t,{containedRoot:r}),t}async function kt(e,t){let i=await QN(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(ts(i),i)}async function tb(e){return await Qh(e.paths,e.name)?Xl(e):null}async function is(e){ts(e.identity);let t=await eb({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),i=[],r=[];return t.nativeRootRef!==e.identity.nativeRootRef&&i.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&i.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&i.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&i.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&i.push("native-root-legacy-identity")),Yh==="win32"&&i.length>0&&i.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?r.push("workspace-inspection-unavailable"):i.length>0&&r.push("workspace-root-changed"),{state:r.length===0?"aligned":r.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:r,driftComponents:i}}async function wa(e){if(ts(e.identity),e.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await is(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=fe(e.paths.projectRoot);return e.identity.changeBranch===null?i.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:i.isGitWorktree?i.currentBranch!==e.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${e.identity.changeBranch}, but the current branch is ${i.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!i.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function ib(e,t){let i=await kt(e,t);if(i===null)return null;let r=await wa({paths:e,identity:i});if(r.state==="drifted")throw new Error(`${r.code}: ${r.message}`);return i}var nb=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],v$=new Set(nb),ab=new Set([...nb,"minimum_runtime_version","revision"]),g$=new Set([...ab,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),w$=new Set(["capability","operation","source","base_hash"]),y$=new Set(["shape","build","verify","archive"]),N$=new Set(["implicit","confirmed"]),b$=new Set(["pending","pass","fail"]),Ie="comet-state.yaml",ep=/^[a-f0-9]{64}$/u,ob=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,k$=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,rs=class extends Error{constructor(i,r){super(`Native change ${i} uses ${r}; run comet native doctor ${i} --repair before mutating it`);this.change=i;this.schema=r;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},mn=class extends Error{constructor(i,r){super(i!==Ne||r===null?`Unsupported Native change schema ${i} for runtime protocol ${3}`:`Native change ${i} requires runtime protocol ${r}; current protocol is ${3}`);this.schema=i;this.minimumRuntimeVersion=r;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},ns=class extends Error{constructor(i,r,n){super(`Native change ${i} revision conflict: expected ${r}, actual ${n}`);this.change=i;this.expectedRevision=r;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},as=class extends Error{constructor(i,r){super(`Native working directory already contains active change${r.length===1?"":"s"} ${r.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=i;this.activeChanges=r;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},ya=class extends Error{constructor(i,r,n,a,o,s=null,c=null){super(`Native change ${i} baseline is incomplete (${r} omitted entr${r===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=i;this.omittedCount=r;this.omittedByReason=n;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},G2=Xs("en");function ss(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function sb(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Zl(e){if(!ob.test(e))throw new Error(`Invalid Native change name: ${e}`)}function S$(e){if(!ob.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function cb(e,t){if(e.length===0||mi.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function E$(e,t){let i=ss(e,`spec_changes[${t}]`);if(sb(i,w$,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(S$(i.capability),i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`Invalid spec operation for ${i.capability}`);let r=i.source,n=i.base_hash;if(r!==void 0&&typeof r!="string")throw new Error(`Spec source for ${i.capability} must be a string`);if(typeof r=="string"&&cb(r,`Spec source for ${i.capability}`),i.operation==="create"){if(!r)throw new Error(`Create spec ${i.capability} requires source`);if(n!==null)throw new Error(`Create spec ${i.capability} requires null base_hash`)}else if(i.operation==="replace"){if(!r)throw new Error(`Replace spec ${i.capability} requires source`);if(typeof n!="string"||!ep.test(n))throw new Error(`Replace spec ${i.capability} requires a SHA-256 base_hash`)}else{if(r!==void 0)throw new Error(`Remove spec ${i.capability} forbids source`);if(typeof n!="string"||!ep.test(n))throw new Error(`Remove spec ${i.capability} requires a SHA-256 base_hash`)}return{capability:i.capability,operation:i.operation,...typeof r=="string"?{source:r}:{},base_hash:n}}function P$(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 tp(e,t){if(sb(e,t,Ie),typeof e.name!="string")throw new Error("Native change name is required");if(Zl(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"||!y$.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&&!N$.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let i=e.spec_changes.map(E$),r=i.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(r.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(r)].join(", ")}`);if(typeof e.verification_result!="string"||!b$.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"&&cb(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!P$(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:i,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function ln(e){let t=ss(e,Ie);if(t.schema!==et)throw new Error(`Expected ${et}`);return{schema:et,...tp(t,v$)}}function os(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Zh(e,t,i){if(e===null)return null;let r=typeof e=="string"?k$.exec(e):null;if(!r||r[1]!==i)throw new Error(`${t} must be null or runtime/evidence/${i}/<sha256>.json relative to the Native change`);return e}function R$(e){if(e==null)return null;if(typeof e!="string"||!ep.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function C$(e){if(e===void 0)return"legacy-v1";if(e!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return e}function di(e){let t=ss(e,Ie);if(t.schema!==be)throw new Error(`Expected ${be}`);if(os(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${be} minimum_runtime_version must be 2`);return{schema:be,minimum_runtime_version:2,revision:os(t.revision,"Native v2 revision"),...tp(t,ab)}}function lt(e){let t=ss(e,Ie);if(t.schema!==Ne){if(t.schema===et||t.schema===be){let o=t.schema===et?ln(t):di(t);throw new rs(o.name,o.schema)}throw new mn(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=os(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new mn(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let r=os(t.revision,"Native revision"),n=tp(t,g$),a=R$(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Ne,minimum_runtime_version:3,revision:r,verification_protocol:C$(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Zh(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Zh(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Zh(t.partial_allowance,"Native partial_allowance","allowances")}}function lb(e){let t=ss(e,Ie);if(t.schema===et){let n=ln(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Ne}`}}if(t.schema===be){let n=di(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Ne}`}}if(t.schema!==Ne){let n=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new mn(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let i=os(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new mn(t.schema,i).message};let r=lt(t);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function pn(e){let t=lt(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,verification_protocol:t.verification_protocol,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,approved_contract_hash:t.approved_contract_hash??null,spec_changes:t.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,implementation_scope:t.implementation_scope,verification_evidence:t.verification_evidence,partial_allowance:t.partial_allowance,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function eu(e){let t=di(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,spec_changes:t.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function ne(e,t){Zl(t);let i=mi.join(e.changesDir,t);if(!O(e.changesDir,i))throw new Error("Native change path escaped");return i}async function Na(e,t){let i=H(e,t),r=mi.join(i,"schema-migration.json");await T(O(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await rb.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function ba(e,t){let i=H(e,t),r=mi.join(i,"checkpoint-journal.json");await T(O(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await rb.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function tu(e,t=mi.dirname(e)){let i=mi.relative(t,e).split(mi.sep).join("/"),r=await Z({root:t,ref:i,maxBytes:null,includeHash:!1}),n=(0,Ql.parseDocument)(r.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function vi(e,t){let i=mi.join(ne(e,t),Ie);await T(e.nativeRoot,i);let r=lb(await tu(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await Na(e,t)?{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimumRuntimeVersion,state:r.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(r.status==="current"&&r.state&&await x$(e,r.state),r)}async function iu(e,t){let i=mi.join(ne(e,t),Ie);await T(e.nativeRoot,i);let r=lb(await tu(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return r}async function x$(e,t){if(await ha(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function De(e,t){let i=await vi(e,t);if(i.status==="migration-required")throw new rs(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new mn(i.schema,i.minimumRuntimeVersion);return await ib(e,t),i.state}async function ub(e,t,i){let r={...t,schema:Ne,minimum_runtime_version:3,revision:i+1},n=await lN({expectedRevision:i,next:r,read:async()=>{let a=lt(await tu(e));if(a.name!==t.name)throw new Error(`Native change file/name mismatch: ${t.name}`);return a},write:a=>he(e,(0,Ql.stringify)(pn(a))),equals:(a,o)=>JSON.stringify(pn(a))===JSON.stringify(pn(o)),conflict:a=>new ns(t.name,i,a)});return Object.assign(t,n),n}async function ru(e,t,i,r){if(await Yn(e.projectRoot),await Na(e,t.name))throw new rs(t.name,t.schema);if(!r?.allowPendingCheckpointRecovery&&await ba(e,t.name))throw new Error(`Native progress checkpoint recovery is required for ${t.name} before another state write`);if((await De(e,t.name)).verification_protocol!==t.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await Kl(e,t.name);let a=mi.join(ne(e,t.name),Ie);return await T(e.nativeRoot,a),ub(a,t,i)}async function db(e,t){return ub(e,t,t.revision)}async function fb(e){return lt(await tu(e))}var pb=["outcome","scope","nonGoals","acceptanceExamples"],A$=[...pb,"constraints","decisions","openQuestions","verificationExpectations"],_$=["acceptanceEvidence","commandsAndResults","skippedChecks","specConsistency","knownLimitationsAndRisks","conclusion"],mb={maxFileBytes:xo};function vb(e){let t=new Map,i=null,r=[],n=()=>{i!==null&&t.set(i,r.join(`
199
+ `).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(n(),i=o[1].trim(),r=[]):i!==null&&r.push(a)}return n(),t}async function T$(e,t){let i=hb.resolve(e,...t.split(/[\\/]/u));if(!O(e,i))throw new Error(`Artifact escapes Native change: ${t}`);let r=await ip.realpath(e),n=await ip.realpath(i);if(!O(r,n))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await ip.stat(n)).isFile())throw new Error(`Artifact is not a file: ${t}`);return n}function cs(e){return{valid:e.length===0,findings:e}}async function rp(e,t){let i=[],r;try{r=(await Z({root:e,ref:t,maxBytes:mb.maxFileBytes})).text}catch(o){return cs([{code:"brief-missing",message:o.message,path:t}])}let n=new Map;for(let[o,s]of vb(r))n.set(Ys(o)??o,s);for(let o of A$)n.has(o)||i.push({code:"brief-section-missing",message:`Missing brief section: ${o}`,path:t});for(let o of pb)(n.get(o)??"").length===0&&i.push({code:"brief-section-empty",message:`Brief section is empty: ${o}`,path:t});let a=n.get("openQuestions")??"";return/^\s*-\s*\[blocking\]/imu.test(a)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),cs(i)}async function np(e,t){let i=[],r;try{r=(await Z({root:e,ref:t,maxBytes:mb.maxFileBytes})).text}catch(a){return cs([{code:"verification-missing",message:a.message,path:t}])}let n=new Map;for(let[a,o]of vb(r))n.set(ev(a)??a,o);for(let a of _$)n.has(a)?(n.get(a)??"").length===0&&i.push({code:"verification-section-empty",message:`Verification section is empty: ${a}`,path:t}):i.push({code:"verification-section-missing",message:`Missing verification section: ${a}`,path:t});return cs(i)}function nu(e,t){return hb.join(e.specsDir,t,"spec.md")}async function gb(e,t){let i=[],r=ne(e,t.name);for(let n of t.spec_changes){let a=nu(e,n.capability),o=null;try{await T(e.nativeRoot,a),o=await ei(a)}catch(s){if(s.code!=="ENOENT"){i.push({code:"spec-canonical-unsafe",message:s.message,path:a});continue}}if(n.operation==="create"&&o!==null&&i.push({code:"spec-create-exists",message:`Canonical spec already exists: ${n.capability}`,path:a}),n.operation!=="create"&&o===null&&i.push({code:"spec-base-missing",message:`Canonical spec is missing: ${n.capability}`,path:a}),n.operation!=="create"&&o!==null&&o!==n.base_hash&&i.push({code:"spec-base-conflict",message:`Canonical spec changed for ${n.capability}: expected ${n.base_hash}, actual ${o}`,path:a}),n.source)try{await T$(r,n.source)}catch(s){i.push({code:"spec-source-invalid",message:s.message,path:n.source})}}return cs(i)}import{promises as DH}from"node:fs";import eS from"node:path";import wb from"node:path";var I$="comet.native.archive-preflight.v1",j$="comet.native.archive-preflight.v1",$$="comet.native.archive-operation.v1",O$=/^[a-f0-9]{64}$/u,yb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,H$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function au(e,t){return e<t?-1:e>t?1:0}function D$(e,t){if(typeof e!="string"||!O$.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Hi(e,t){return e===null?null:D$(e,t)}function L$(e,t){let i=wb.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||wb.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized Native-relative ref`);return e}function M$(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function F$(e){if(e==null)return null;if(e.schema!=="comet.native.workspace.v3")throw new Error("Native archive workspace schema is invalid");if(e.isolation!=="current"&&e.isolation!=="branch"&&e.isolation!=="worktree")throw new Error("Native archive workspace isolation is invalid");for(let[t,i]of[["change",e.changeBranch],["target",e.targetBranch]])if(i!==null&&(i.length===0||i.trim()!==i||Array.from(i).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})))throw new Error(`Native archive workspace ${t} branch is invalid`);if(e.finish!==null&&e.finish!=="merge"&&e.finish!=="push"&&e.finish!=="pull-request"&&e.finish!=="keep")throw new Error("Native archive workspace finish is invalid");if((e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null||e.finish===null))throw new Error("Native isolated archive workspace requires branches and a finish action");if(e.isolation==="current"&&e.finish!==null)throw new Error("Native current archive workspace cannot have a finish action");return{...e}}function B$(e,t){if(!yb.test(e.capability))throw new Error(`Native archive spec ${t} capability is invalid`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Native archive spec ${e.capability} operation is invalid`);let i=Hi(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),r=Hi(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=Hi(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&i!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&i===null)throw new Error(`Native archive ${e.operation} ${e.capability} requires a base hash`);if(e.operation==="remove"!=(n===null))throw new Error(`Native archive ${e.operation} ${e.capability} proposed hash is invalid`);return{capability:e.capability,operation:e.operation,expectedBaseHash:i,actualBaseHash:r,proposedHash:n}}function V$(e){if(e.result!=="pending"&&e.result!=="pass"&&e.result!=="fail")throw new Error("Native archive verification result is invalid");if(!["missing","invalid","stale","complete","partial"].includes(e.freshness))throw new Error("Native archive verification freshness is invalid");if(!Number.isSafeInteger(e.skippedAcceptanceCount)||e.skippedAcceptanceCount<0)throw new Error("Native archive skipped acceptance count is invalid");let t={result:e.result,freshness:e.freshness,contractHash:Hi(e.contractHash,"Native archive contract hash"),acceptanceHash:Hi(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:Hi(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:Hi(e.reportHash,"Native archive report hash"),envelopeHash:Hi(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:Hi(e.partialAllowanceHash,"Native archive partial allowance hash"),skippedAcceptanceCount:e.skippedAcceptanceCount};if((e.freshness==="complete"||e.freshness==="partial")&&[t.contractHash,t.acceptanceHash,t.implementationScopeHash,t.reportHash,t.envelopeHash].some(i=>i===null))throw new Error("Fresh Native archive evidence requires every bound content hash");if(e.freshness==="partial"&&t.partialAllowanceHash===null||e.freshness==="complete"&&t.partialAllowanceHash!==null)throw new Error("Native archive partial evidence allowance state is invalid");return t}function q$(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(r=>{if(typeof r!="string"||!H$.test(r))throw new Error(`Native archive preflight finding code is invalid: ${String(r)}`);return r}),i=[...new Set(t)].sort(au);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function W$(e){let t=[];e.phase!=="archive"&&t.push("archive-phase-required"),e.archived&&t.push("change-already-archived"),e.pendingJournal&&t.push("pending-journal"),e.targetExists&&t.push("archive-target-exists"),e.evidence.result!=="pass"&&t.push("verification-not-passed"),e.evidence.freshness==="missing"&&t.push("verification-evidence-missing"),e.evidence.freshness==="invalid"&&t.push("verification-evidence-invalid"),e.evidence.freshness==="stale"&&t.push("verification-evidence-stale"),e.evidence.skippedAcceptanceCount>0&&t.push("verification-acceptance-skipped");for(let i of e.specs)i.actualBaseHash!==i.expectedBaseHash&&t.push("spec-base-conflict");return[...new Set(t)].sort(au)}function Nb(e){if(!yb.test(e.change))throw new Error("Native archive change name is invalid");if(typeof e.stateSchema!="string"||e.stateSchema.length===0)throw new Error("Native archive state schema is invalid");if(!Array.isArray(e.specs)||e.specs.length>64)throw new Error("Native archive preflight exceeds its spec budget");let t=e.specs.map(B$).sort((l,u)=>au(l.capability,u.capability));if(new Set(t.map(l=>l.capability)).size!==t.length)throw new Error("Native archive preflight contains duplicate capabilities");let i=t.map(l=>({...l,operationHash:D($$,l)})),r=V$(e.evidence),n=F$(e.workspace),a=[...new Set([...q$(e.findingCodes??[]),...W$({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:r})])].sort(au),o=M$(e.revision),s=L$(e.targetRef,"Native archive target");if(e.archiveConfirmation!=="automatic"&&e.archiveConfirmation!=="required")throw new Error("Native archive confirmation must be automatic or required");let c={stateSchema:e.stateSchema,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetRef:s,targetExists:e.targetExists,operations:i,evidence:r,workspace:n,findingCodes:a};return{schema:I$,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:r.freshness,operationCount:i.length,operations:i,workspace:n,findingCodes:a,preflightHash:D(j$,c)}}import{createHash as z$}from"node:crypto";import bb from"node:path";var J$="comet.native.conflict-radar.v1",ut=Object.freeze({maxChanges:32,maxSpecsPerChange:64,maxArtifactsPerChange:128,maxTotalSpecs:512,maxTotalArtifacts:1024,maxSignalsPerRelationship:8,maxRelationships:256,maxSerializedBytes:64*1024,maxNameBytes:128,maxCapabilityBytes:128,maxArtifactPathBytes:512}),G$="comet.native.conflict-radar.v1",U$="comet.native.conflict-radar-signals.v1",K$=/^[a-f0-9]{64}$/u,Eb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Y$=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),X$=new Set(["capability","operation","baseHash"]),Q$=new Set(["path","kind"]);function ka(e,t){return e<t?-1:e>t?1:0}function ap(e){return Buffer.byteLength(e,"utf8")}function op(e,t,i){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${i} must be an object`);let r=e,n=Object.keys(r).filter(a=>!t.has(a));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);return r}function sp(e,t,i){if(typeof e!="string"||e.length===0||e!==e.trim())throw new Error(`${t} must be a non-empty trimmed string`);if(ap(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function Z$(e,t){let i=sp(e,t,ut.maxArtifactPathBytes),r=bb.posix.normalize(i);if(i.includes("\\")||Array.from(i).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(i)||bb.posix.isAbsolute(r)||i.split("/").includes("..")||r!==i||r==="."||i.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return i}function Pb(e,t){if(typeof e!="string"||!K$.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function eO(e,t){let i=op(e,X$,t),r=sp(i.capability,`${t} capability`,ut.maxCapabilityBytes);if(!Eb.test(r))throw new Error(`${t} capability is invalid`);if(i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`${t} operation is invalid`);let n=i.baseHash===null?null:Pb(i.baseHash,`${t} canonical base hash`);if(i.operation==="create"&&n!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(i.operation!=="create"&&n===null)throw new Error(`${t} ${i.operation} operation requires a canonical base hash`);return{capability:r,operation:i.operation,baseHash:n}}function tO(e,t){let i=op(e,Q$,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:Z$(i.path,`${t} path`),kind:i.kind}}function iO(e,t){let i=op(e,Y$,`Conflict radar change ${t}`),r=sp(i.name,`Conflict radar change ${t} name`,ut.maxNameBytes);if(!Eb.test(r))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(i.revision)||i.revision<1)throw new Error(`Conflict radar change ${r} revision must be a positive safe integer`);if(!Array.isArray(i.specs))throw new Error(`Conflict radar change ${r} specs must be an array`);if(i.specs.length>ut.maxSpecsPerChange)throw new Error(`Conflict radar change ${r} exceeds the spec budget`);if(!Array.isArray(i.declaredArtifacts))throw new Error(`Conflict radar change ${r} declared artifacts must be an array`);if(i.declaredArtifacts.length>ut.maxArtifactsPerChange)throw new Error(`Conflict radar change ${r} exceeds the declared artifact budget`);let n=i.specs.map((c,l)=>eO(c,`Conflict radar change ${r} spec ${l}`)).sort((c,l)=>ka(c.capability,l.capability));if(new Set(n.map(c=>c.capability)).size!==n.length)throw new Error(`Conflict radar change ${r} has duplicate capabilities`);let a=i.declaredArtifacts.map((c,l)=>tO(c,`Conflict radar change ${r} artifact ${l}`)).sort((c,l)=>ka(c.path,l.path)||ka(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${r} has duplicate or conflicting artifact paths`);let s=i.workspaceIdentityHash===void 0||i.workspaceIdentityHash===null?null:Pb(i.workspaceIdentityHash,`Conflict radar change ${r} workspace identity hash`);return{name:r,revision:i.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function rO(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>ut.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(iO).sort((n,a)=>ka(n.name,a.name));if(new Set(t.map(n=>n.name)).size!==t.length)throw new Error("Native conflict radar contains duplicate change names");if(t.reduce((n,a)=>n+a.specs.length,0)>ut.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>ut.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function nO(e,t){let i=e.baseHash!==null&&e.baseHash===t.baseHash;return{kind:"capability",certainty:e.operation==="create"||t.operation==="create"||i?"definite-conflict":"possible-overlap",capability:e.capability,leftOperation:e.operation,rightOperation:t.operation,leftBaseHash:e.baseHash,rightBaseHash:t.baseHash}}function aO(e,t){let i=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),r=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),n=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!i&&!r&&!n?null:{kind:"artifact",certainty:n?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function oO(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function sO(e,t){let i=[],r=z$("sha256").update(`${U$}
200
+ [`),n=0,a=!1,o=l=>{n>0&&r.update(","),r.update(Mo(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),i.length<ut.maxSignalsPerRelationship&&i.push(l)},s=new Map(t.specs.map(l=>[l.capability,l]));for(let l of e.specs){let u=s.get(l.capability);u&&o(nO(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=aO(l,u);d&&o(d)}let c=a?"definite-conflict":n>0?"possible-overlap":"disjoint";return r.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:oO(e,t),signalCount:n,signalHash:r.digest("hex"),signals:i,signalsTruncated:i.length!==n}}function kb(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function cO(e,t){return kb(e.classification)-kb(t.classification)||ka(e.left,t.left)||ka(e.right,t.right)}function Sb(e,t,i,r){let n={definiteConflict:t.filter(({classification:a})=>a==="definite-conflict").length,possibleOverlap:t.filter(({classification:a})=>a==="possible-overlap").length,disjoint:t.filter(({classification:a})=>a==="disjoint").length};return{schema:J$,workspaceIdentityAdvisoryOnly:!0,changeCount:e.length,relationshipCount:t.length,counts:n,relationships:i,relationshipsTruncated:i.length!==t.length,omittedRelationshipCount:t.length-i.length,radarHash:r}}function Rb(e){let t=rO(e),i=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)i.push(sO(t[s],t[c]));i.sort(cO);let r=i.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=D(G$,{changes:t,relationships:r}),a=i.slice(0,ut.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=Sb(t,i,a,n);for(;a.length>0&&ap(JSON.stringify(o))>ut.maxSerializedBytes;)a=a.slice(0,-1),o=Sb(t,i,a,n);if(ap(JSON.stringify(o))>ut.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as y0}from"node:crypto";import{promises as ni}from"node:fs";import yi from"node:path";import{createHash as $b}from"node:crypto";import Cb from"path";var cp="comet.native.implementation-scope.v2",Ob="comet.native.content-snapshot-projection.v1",ls="comet.native.content-snapshot-projection.v1",Hb="comet.native.implementation-scope.v2",lO="comet.native.unresolved-scope-id.v1",uO="comet.native.scope-detail-overflow.v1",dO="comet.native.snapshot-projection-overflow.v2",fp=/^[a-f0-9]{64}$/u,gn=1024*1024,fO=128,hO=128;function Ge(e,t){return e<t?-1:e>t?1:0}function lp(e){if(!fp.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function pO(e,t){return e===t?0:e===null?-1:t===null?1:Ge(e,t)}function xr(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a normalized project-relative path`);let i=Cb.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||Cb.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function Db(e,t){return e==="."?e:xr(e,t)}function Sa(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function mO(e,t){if(e.type!=="file")throw new Error(`${t} must describe a file`);if(typeof e.hash!="string"||e.hash.length===0)throw new Error(`${t} hash must be non-empty`);return{path:xr(e.path,`${t} path`),hash:e.hash,size:Sa(e.size,`${t} size`),type:"file"}}function vO(e,t){return{path:Db(e.path,`${t} path`),size:e.size===null?null:Sa(e.size,`${t} size`),type:e.type,reason:e.reason}}function gO(e,t){return Ge(e.path,t.path)||Ge(e.hash,t.hash)||e.size-t.size}function wO(e,t){return Ge(e.path,t.path)||Ge(e.reason,t.reason)||Ge(e.type,t.type)||(e.size??-1)-(t.size??-1)}function ds(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
201
+ `,"utf8")}function Cr(e,t,i){let r=`${t}
202
+ ${Mo(i)}`;e.update(`${Buffer.byteLength(r,"utf8")}:`),e.update(r)}function yO(e){if(ds(e)<=gn)return e;let t=[...e.entries],i=[...e.omitted],r=e.omittedCount,n=e.omissionOverflow?.count??0,a=$b("sha256");a.update(`${dO}
203
+ `),e.omissionOverflow&&Cr(a,"existing-overflow",e.omissionOverflow);let o=(f,h)=>{h||(r+=1),n+=1,Cr(a,"omission",f)},s=f=>{r+=1,n+=1,Cr(a,"entry",f)},c=()=>{for(let f=i.length-1;f>=0;f-=1){let h=i[f];if(!(h.reason==="git-enumeration-limit"||h.reason==="git-selection-changed"||h.reason==="physical-enumeration-limit"||h.reason==="physical-selection-changed"))return i.splice(f,1),h}return null},l=()=>({...e,complete:r===0,entries:t,omitted:i,omittedCount:r,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:n}}),u=l();for(;ds(u)>gn;){if(i.filter(h=>h.reason!=="git-enumeration-limit"&&h.reason!=="git-selection-changed"&&h.reason!=="physical-enumeration-limit"&&h.reason!=="physical-selection-changed").length>0){let h=Math.max(1,Math.ceil(i.length/4));for(let v=0;v<h;v+=1){let m=c();if(m===null)break;o(m,!0)}}else if(t.length>0){let h=Math.max(1,Math.ceil(t.length/4));for(let v of t.splice(-h))s(v)}else throw new Error("Native snapshot projection metadata exceeds its evidence byte budget");u=l()}let d=a.digest("hex");return{...u,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${d}`,hash:d,count:n}}}function up(e){let t=$i(e),i=t.entries.map((n,a)=>mO(n,`Snapshot entry ${a}`));if(i.sort(gO),new Set(i.map(n=>n.path)).size!==i.length)throw new Error("Snapshot entries must not contain duplicate paths");let r=t.omitted.map((n,a)=>vO(n,`Snapshot omission ${a}`));return r.sort(wO),yO({schema:Ob,origin:t.origin,...t.capture?{capture:t.capture}:{},complete:t.complete,limits:{maxFiles:t.limits.maxFiles,maxFileBytes:t.limits.maxFileBytes,maxTotalBytes:t.limits.maxTotalBytes,maxManifestBytes:t.limits.maxManifestBytes,...t.limits.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},...t.policy?{policy:t.policy}:{},entries:i,omitted:r,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:{ref:t.omissionOverflow.ref,hash:t.omissionOverflow.hash,count:t.omissionOverflow.count}}:{}})}function fs(e){let t=new Map;for(let[i,r]of e.entries()){if(r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${i} kind is invalid`);let n={path:xr(r.path,`Declared artifact ${i} path`),kind:r.kind},a=t.get(n.path);if(a&&a.kind!==n.kind)throw new Error(`Declared artifact path has conflicting kinds: ${n.path}`);t.set(n.path,n)}return[...t.values()].sort((i,r)=>Ge(i.path,r.path)||Ge(i.kind,r.kind))}function hs(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function xb(e){return e?{hash:e.hash,size:e.size}:null}function hp(e,t,i){let r=0,n=0;for(;r<e.entries.length||n<t.entries.length;){let a=e.entries[r],o=t.entries[n],s=a===void 0?1:o===void 0?-1:Ge(a.path,o.path),c=s<=0?a:void 0,l=s>=0?o:void 0;if(s<=0&&(r+=1),s>=0&&(n+=1),c&&l&&c.hash===l.hash&&c.size===l.size||c&&!l&&!t.complete)continue;let u=c?.path??l?.path;u!==void 0&&i({path:u,kind:c?l?"modified":"removed":"added",before:xb(c),after:xb(l)})}}function Lb(e,t){return{...e,attributedTo:t.filter(i=>hs(i,e.path))}}function pp(e){let t=fs(e.declaredArtifacts),i=[];return hp(e.baseline,e.current,r=>{i.push(Lb(r,t))}),i}function Di(e,t){return{id:`scope:${D(lO,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function NO(e,t){let i=t.omitted.map(r=>Di({kind:"snapshot-omission",source:e,path:r.path,evidence:{reason:r.reason,size:r.size,type:r.type}},`${e} snapshot omitted ${r.path}: ${r.reason}`));return t.complete||i.push(Di({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&i.push(Di({kind:"snapshot-omission-overflow",source:e,path:null,evidence:{count:t.omissionOverflow.count,hash:t.omissionOverflow.hash,ref:t.omissionOverflow.ref}},`${e} snapshot has ${t.omissionOverflow.count} unlisted omissions`)),i}function Ab(e,t){return NO(e,{...t,omitted:[]}).filter(i=>i.kind!=="snapshot-omission")}function dp(e,t){return Ge(e.kind,t.kind)||Ge(e.source,t.source)||pO(e.path,t.path)||Ge(e.id,t.id)}function bO(e){return[...new Map(e.map(i=>[i.id,i])).values()].sort(dp)}function Mb(e){return[...new Set(e.map((t,i)=>xr(t,`Git path ${i}`)))].sort(Ge)}function _b(e,t){if(typeof e!="string"||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(e))throw new Error(`${t} must be a Git commit object id`);return e}function kO(e,t){if(typeof e!="string"||e.length===0||e.trim()!==e||e.includes("\\")||e.includes("\0")||e.startsWith("-"))throw new Error(`${t} must be a valid Git branch name`);return e}function Fb(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=Mb(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:_b(e.baseCommit,"Native external drift base commit"),targetBranch:kO(e.targetBranch,"Native external drift target branch"),targetCommit:_b(e.targetCommit,"Native external drift target commit"),paths:t}}function Bb(e){if(typeof e.contractHash!="string"||!fp.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:fs(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:Mb(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:Fb(e.externalDrift)}}}function SO(e,t,i,r,n){let a=[],o=r===void 0?null:new Set(r),s=[],c=[],l=0,u=!1,d=0,f=0;return hp(e,t,h=>{let v=i.some(m=>hs(m,h.path));if(d+=1,c.push(h.path),!v&&!n?.has(h.path)&&(f+=1),o?.has(h.path)&&s.push(h.path),!u&&a.length<fO){let m=Lb(h,i),p=ds(m);l+p<=gn?(a.push(m),l+=p):u=!0}}),{candidates:a,gitPathsPresentInChanges:s,changePaths:c,totalChanges:d,totalUnattributed:f}}function Vb(e,t){return Di({kind:"scope-detail-overflow",source:"implementation-scope",path:null,evidence:{changeCount:t.changes,hash:e,unattributedCount:t.unattributed,unresolvedCount:t.unresolved}},`Implementation scope summarized ${t.changes} additional change details and ${t.unresolved} unresolved details (${t.unattributed} unattributed); overflow hash ${e}`)}function EO(e){let t=/^Implementation scope summarized ([0-9]+) additional change details and ([0-9]+) unresolved details \(([0-9]+) unattributed\); overflow hash ([a-f0-9]{64})$/u.exec(e.reason);if(!t)throw new Error("Implementation scope detail overflow is invalid");let i={changes:Sa(Number(t[1]),"Scope overflow change count"),unresolved:Sa(Number(t[2]),"Scope overflow unresolved count"),unattributed:Sa(Number(t[3]),"Scope overflow unattributed count")},r=vn(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(Vb(r,i)))throw new Error("Implementation scope detail overflow is inconsistent");return{...i,hash:r}}function PO(e){let t=$b("sha256");t.update(`${uO}
204
+ `);let i=0;hp(e.baseline,e.current,n=>{if(i>=e.detailedChangeCount){Cr(t,"change",n);let a=0;for(let o of e.declaredArtifacts)hs(o,n.path)&&(a+=1,Cr(t,"change-attribution",o));Cr(t,"change-end",{attributionCount:a}),a===0&&Cr(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}i+=1});let r=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)r>=e.detailedOmissionCount&&Cr(t,"snapshot-omission",{source:n,...o}),r+=1;return t.digest("hex")}function qb(e,t,i){let{contractHash:r,declaredArtifacts:n,noCodeReason:a}=i,o=SO(e,t,n,i.gitChangedPaths,i.externalDrift?new Set(i.externalDrift.paths):void 0);if(i.externalDrift){let R=new Set(i.externalDrift.paths),N=new Set(o.changePaths),w=i.externalDrift.paths.filter(P=>!N.has(P)||n.some(F=>hs(F,P)));if(w.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${w.slice(0,8).join(", ")}`);if(R.size!==i.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=D(ls,e),c=D(ls,t),l=[],u=new Set(i.externalDrift?.paths??[]);for(let[R,N]of[["baseline",e],["current",t]])for(let w of N.omitted){if(l.length>=hO)break;l.push(Di({kind:"snapshot-omission",source:R,path:w.path,evidence:{reason:w.reason,size:w.size,type:w.type}},`${R} snapshot omitted ${w.path}: ${w.reason}`))}let d=e.omitted.length+t.omitted.length,f=[...Ab("baseline",e),...Ab("current",t),...o.totalChanges===0&&a===null?[Di({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:s,currentProjectionHash:c}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],h=()=>{if(i.gitChangedPaths===void 0)return;let R=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:i.gitChangedPaths,pathsPresentInSnapshotChanges:i.gitChangedPaths.filter(N=>R.has(N)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(N=>!R.has(N))}},v=R=>{let N=o.candidates.slice(0,R.detailedChangeCount),w=N.filter(Vt=>Vt.attributedTo.length===0&&!u.has(Vt.path)),P=o.totalChanges-N.length,F=o.totalUnattributed-w.length,$=d-R.detailedOmissionCount,Be=F+$,ue=[...w.map(Vt=>Di({kind:"unattributed-change",source:"implementation-scope",path:Vt.path,evidence:{after:Vt.after,before:Vt.before,changeKind:Vt.kind}},`Changed path is not covered by a declared artifact: ${Vt.path}`)),...l.slice(0,R.detailedOmissionCount),...f,...Be>0?[Vb(R.overflowHash,{changes:P,unattributed:F,unresolved:Be})]:[]],te=bO(ue),oi=R.includeGitAdvisory?h():void 0;return{schema:cp,contractHash:r,baselineProjectionRef:lp(s),baselineProjectionHash:s,currentProjectionRef:lp(c),currentProjectionHash:c,complete:te.length===0,declaredArtifacts:n,changes:N,unattributed:w,unresolvedScopes:te,noCodeReason:a,...oi?{gitAdvisory:oi}:{},...i.externalDrift?{externalDrift:i.externalDrift}:{}}},m=o.candidates.length,p=l.length,b=i.gitChangedPaths!==void 0,g="0".repeat(64);for(;;){let R=v({detailedChangeCount:m,detailedOmissionCount:p,includeGitAdvisory:b,overflowHash:g});if(ds({...R,scopeHash:g})<=gn)break;if(b){b=!1;continue}if(p>0){p-=Math.max(1,Math.ceil(p/4));continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let E=o.totalChanges>m||d>p?PO({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:m,detailedOmissionCount:p}):g,k=v({detailedChangeCount:m,detailedOmissionCount:p,includeGitAdvisory:b,overflowHash:E}),S={...k,scopeHash:D(Hb,k)};if(ds(S)>gn)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return S}function mp(e){let t=up(e.baseline),i=up(e.current),r=Bb(e);return{authority:r,baseline:t,current:i,scope:qb(t,i,r)}}var RO=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"]);function gi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function wi(e,t,i,r){let n=new Set([...t,...i]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${r} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${r} is missing field(s): ${o.join(", ")}`)}function vn(e,t){if(typeof e!="string"||!fp.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Tb(e,t,i){let r=lp(t);if(e!==r)throw new Error(`${i} ref/hash mismatch`);return r}function Ea(e,t){let i=gi(e,"Native snapshot projection");if(wi(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==Ob)throw new Error("Native snapshot projection schema is invalid");let r=$i({schema:"comet.native.content-snapshot.v1",origin:i.origin,...i.capture===void 0?{}:{capture:i.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:i.complete,limits:i.limits,...i.policy===void 0?{}:{policy:i.policy},entries:i.entries,omitted:i.omitted,omittedCount:i.omittedCount,...i.omissionOverflow===void 0?{}:{omissionOverflow:i.omissionOverflow}}),n=up(r);if(D(ls,i)!==D(ls,n))throw new Error("Native snapshot projection is not canonical");let a=D(ls,n);if(t!==void 0&&vn(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function vp(e,t){let i=gi(e,`Declared artifact ${t}`);if(wi(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:xr(i.path,`Declared artifact ${t} path`),kind:i.kind}}function Ib(e,t){if(e===null)return null;let i=gi(e,t);return wi(i,["hash","size"],[],t),{hash:vn(i.hash,`${t} hash`),size:Sa(i.size,`${t} size`)}}function jb(e,t){let i=gi(e,`Implementation change ${t}`);if(wi(i,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),i.kind!=="added"&&i.kind!=="modified"&&i.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(i.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let r=i.attributedTo.map(vp),n=fs(r);if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=Ib(i.before,`Implementation change ${t} before`),o=Ib(i.after,`Implementation change ${t} after`);if(i.kind==="added"&&(a!==null||o===null)||i.kind==="removed"&&(a===null||o!==null)||i.kind==="modified"&&(a===null||o===null||JSON.stringify(a)===JSON.stringify(o)))throw new Error(`Implementation change ${t} before/after state is invalid`);return{path:xr(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:r}}function CO(e,t){let i=gi(e,`Unresolved scope ${t}`);wi(i,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let r=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof i.kind!="string"||!r.has(i.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(i.source!=="baseline"&&i.source!=="current"&&i.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof i.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(i.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(i.path!==null&&typeof i.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof i.reason!="string"||i.reason.length===0||i.reason.trim()!==i.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:i.id,kind:i.kind,source:i.source,path:i.path===null?null:i.kind==="snapshot-omission"?Db(i.path,`Unresolved scope ${t} path`):xr(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function us(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of paths`);let i=e.map((n,a)=>xr(n,`${t} ${a}`)),r=[...new Set(i)].sort(Ge);if(JSON.stringify(i)!==JSON.stringify(r))throw new Error(`${t} must be sorted and unique`);return i}function Wb(e){let t=gi(e,"Native implementation external drift");if(wi(t,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),t.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let i=us(t.paths,"Native external drift paths");return Fb({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:i})}function Pa(e){let t=gi(e,"Native implementation scope"),i=[...RO].filter(w=>w!=="gitAdvisory"&&w!=="externalDrift");if(wi(t,i,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==cp)throw new Error("Native implementation scope schema is invalid");let r=vn(t.contractHash,"Implementation scope contractHash"),n=vn(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=Tb(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=vn(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=Tb(t.currentProjectionRef,o,"Implementation scope current projection");if(typeof t.complete!="boolean")throw new Error("Implementation scope complete flag is invalid");if(!Array.isArray(t.declaredArtifacts)||!Array.isArray(t.changes)||!Array.isArray(t.unattributed)||!Array.isArray(t.unresolvedScopes))throw new Error("Implementation scope collections are invalid");let c=t.declaredArtifacts.map(vp);if(JSON.stringify(c)!==JSON.stringify(fs(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(jb),u=[...l].sort((w,P)=>Ge(w.path,P.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(w=>w.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(w=>`${w.kind}:${w.path}`));if(l.some(w=>w.attributedTo.some(P=>!d.has(`${P.kind}:${P.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(w=>JSON.stringify(w.attributedTo)!==JSON.stringify(c.filter(P=>hs(P,w.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(jb),h=t.externalDrift===void 0?void 0:Wb(t.externalDrift),v=new Set(h?.paths??[]),m=l.filter(w=>w.attributedTo.length===0&&!v.has(w.path));if(JSON.stringify(f)!==JSON.stringify(m))throw new Error("Implementation scope unattributed changes are inconsistent");let p=t.unresolvedScopes.map(CO),b=p.filter(w=>w.kind==="scope-detail-overflow");if(b.length>1)throw new Error("Implementation scope has multiple detail overflow records");let g=b[0]===void 0?null:EO(b[0]);if(g&&(g.changes+g.unresolved===0||g.unattributed>g.changes||g.unattributed>g.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let y=t.noCodeReason,E=[...m.map(w=>Di({kind:"unattributed-change",source:"implementation-scope",path:w.path,evidence:{after:w.after,before:w.before,changeKind:w.kind}},`Changed path is not covered by a declared artifact: ${w.path}`)),...l.length+(g?.changes??0)===0&&y===null?[Di({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:n,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],k=p.filter(w=>w.kind==="unattributed-change"||w.kind==="missing-no-code-reason");if(JSON.stringify(p)!==JSON.stringify([...p].sort(dp))||new Set(p.map(w=>w.id)).size!==p.length||JSON.stringify(k)!==JSON.stringify(E.sort(dp))||t.complete!==(p.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let S;if(t.gitAdvisory!==void 0){let w=gi(t.gitAdvisory,"Implementation scope Git advisory");if(wi(w,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),w.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let P=us(w.changedPaths,"Git changed paths"),F=us(w.pathsPresentInSnapshotChanges,"Git present paths"),$=us(w.pathsAbsentFromSnapshotChanges,"Git absent paths"),Be=[...F,...$].sort(Ge);if(JSON.stringify(Be)!==JSON.stringify(P)||$.some(ue=>l.some(te=>te.path===ue)))throw new Error("Implementation scope Git advisory partition is invalid");S={advisoryOnly:!0,changedPaths:P,pathsPresentInSnapshotChanges:F,pathsAbsentFromSnapshotChanges:$}}let R={schema:cp,contractHash:r,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:p,noCodeReason:y,...S?{gitAdvisory:S}:{},...h?{externalDrift:h}:{}},N=vn(t.scopeHash,"Implementation scope scopeHash");if(D(Hb,R)!==N)throw new Error("Implementation scope content hash mismatch");return{...R,scopeHash:N}}function xO(e){let t=gi(e,"Native implementation scope authority");if(wi(t,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths","externalDrift"],"Native implementation scope authority"),!Array.isArray(t.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let i=t.declaredArtifacts.map(vp);if(JSON.stringify(i)!==JSON.stringify(fs(i)))throw new Error("Native implementation scope authority declarations must be canonical");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let r;t.gitChangedPaths!==void 0&&(r=us(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:Wb(t.externalDrift),a=Bb({contractHash:t.contractHash,declaredArtifacts:i,noCodeReason:t.noCodeReason,...r===void 0?{}:{gitChangedPaths:r},...n===void 0?{}:{externalDrift:n}});if(a.contractHash!==t.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return a}function ps(e){let t=gi(e,"Native implementation scope bundle");wi(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=xO(t.authority),r=Ea(t.baseline),n=Ea(t.current),a=Pa(t.scope),o=qb(r,n,i);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:i,baseline:r,current:n,scope:o}}function zb(e){let t=Pa(e.scope);return ps({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{},...t.externalDrift?{externalDrift:t.externalDrift}:{}},baseline:e.baseline,current:e.current,scope:t})}import Jb from"node:path";var AO=/\b(Bearer|Basic)\s+[^\s"']+/giu,_O=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,TO=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,IO=/\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,jO=/("(?:[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,$O=/(["'])((?:[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,OO=/\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(AO,"$1 [REDACTED]").replace(_O,"[REDACTED PRIVATE KEY]").replace(TO,"$1[REDACTED]@").replace(IO,"[REDACTED TOKEN]").replace(jO,'$1"[REDACTED]"').replace($O,"$1$2$1$3$4[REDACTED]$4").replace(OO,"$1$2[REDACTED]")}var Ub=/^[a-f0-9]{64}$/u;var HO="comet.native.acceptance-trace.v2",DO="comet.native.partial-allowance.v1",LO="comet.native.verification-evidence.v2";function Li(e,t){if(!Ub.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Kb(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function Yb(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native evidence change name: ${e}`);return e}function gp(e,t,i=2e3){let r=$t(e).trim();if(r.length===0||r.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return r}function ms(e,t){let i=Jb.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||Jb.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function MO(e,t,i){let r=ms(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(r))return r;let n=li(r),a=r.toLowerCase(),o=i?ms(i,"Native root ref").toLowerCase():null;if(n||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${t} is excluded as sensitive (${n??"native-runtime"}): ${r}`);return r}function wp(e){let t=ms(e,"Verification typed receipt ref");if(!/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u.test(t))throw new Error("Verification receipt ref must identify a typed v3 receipt");return t}function Ra(e,t){return e<t?-1:e>t?1:0}function ou(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function su(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function Xb(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function Gb(e,t,i){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let r=`runtime/evidence/${t}/${i}.json`;if(e!==r)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function FO(e){let t=ou(e,"Native acceptance trace");if(su(t,["schema","nativeRootRef","criteriaHash","total","evidenced","skipped","entries","traceHash"],"Native acceptance trace"),t.schema!=="comet.native.acceptance-trace.v2"||typeof t.nativeRootRef!="string"||typeof t.criteriaHash!="string"||!Ub.test(t.criteriaHash)||!Number.isSafeInteger(t.total)||!Number.isSafeInteger(t.evidenced)||!Number.isSafeInteger(t.skipped)||!Array.isArray(t.entries))throw new Error("Native acceptance trace is invalid");let i=ms(t.nativeRootRef,"Native root ref"),r=t.entries.map((o,s)=>{let c=ou(o,`Native acceptance trace entry ${s}`);if(su(c,["acceptanceId","status","kind","source","evidenceRefs","skippedReason"],`Native acceptance trace entry ${s}`),typeof c.acceptanceId!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(c.acceptanceId)||c.kind!=="brief-example"&&c.kind!=="spec-scenario"&&c.kind!=="spec-must"||typeof c.source!="string"||!Array.isArray(c.evidenceRefs)||c.status!=="passed"&&c.status!=="failed"&&c.status!=="missing"||c.evidenceRefs.some(d=>typeof d!="string")||c.skippedReason!==null&&(typeof c.skippedReason!="string"||c.skippedReason.length===0||c.skippedReason.trim()!==c.skippedReason))throw new Error(`Native acceptance trace entry ${s} is invalid`);let l=c.evidenceRefs.map(d=>wp(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Ra))||u==="passed"&&(l.length===0||c.skippedReason!==null)||u==="failed"&&l.length===0&&c.skippedReason===null||u==="missing"&&(l.length>0||c.skippedReason!==null))throw new Error(`Native acceptance trace entry ${s} evidence state is invalid`);return{acceptanceId:c.acceptanceId,status:u,kind:c.kind,source:ms(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:gp(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(r)!==JSON.stringify([...r].sort((o,s)=>Ra(o.acceptanceId,s.acceptanceId)))||new Set(r.map(o=>o.acceptanceId)).size!==r.length||t.total!==r.length||t.evidenced!==r.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==r.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let n={schema:"comet.native.acceptance-trace.v2",nativeRootRef:i,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:r},a=Li(t.traceHash,"Native acceptance trace hash");if(D(HO,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function cu(e){let t=ou(e,"Native partial allowance");if(su(t,["schema","change","scopeHash","scopeIds","reason","confirmedSummary","sourceRevision","confirmedAt","allowanceHash"],"Native partial allowance"),t.schema!=="comet.native.partial-allowance.v1"||typeof t.change!="string"||typeof t.scopeHash!="string"||!Array.isArray(t.scopeIds)||t.scopeIds.length===0||t.scopeIds.some(n=>typeof n!="string"||!/^scope:[a-f0-9]{64}$/u.test(n))||JSON.stringify(t.scopeIds)!==JSON.stringify([...new Set(t.scopeIds)].sort(Ra))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let i={schema:"comet.native.partial-allowance.v1",change:Yb(t.change),scopeHash:Li(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:gp(t.reason,"Partial allowance reason"),confirmedSummary:gp(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:Kb(t.sourceRevision),confirmedAt:Xb(t.confirmedAt,"Native partial allowance timestamp")};if(i.reason!==t.reason||i.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let r=Li(t.allowanceHash,"Native partial allowance hash");if(D(DO,i)!==r)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:r}}function vs(e){let t=ou(e,"Native verification evidence");if(su(t,["schema","change","sourceRevision","result","freshness","contractHash","acceptanceCriteriaHash","implementationScopeRef","implementationScopeHash","reportRef","reportHash","acceptanceTrace","partialAllowanceRef","partialAllowanceHash","requiredReceiptRefs","receiptRefs","createdAt","envelopeHash"],"Native verification evidence"),t.schema!=="comet.native.verification-evidence.v2"||typeof t.change!="string"||t.result!=="pass"&&t.result!=="fail"||t.freshness!=="complete"&&t.freshness!=="partial"||typeof t.implementationScopeHash!="string"||typeof t.reportRef!="string"||!Array.isArray(t.requiredReceiptRefs)||!Array.isArray(t.receiptRefs))throw new Error("Native verification evidence is invalid");let i=Li(t.implementationScopeHash,"Native verification implementation scope hash"),r=FO(t.acceptanceTrace),n=Li(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(r.criteriaHash!==n)throw new Error("Native verification acceptance trace does not match its criteria hash");let a=t.partialAllowanceRef!==null||t.partialAllowanceHash!==null;if(t.partialAllowanceRef===null!=(t.partialAllowanceHash===null)||t.freshness==="complete"&&a||t.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=t.partialAllowanceHash===null?null:Li(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>wp(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(Ra)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(r.entries.flatMap(f=>f.evidenceRefs))].sort(Ra);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=t.requiredReceiptRefs.map(f=>wp(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Ra)))throw new Error("Native required receipt refs must be canonical");if(t.result==="pass"&&l.length===0)throw new Error("Passing verification has no current static receipt");let u={schema:"comet.native.verification-evidence.v2",change:Yb(t.change),sourceRevision:Kb(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:Li(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:Gb(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:MO(t.reportRef,"Native verification report ref"),reportHash:Li(t.reportHash,"Native verification report hash"),acceptanceTrace:r,partialAllowanceRef:o===null?null:Gb(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:Xb(t.createdAt,"Native verification timestamp")},d=Li(t.envelopeHash,"Native verification envelope hash");if(D(LO,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}import Qb from"node:path";var Zb="comet.native.check-receipt.v1",BO="comet.native.check-receipt.v1",Ca="scoped-text-safety",yp=1,dt=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),VO=/^[a-f0-9]{64}$/u,qO=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,WO="comet.native.checker-policy.v1",zO="comet.native.check-input.v1",JO=2048,ek=D(WO,{policy:Ca,version:yp,limits:dt,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),GO=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),tk=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],rk=["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"],UO=new Set(rk);function Ar(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function _r(e,t,i,r=[]){let n=new Set([...t,...r]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${i} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${i} is missing field(s): ${o.join(", ")}`)}function Mi(e,t){if(typeof e!="string"||!VO.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function St(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function nk(e,t){let i=St(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function ik(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(!Number.isFinite(i.getTime())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function KO(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>JO||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a bounded normalized project-relative path`);let i=Qb.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||Qb.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function YO(e){let t=Ar(e,"Native check receipt checker");_r(t,["policy","version","hash","limits"],"Native check receipt checker");let i=Ar(t.limits,"Native check receipt limits");if(_r(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==Ca||t.version!==yp||t.hash!==ek||i.maxFiles!==dt.maxFiles||i.maxFileBytes!==dt.maxFileBytes||i.maxTotalBytes!==dt.maxTotalBytes||i.maxIssues!==dt.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:Ca,version:yp,hash:ek,limits:{...dt}}}function XO(e){let t=Ar(e,"Native check receipt contract");return _r(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:Mi(t.expectedHash,"Native check expected contract hash"),beforeHash:Mi(t.beforeHash,"Native check before contract hash"),afterHash:Mi(t.afterHash,"Native check after contract hash")}}function QO(e){let t=Ar(e,"Native check receipt implementation");return _r(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:Mi(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:Mi(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:Mi(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:Mi(t.afterSnapshotHash,"Native check after snapshot hash")}}function ZO(e,t){let i=Ar(e,`Native check batch ${t}`);_r(i,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let r={filesSelected:St(i.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:St(i.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:St(i.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:St(i.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:St(i.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:St(i.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(r.filesSelected>dt.maxFiles||r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.bytesScanned>dt.maxTotalBytes||r.recordedIssueCount>r.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return r}function e0(e){let t=Ar(e,"Native check receipt counts");_r(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let i={filesSelected:St(t.filesSelected,"Native check filesSelected"),filesScanned:St(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:St(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:St(t.bytesScanned,"Native check bytesScanned"),issueCount:St(t.issueCount,"Native check issueCount"),recordedIssueCount:St(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(ZO):(()=>{throw new Error("Native check receipt batches must be an array")})()}},r=i.batches;if(r!==void 0){if(r.length===0)throw new Error("Native check receipt batches must not be empty");let n=r.reduce((a,o)=>({filesSelected:a.filesSelected+o.filesSelected,filesScanned:a.filesScanned+o.filesScanned,binaryFilesSkipped:a.binaryFilesSkipped+o.binaryFilesSkipped,bytesScanned:a.bytesScanned+o.bytesScanned,issueCount:a.issueCount+o.issueCount,recordedIssueCount:a.recordedIssueCount+o.recordedIssueCount}),{filesSelected:0,filesScanned:0,binaryFilesSkipped:0,bytesScanned:0,issueCount:0,recordedIssueCount:0});if(JSON.stringify(n)!==JSON.stringify({...i,batches:void 0}))throw new Error("Native check receipt batch totals are inconsistent")}if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>dt.maxIssues||r===void 0&&(i.filesScanned+i.binaryFilesSkipped>dt.maxFiles||i.bytesScanned>dt.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return i}function t0(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||tk.indexOf(e.kind)-tk.indexOf(t.kind)}function i0(e){if(!Array.isArray(e)||e.length>dt.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((r,n)=>{let a=Ar(r,`Native check issue ${n}`);if(_r(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!GO.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:KO(a.path,`Native check issue ${n} path`),line:nk(a.line,`Native check issue ${n} line`),kind:a.kind}}),i=[...t].sort(t0);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function r0(e){if(!Array.isArray(e)||e.some(r=>typeof r!="string"||!UO.has(r)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=rk.filter(r=>t.includes(r));if(new Set(t).size!==t.length||JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function n0(e){return D(zO,e)}function lu(e){let t=Ar(e,"Native check receipt");if(_r(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==Zb)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!qO.test(t.change))throw new Error("Native check receipt change name is invalid");let i=nk(t.sourceRevision,"Native check source revision"),r=YO(t.checker),n=XO(t.contract),a=QO(t.implementation),o=n0({change:t.change,sourceRevision:i,checkerHash:r.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(Mi(t.inputHash,"Native check input hash")!==o)throw new Error("Native check receipt input hash mismatch");if(t.status!=="passed"&&t.status!=="failed")throw new Error("Native check receipt status is invalid");let s=ik(t.startedAt,"Native check receipt startedAt"),c=ik(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=e0(t.counts),u=i0(t.issues);if(l.recordedIssueCount!==u.length)throw new Error("Native check receipt recorded issue count is inconsistent");if(typeof t.issuesTruncated!="boolean"||t.issuesTruncated!==l.issueCount>u.length)throw new Error("Native check receipt issue truncation flag is inconsistent");let d=r0(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let f=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==f)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.batches===void 0&&l.filesSelected>dt.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.batches===void 0&&l.filesSelected>dt.maxFiles&&!u.some(m=>m.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let h={schema:Zb,change:t.change,sourceRevision:i,checker:r,inputHash:o,status:t.status,startedAt:s,endedAt:c,contract:n,implementation:a,counts:l,issues:u,issuesTruncated:t.issuesTruncated,stale:t.stale,staleReasons:d},v=Mi(t.receiptHash,"Native check receipt content hash");if(D(BO,h)!==v)throw new Error("Native check receipt content hash mismatch");return{...h,receiptHash:v}}var bp="comet.native.verification-receipt.v3",a0=bp,o0="comet.native.declared-artifacts.v1",s0=/^[a-f0-9]{64}$/u,c0=/^acceptance-[a-f0-9]{64}$/u,l0=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,u0=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,d0=4096,f0=256,h0=1024;function xa(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function Tr(e,t,i){let r=Object.keys(e).sort(),n=[...t].sort();if(r.length!==n.length||r.some((a,o)=>a!==n[o]))throw new Error(`${i} fields are invalid`)}function Fi(e,t){if(typeof e!="string"||!s0.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function ri(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=$t(e).trim();if(!i||i.length>d0||i!==e.trim())throw new Error(`${t} is invalid`);return i}function Np(e,t){let i=ri(e,t),r=new Date(i);if(Number.isNaN(r.getTime())||r.toISOString()!==i)throw new Error(`${t} must be a canonical timestamp`);return i}function gs(e,t,i=ri,r=!1,n=f0){if(!Array.isArray(e)||e.length>n||!r&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>i(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function p0(e,t){if(typeof e!="string"||!c0.test(e))throw new Error(`${t} is invalid`);return e}function m0(e){let t=xa(e,"Native verification receipt bindings");if(Tr(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!l0.test(t.change)||!Number.isSafeInteger(t.sourceRevision)||t.sourceRevision<1)throw new Error("Native verification receipt bindings are invalid");return{change:t.change,sourceRevision:t.sourceRevision,contractHash:Fi(t.contractHash,"Native verification receipt contract hash"),scopeHash:Fi(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:Fi(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:Fi(t.artifactHash,"Native verification receipt artifact hash")}}function v0(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=u0.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function g0(e,t,i,r){let n=xa(t,`Native ${e} evidence`);if(e==="automated-check"){if(Tr(n,["executable","args","cwd","exitCode","signal","timedOut","timeoutMs","startedAt","endedAt","worktree","afterFence","outputHash","outputSummary","outputTruncated"],"Native automated-check evidence"),!Number.isSafeInteger(n.exitCode)||!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<1||n.timeoutMs>3600*1e3||typeof n.timedOut!="boolean"||typeof n.outputTruncated!="boolean"||n.signal!==null&&typeof n.signal!="string")throw new Error("Native automated-check exit code is invalid");let a=Np(n.startedAt,"Native automated-check start time"),o=Np(n.endedAt,"Native automated-check end time");if(Date.parse(o)<Date.parse(a))throw new Error("Native automated-check time range is invalid");if(i==="passed"&&n.exitCode!==0||i==="failed"&&n.exitCode===0||i==="passed"&&(n.timedOut||n.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=xa(n.worktree,"Native automated-check worktree");if(Tr(s,["provider","root","beforeCommit","afterCommit"],"Native automated-check worktree"),s.provider!=="git"&&s.provider!=="none"||s.beforeCommit!==null&&(typeof s.beforeCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.beforeCommit))||s.afterCommit!==null&&(typeof s.afterCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.afterCommit)))throw new Error("Native automated-check worktree identity is invalid");let c=xa(n.afterFence,"Native automated-check after fence");if(Tr(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(i==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:ri(n.executable,"Native automated-check executable"),args:gs(n.args,"Native automated-check arguments",ri,!0),cwd:ri(n.cwd,"Native automated-check cwd"),exitCode:n.exitCode,signal:n.signal,timedOut:n.timedOut,timeoutMs:n.timeoutMs,startedAt:a,endedAt:o,worktree:{provider:s.provider,root:ri(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:Fi(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:Fi(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:Fi(n.outputHash,"Native automated-check output hash"),outputSummary:ri(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){Tr(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=v0(n.checkReceiptRef);if(Fi(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:gs(n.subjects,"Native static inspection subjects",ri,r==="required-check"),rule:ri(n.rule,"Native static inspection rule"),resultSummary:ri(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return Tr(n,["steps","observations"],"Native manual-evidence evidence"),{steps:gs(n.steps,"Native manual evidence steps"),observations:gs(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function w0(e){let t=xa(e,"Native verification receipt");if(Tr(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence"],"Native verification receipt input"),!["automated-check","static-inspection","manual-evidence"].includes(t.kind)||t.role!=="required-check"&&t.role!=="acceptance-evidence"||!["passed","failed","skipped","blocked"].includes(t.status))throw new Error("Native verification receipt kind or status is invalid");let i=t.kind,r=t.role,n=t.status,a=ri(t.actor,"Native verification receipt actor"),o=gs(t.acceptanceIds,"Native receipt acceptance IDs",p0,r==="required-check",h0).sort();if(r==="required-check"&&o.length!==0||r==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(r==="required-check"&&i!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:bp,kind:i,role:r,status:n,bindings:m0(t.bindings),acceptanceIds:o,actor:a,issuedAt:Np(t.issuedAt,"Native verification receipt issue time"),evidence:g0(i,t.evidence,n,r)};if(r==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==Ca||s.actor!==`native-runtime:${Ca}`))throw new Error("Native required check policy identity is invalid");return s}function uu(e){let t=xa(e,"Native verification receipt");if(Tr(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==bp)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...r}=t,n=w0(r),a=Fi(t.receiptHash,"Native verification receipt hash");if(D(a0,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function kp(e){return D(o0,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}var ck=/^[a-f0-9]{64}$/u,Ir=gn,Lz=3*Ir;function Sp(e,t){let i=yi.relative(e,t);return i===""||!yi.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${yi.sep}`)}function N0(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function du(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return vt(i,r)?z(i,r):z(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function ak(e){let t=await ni.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await ni.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function b0(e,t){let i=yi.resolve(e),r=yi.resolve(t);if(!Sp(i,r))throw new Error("Native evidence path is outside its change");let n=[await ak(i)],a=i;for(let o of yi.relative(i,r).split(yi.sep).filter(Boolean)){a=yi.join(a,o);let s=await ak(a);if(!Sp(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function ok(e){for(let t of e){let i=await ni.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!N0(t,i)||await ni.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function k0(e,t,i={}){let r=await b0(t,yi.dirname(e));await i.afterParentChainCaptured?.();let n=await ni.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await ni.realpath(e);if(!Sp(r[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await ni.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),ni.lstat(e),ni.realpath(e)]);if(await ok(r),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!du(s,n)||!du(s,c))throw new Error("Native evidence document changed while opening");if(s.size>Ir)throw new Error(`Native evidence document exceeds ${Ir} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let p=Ir+1-d,b=await o.read(f,0,Math.min(f.length,p),null);if(b.bytesRead===0)break;if(d+=b.bytesRead,d>Ir)throw new Error(`Native evidence document exceeds ${Ir} bytes`);u.push(Buffer.from(f.subarray(0,b.bytesRead)))}await i.beforeFinalCheck?.();let[h,v,m]=await Promise.all([o.stat(),ni.lstat(e),ni.realpath(e)]);if(await ok(r),!v.isFile()||v.isSymbolicLink()||m!==a||!du(s,h)||!du(s,v))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function _a(e,t){if(!ck.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}function lk(e){return _a("reports",e)}async function S0(e,t,i,r,n){if(!ck.test(i))throw new Error("Native report evidence hash is invalid");let a=await wn({paths:e,name:t,kind:"reports",hash:i,hooks:r,changeDir:n});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==i||typeof o.content!="string"||y0("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==i)throw new Error("Native report evidence does not match its hash");return o.content}function Aa(e,t){let i=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!i||i[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return i[2]}function E0(e,t,i,r,n){let a=_a(i,r);return n?yi.join(n,...a.split("/")):fr(H(e,t),a)}async function wn(e){let t=E0(e.paths,e.name,e.kind,e.hash,e.changeDir),i=e.changeDir??j(e.paths,t);return await T(i,t),k0(t,i,e.hooks)}function sk(e,t){return Ea(e,t)}function P0(e,t){let i=Pa(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function R0(e,t,i){let r=cu(e);if(r.change!==t||r.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return r}function C0(e,t,i){let r=vs(e);if(r.change!==t||r.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return r}async function x0(e,t,i,r=!1,n){let a=await fu(e,t,i.implementationScopeRef,void 0,n);if(r&&await S0(e,t,i.reportHash,void 0,n),a.scopeHash!==i.implementationScopeHash||a.contractHash!==i.contractHash||(a.complete?"complete":"partial")!==i.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(i.partialAllowanceRef===null)return;let o=await uk(e,t,i.partialAllowanceRef,void 0,n);if(o.allowanceHash!==i.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=i.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function ws(e,t,i,r,n){let a=Aa(i,"scopes"),o=P0(await wn({paths:e,name:t,kind:"scopes",hash:a,hooks:r,changeDir:n}),a),s=Aa(o.baselineProjectionRef,"snapshots"),c=Aa(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([wn({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>sk(d,s)),wn({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>sk(d,c))]);return zb({baseline:l,current:u,scope:o})}async function fu(e,t,i,r,n){return(await ws(e,t,i,r,n)).scope}async function uk(e,t,i,r,n){let a=Aa(i,"allowances");return R0(await wn({paths:e,name:t,kind:"allowances",hash:a,hooks:r,changeDir:n}),t,a)}async function ys(e,t,i,r,n){let a=Aa(i,"receipts"),o=uu(await wn({paths:e,name:t,kind:"receipts",hash:a,hooks:r,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function Ta(e,t,i,r,n){let a=Aa(i,"verifications"),o=C0(await wn({paths:e,name:t,kind:"verifications",hash:a,hooks:r,changeDir:n}),t,a);return await x0(e,t,o,!1,n),o}var A0=4096;async function _0(e,t=ut.maxChanges){try{let i=await wt({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:t});return await i.verify(),i.entries}catch(i){if(i.code==="ENOENT")return[];throw i}}async function dk(e,t){let i=await De(e,t),[r,n]=await Promise.all([i.implementation_scope?fu(e,t,i.implementation_scope):null,kt(e,t).catch(()=>null)]);return{name:i.name,revision:i.revision,specs:i.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:r?.declaredArtifacts??[],workspaceIdentityHash:n?.nativeRootId??null}}async function hu(e,t,i={}){let n=(await _0(e,A0)).filter(c=>c.isDirectory()&&!c.isSymbolicLink()).map(c=>c.name).sort();if(!n.includes(t))throw new Error(`Native conflict target is not visible: ${t}`);let a=await dk(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await dk(e,c).catch(d=>{if(i.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=Rb([a,l]).relationships[0];u.classification==="definite-conflict"&&(o+=1),u.classification==="possible-overlap"&&(s+=1)}return{definiteConflictCount:o,possibleOverlapCount:s,findingCodes:[...o>0?["native-change-conflict"]:[],...s>0?["native-change-overlap"]:[]]}}import{promises as G0}from"fs";import U0 from"path";import{isDeepStrictEqual as mu}from"util";var Ia={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var T0=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function I0(e,t){return e<t?-1:e>t?1:0}function j0(e,t,i,r){if(!Array.isArray(e)||e.length>i||!r&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let n=e.map(a=>{if(typeof a!="string"||!T0.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(I0)}function Ep(e=[]){return j0(e,"Native repair failed check IDs",Ia.maxFailedCheckIds,!0)}function fk(e,t){let i=new Set(t);return e.every(r=>i.has(r))}function $0(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:fk(e.failedAcceptanceIds,t.failedAcceptanceIds)&&fk(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function Pp(e,t){let i=1,r=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if($0(r,a))break;i+=1,r=a}return i}function Rp(e,t){if(typeof e!="string"||e.trim().length===0||e.length>4096)throw new Error(`${t} must be between 1 and 4096 characters`)}var hk="repairStagnation",Et={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},H0=/^[a-f0-9]{64}$/u;var D0=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),L0=["data","runId","sequence","timestamp","type"],pk=["disposition","overrideSummaryHash","signatureHash"],M0=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],mk=12;function xp(e,t){return e<t?-1:e>t?1:0}function vk(e,t,i){let r=Object.keys(e).sort(xp);if(r.length!==t.length||r.some((n,a)=>n!==t[a]))throw new Error(`${i} fields are invalid`)}function pu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function Ns(e,t){if(typeof e!="string"||!H0.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function F0(e){if(!Array.isArray(e)||e.length>Ia.maxFailedAcceptanceIds||e.some(t=>typeof t!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(t)))throw new Error("Native repair trajectory failed acceptance IDs are invalid");return[...new Set(e)].sort(xp)}function gk(e){if(typeof e!="string"||e.length===0||e.length>Et.maxRunIdCharacters||Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function Cp(e,t,i,r,n=!1){if(i.nodes+=1,i.nodes>Et.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Et.maxDataDepth)throw new Error("Native repair trajectory event data exceeds its depth boundary");if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${r} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>Et.maxTextCharacters&&(!n||e.length>Et.maxEventDataCharacters))throw new Error(`${r} contains oversized text`);if(i.characters+=e.length,i.characters>Et.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${r} contains a non-JSON value`);if(i.ancestors.has(e))throw new Error(`${r} contains a cycle`);i.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>Et.maxArrayEntries)throw new Error(`${r} contains an oversized array`);e.forEach((s,c)=>Cp(s,t+1,i,`${r}[${c}]`));return}let a=pu(e,r),o=Object.keys(a);if(o.length>Et.maxObjectFields)throw new Error(`${r} contains too many fields`);for(let s of o){if(s.length===0||s.length>Et.maxKeyCharacters)throw new Error(`${r} contains an invalid field name`);if(i.characters+=s.length,i.characters>Et.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");Cp(a[s],t+1,i,`${r}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function B0(e){if(typeof e!="string"||e.length>64)throw new Error("Native repair trajectory timestamp is invalid");let t=new Date(e);if(!Number.isFinite(t.valueOf())||t.toISOString()!==e)throw new Error("Native repair trajectory timestamp is invalid");return e}function V0(e,t,i){let r=pu(e,`Native repair trajectory event ${t+1}`);if(vk(r,L0,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(r.sequence)||r.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(B0(r.timestamp),typeof r.type!="string"||!D0.has(r.type))throw new Error("Native repair trajectory event type is invalid");if(gk(r.runId)!==i)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let n={nodes:0,characters:0,ancestors:new Set};return Cp(r.data,0,n,"Native trajectory event data"),pu(r.data,"Native repair trajectory event data"),{event:r,dataNodes:n.nodes,dataCharacters:n.characters}}function Ap(e){let t=pu(e,"Native repair trajectory projection"),i=Object.keys(t).sort(xp),r=i.length===pk.length&&i.every((l,u)=>l===pk[u]);r||vk(t,M0,"Native repair trajectory projection");let n=Ns(t.signatureHash,"Native repair trajectory signature hash");if(t.disposition!=="continue"&&t.disposition!=="warn"&&t.disposition!=="manual-stop"&&t.disposition!=="hard-stop")throw new Error("Native repair trajectory disposition is invalid");let a=t.overrideSummaryHash===null?null:Ns(t.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&t.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(r)return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=Ns(t.contractHash,"Native repair trajectory contract hash"),s=F0(t.failedAcceptanceIds),c=Ep(t.failedCheckIds);if(!Number.isSafeInteger(t.maxVerifyFailures)||t.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:o,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:t.maxVerifyFailures}}function q0(e,t){if(t.overrideSummaryHash===null){if(e.previousPhase!=="verify"||e.nextPhase!=="build"||e.verificationResult!=="fail")throw new Error("Native repair failure projection is only valid on a failed Verify-to-Build transition");return}if(t.disposition!=="continue"||e.previousPhase!=="build"||e.nextPhase!=="verify"||e.verificationResult!==null)throw new Error("Native repair override projection is only valid on a Build-to-Verify transition")}function W0(e,t){let i=t.filter(s=>s.kind==="failure"),r=i.length+1,n=e.maxVerifyFailures??mk;if(r>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=Pp({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=r>=n?"hard-stop":a<Ia.warningAtConsecutiveFailures?"continue":a<Ia.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function z0(e,t,i){let r=t.filter(a=>a.kind==="failure"),n=i?.maxVerifyFailures??mk;if(r.length>=n)throw new Error("Native repair trajectory cannot override a hard stop");if(i?.disposition!=="manual-stop"||i.signatureHash!==e.signatureHash||r.at(-1)?.signatureHash!==e.signatureHash)throw new Error("Native repair trajectory override does not match the latest manual stop");if(t.some(a=>a.kind==="override"&&a.signatureHash===e.signatureHash))throw new Error("Native repair trajectory signature was already overridden")}function wk(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Et.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=gk(e.runId);if(!Number.isSafeInteger(e.committedTrajectoryOffset)||e.committedTrajectoryOffset<0||e.committedTrajectoryOffset>e.trajectory.length)throw new Error("Native repair committed trajectory offset is invalid");let i=[],r=null,n=null,a=null,o=0,s=0,c=0;for(let l=0;l<e.committedTrajectoryOffset;l+=1){let u=V0(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>Et.maxTotalDataNodes||c>Et.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,h=Object.hasOwn(f,"repairScopeHash")?Ns(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?Ns(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,hk)){if(r?.contractHash===null&&d.type==="state_transitioned"&&f.previousPhase==="build"&&f.nextPhase==="verify"&&(h!==null&&n!==null&&h!==n||h===null&&(r?.disposition==="manual-stop"||r?.disposition==="hard-stop"))){i.length=0,r=null,n=h,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let v=Ap(f[hk]);if(q0(f,v),v.overrideSummaryHash===null)v.contractHash!==null&&a!==null&&v.contractHash!==a&&(i.length=0,o=0),v.contractHash!==null&&(a=v.contractHash),v.contractHash===null&&h!==null&&n!==null&&h!==n&&(i.length=0,o=0),h!==null&&(n=h),W0(v,i),o+=1,i.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:v.signatureHash,...v.contractHash===null?{}:{failedAcceptanceIds:[...v.failedAcceptanceIds],failedCheckIds:[...v.failedCheckIds]}});else{if(r?.contractHash===null&&h!==null&&n!==null&&h!==n)throw new Error("Native repair override cannot cross implementation scope progress");z0(v,i,r);let m=i.at(-1);if(!m||m.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");i.push({kind:"override",revision:d.sequence,iteration:m.iteration,signatureHash:v.signatureHash,summaryHash:v.overrideSummaryHash})}if(r=v,i.length>Ia.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:r}}function yk(e){return wk(e).history}function Nk(e){let t=wk(e).latestProjection;return t?{...t}:null}var Ni={root:"/comet/native-runtime",packageKind:"runtime",definition:{apiVersion:"comet/v1alpha1",kind:"Skill",metadata:{name:"comet-native-runtime",version:"3",description:"Comet-owned state runtime for the Native workflow."},goal:{statement:"Advance a Native change only after its current guard passes.",inputs:[],outputs:[],success:["The Native change and Run state agree on the next phase."]},orchestration:{mode:"deterministic",entry:"shape",steps:[{id:"shape",action:{type:"checkpoint"},next:"build"},{id:"build",action:{type:"checkpoint"},next:"verify"},{id:"verify",action:{type:"checkpoint"},next:"archive"},{id:"archive",action:{type:"checkpoint"}}]},skills:[],agents:[],tools:[]},guardrails:{allowedSkills:[],allowedAgents:[],allowedTools:[],maxIterations:Number.MAX_SAFE_INTEGER,maxRetriesPerAction:2,confirmationRequiredFor:[]},evals:[]},bs=L("comet-native-runtime:v3:scope-reopen"),J0=[{skillVersion:"3",skillHash:L("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:L("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:L("comet-native-runtime:v1")}];function bk(e){return e.skillVersion===Ni.definition.metadata.version&&e.skillHash===bs||J0.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}var _p={resolveStep({pkg:e,state:t}){return e.definition.orchestration.steps?.find(i=>i.id===t.currentStep)},resolveNext({step:e,outcome:t}){return e.id==="verify"&&t.state?.verification_result==="fail"?"build":e.next??null}};async function jr(e){let i={sequence:(await it(e.changeDir,e.run.trajectoryRef)).length+1,timestamp:(e.now??new Date).toISOString(),type:e.type,runId:e.run.runId,data:e.data};return await BN(e.changeDir,e.run.trajectoryRef,i),i}async function yn(e){let t={runId:e.run.runId,stateVersion:e.run.iteration,trajectoryOffset:e.trajectoryOffset,contextHash:null,artifactsHash:L(e.evidenceHash),createdAt:(e.now??new Date).toISOString()};return await VN(e.changeDir,e.run.checkpointRef,t),t}function kk(e){return L(JSON.stringify({summary:e.summary,returnToBuild:e.returnToBuild??!1,confirmed:e.confirmed??!1,artifacts:[...e.artifacts??[]].sort(),noCodeReason:e.noCodeReason??null,verificationResult:e.verificationResult??null,verificationReport:e.verificationReport??null,allowPartialScopeHash:e.allowPartialScopeHash??null,partialReason:e.partialReason??null,repairOverrideSignature:e.repairOverrideSignature??null,repairOverrideSummary:e.repairOverrideSummary??null}))}var _k=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],K0=new Set(_k),Tk=new Set([..._k,"minimum_runtime_version","revision"]),Y0=new Set([...Tk,"operation"]),X0=512*1024,Tp=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),Q0=new Set([...Tp,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),ks=class extends Error{constructor(i){super(`Native transition for ${i} requires doctor migration before recovery`);this.change=i;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function Ue(e,t){return U0.join(H(e,t),"transition.json")}function Z0(e){return`transition-${e}`}async function eH(e,t,i){let r=Z0(t);return pr(e,r,i)}async function Nn(e,t,i,r){let n=await eH(e,t,i);try{return await r()}finally{await mr(n)}}function gu(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function jp(e,t){let i=Object.keys(e).find(r=>!t.has(r));if(i)throw new Error(`Native transition journal contains unknown field: ${i}`)}function vu(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function bi(e,t){return mu(e,t)}function Ip(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let i=e,r=Object.keys(i),n=r.find(u=>!Q0.has(u)),a=[...Tp].find(u=>!Object.hasOwn(i,u)),o=Tp.size+(Object.hasOwn(i,"implementationScopeHash")?1:0)+(Object.hasOwn(i,"repairScopeHash")?1:0)+(Object.hasOwn(i,"repairStagnation")?1:0)+(Object.hasOwn(i,"returnToBuild")?1:0);if(n||a||r.length!==o)throw new Error(`Native transition journal event data keys are invalid${n?`: ${n}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(i.previousPhase)||!["shape","build","verify","archive"].includes(i.nextPhase))throw new Error("Native transition journal event phases are invalid");if(i.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if(i.returnToBuild!==void 0&&typeof i.returnToBuild!="boolean")throw new Error("Native transition journal returnToBuild flag is invalid");if(Rp(i.summary,"Native transition journal event summary"),$t(i.summary)!==i.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(i.artifacts)||i.artifacts.length>128||i.artifacts.some(u=>typeof u!="string"||u.length===0||Buffer.byteLength(u,"utf8")>512))throw new Error("Native transition journal event artifacts are invalid");if(i.noCodeReason!==null&&(Rp(i.noCodeReason,"Native transition journal event no-code reason"),$t(i.noCodeReason)!==i.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(i.verificationResult!==null&&i.verificationResult!=="pass"&&i.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(i,"implementationScopeHash")?i.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||i.previousPhase!=="build"&&i.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(i,"repairStagnation")?Ap(i.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(i.previousPhase!=="verify"||i.nextPhase!=="build"||i.verificationResult!=="fail")||!u&&(i.previousPhase!=="build"||i.nextPhase!=="verify"||i.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(i,"repairScopeHash")?i.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||i.previousPhase!=="build"&&i.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:t,summary:i.summary,artifacts:[...i.artifacts],noCodeReason:i.noCodeReason,verificationResult:i.verificationResult,...i.returnToBuild===!0?{returnToBuild:!0}:{},...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function tH(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let i=e,r=Object.keys(i),n=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(r.length===n.size&&r.every(a=>n.has(a))&&i.reason==="spec-rebase")return Ip({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return Ip(e,t)}function $p(e,t,i=!1){if(e.change!==t)throw new Error("Native transition journal change mismatch");if(typeof e.id!="string"||e.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof e.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(e.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native transition journal timestamp is invalid");let r=i?tH(e.eventData,e.evidenceHash):Ip(e.eventData,e.evidenceHash),n=Rr(e.nextRun),a=e.previousRun===null?null:Rr(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:r}}function Sk(e,t,i=!1){if(e.skill!==Ni.definition.metadata.name||(i?!bk(e):e.skillVersion!==Ni.definition.metadata.version||e.skillHash!==bs)||e.orchestration!==Ni.definition.orchestration.mode||e.pendingRef!==Nt.pendingRef||e.trajectoryRef!==Nt.trajectoryRef||e.contextRef!==Nt.contextRef||e.artifactsRef!==Nt.artifactsRef||e.checkpointRef!==Nt.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function Ek(e){return{runId:e.runId,skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash,orchestration:e.orchestration,pendingRef:e.pendingRef,trajectoryRef:e.trajectoryRef,contextRef:e.contextRef,artifactsRef:e.artifactsRef,checkpointRef:e.checkpointRef,retries:e.retries}}function Pk(e,t){if(e.status!=="running")throw new Error(`Native transition journal ${t} status must be running`);if(e.pending!==null)throw new Error(`Native transition journal ${t} pending action must be null`)}function Op(e,t,i,r=!1,n="advance"){let{previousRun:a,nextRun:o}=i;if(Sk(o,"next Run",r||a!==null),Pk(o,"next Run"),o.runId!==t.run_id||o.currentStep!==t.phase)throw new Error("Native transition journal next Run does not match the next change state");if(n==="runtime-rebuild"){if(a!==null||e.phase==="shape"||t.phase!=="build"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native Runtime rebuild Run transition is invalid");return}if(a===null){if(e.run_id!==null||e.phase!=="shape"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native transition journal first Run transition is invalid");return}if(Sk(a,"previous Run",!0),Pk(a,"previous Run"),e.run_id!==a.runId||a.currentStep!==e.phase||t.run_id!==a.runId)throw new Error("Native transition journal previous Run does not match the change state");if(o.iteration!==a.iteration+1)throw new Error("Native transition journal next Run iteration must advance exactly once");if(!mu(Ek(a),Ek(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function iH(e,t,i){return L(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function Ik(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function Rk(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function Hp(e,t,i,r,n=!1){let a=i.eventData,o=Rk(e),s=Rk(t);if(a.previousPhase!==e.phase||a.nextPhase!==t.phase)throw new Error("Native transition journal event phases do not match its states");if(e.archived||t.archived)throw new Error("Native transition journal cannot mutate an archived change");if(r==="runtime-rebuild"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&mu(e.spec_changes,t.spec_changes);if(e.phase==="shape"||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||!c||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native Runtime rebuild transition semantics are invalid");return}if(r==="evidence-retreat"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&e.run_id===t.run_id&&mu(e.spec_changes,t.spec_changes),l=kk({summary:a.summary,...a.returnToBuild?{returnToBuild:!0}:{}});if(!(e.phase==="archive"&&e.verification_result==="pass"||e.phase==="verify"&&e.verification_result==="pending")||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||i.evidenceHash!==l||!c||o===null||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native transition journal evidence retreat semantics are invalid");return}if(r==="spec-rebase"){let c=iH(e.name,a.summary,t.spec_changes),l=L(`spec-rebase:${e.name}:${a.summary}`);if(e.phase==="shape"||t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||t.verification_report!==null||!n&&i.evidenceHash!==c||n&&i.evidenceHash!==c&&i.evidenceHash!==l||"implementation_scope"in t&&(t.implementation_scope!==null||t.verification_evidence!==null||t.partial_allowance!==null))throw new Error("Native transition journal spec rebase semantics are invalid");return}if(e.phase==="shape"){if(t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!=="pending"||t.verification_result!=="pending"||e.verification_report!==null||t.verification_report!==null||o!==null&&s!==null&&(o.implementation_scope!==null||o.verification_evidence!==null||o.partial_allowance!==null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null))throw new Error("Native transition journal Shape to Build semantics are invalid");return}if(e.phase==="build"){if(t.phase!=="verify"||a.verificationResult!==null||a.artifacts.length===0&&a.noCodeReason===null||t.verification_result!=="pending"||t.verification_report!==null||o!==null&&s!==null&&(s.implementation_scope===null||s.verification_evidence!==null||s.implementation_scope!==o.implementation_scope&&s.partial_allowance!==null&&s.partial_allowance===o.partial_allowance))throw new Error("Native transition journal Build to Verify semantics are invalid");return}if(e.phase==="verify"){let c=a.verificationResult==="pass"?"archive":"build";if(a.verificationResult!=="pass"&&a.verificationResult!=="fail"||t.phase!==c||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!==a.verificationResult||t.verification_report===null||o!==null&&s!==null&&(o.implementation_scope===null||s.implementation_scope!==o.implementation_scope||s.partial_allowance!==o.partial_allowance||o.verification_evidence!==null||s.verification_evidence===null))throw new Error("Native transition journal Verify outcome semantics are invalid");return}throw new Error("Native transition journal cannot advance from Archive")}function Dp(e,t){let i=gu(e);if(jp(i,Y0),i.schema!==vr)throw new Error(`Expected Native transition schema ${vr}`);let r=vu(i.minimum_runtime_version,"Native transition minimum_runtime_version");if(r>3)throw new Error(`Native transition requires runtime protocol ${r}; current protocol is ${3}`);if(r!==3)throw new Error(`Native transition ${vr} minimum_runtime_version must be ${3}`);let n=vu(i.revision,"Native transition revision");if(n!==1)throw new Error("Native transition journal revision must be 1");if(i.operation!=="advance"&&i.operation!=="spec-rebase"&&i.operation!=="evidence-retreat"&&i.operation!=="runtime-rebuild")throw new Error("Native transition journal operation is invalid");let a=$p(i,t),o=lt(i.previousState),s=lt(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(Hp(o,s,a,i.operation),Op(o,s,a,!1,i.operation),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:vr,minimum_runtime_version:3,revision:n,operation:i.operation,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function rH(e,t){let i=gu(e);if(jp(i,K0),i.schema!==cn)throw new Error(`Expected Native transition schema ${cn}`);let r=$p(i,t,!0),n=ln(i.previousState),a=ln(i.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return Hp(n,a,r,Ik(n,a,r.eventData),!0),Op(n,a,r,!0),{schema:cn,id:r.id,change:t,evidenceHash:r.evidenceHash,createdAt:r.createdAt,previousState:n,nextState:a,previousRun:r.previousRun,nextRun:r.nextRun,eventData:r.eventData}}function Lp(e,t){let i=gu(e);if(jp(i,Tk),i.schema!==ji)throw new Error(`Expected Native transition schema ${ji}`);if(vu(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${ji} minimum_runtime_version must be 2`);let n=vu(i.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=$p(i,t,!0),o=di(i.previousState),s=di(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(Hp(o,s,a,Ik(o,s,a.eventData),!0),Op(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:ji,minimum_runtime_version:2,revision:n,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function nH(e,t){let i=gu(e);if(i.schema===vr)return{status:"current",journal:Dp(i,t)};if(i.schema===cn)return{status:"migration-required",journal:rH(i,t)};if(i.schema===ji)return{status:"migration-required",journal:Lp(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function Mp(e,t){let i=Ue(e,t),r=j(e,i);await T(r,i);try{let n=await re({root:r,file:i,maxBytes:X0,label:`Native transition journal ${t}`});return nH(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Bi(e,t){let i=await Mp(e,t);if(!i)return null;if(i.status==="migration-required")throw new ks(t);return i.journal}function Ck(e,t){if(bi(e,t.nextRun))return"next";if(t.previousRun===null){if(e===null)return"previous"}else if(bi(e,t.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${t.change}; recovery journal was preserved`)}function xk(e,t){if(bi(e,t.nextState))return"next";if(bi(e,t.previousState))return"previous";throw new Error(`Native transition change content changed for ${t.change}; recovery journal was preserved`)}function aH(e){let{journal:t}=e;return jk({sequence:e.sequence,timestamp:t.createdAt,type:e.type,runId:t.nextRun.runId,data:e.type==="run_started"?{runtime:"comet-native",phase:t.previousState.phase,transitionId:t.id}:{...t.eventData,transitionId:t.id}})}function jk(e){return{sequence:e.sequence,timestamp:e.timestamp,type:e.type,runId:e.runId,data:e.data}}function Ak(e,t){let i=e.map((a,o)=>({event:a,index:o})).filter(({event:a})=>a.data.transitionId===t.id),r=i.filter(({event:a})=>a.type==="run_started"),n=i.filter(({event:a})=>a.type==="state_transitioned");if(i.length!==r.length+n.length||r.length>(t.previousRun===null?1:0)||n.length>1||t.previousRun===null&&n.length===1&&(r.length!==1||r[0].index>=n[0].index))throw new Error(`Native trajectory transition id collision for ${t.change}; recovery journal was preserved`);for(let a of[...r,...n]){let o=aH({sequence:a.index+1,journal:t,type:a.event.type});if(!bi(jk(a.event),o))throw new Error(`Native trajectory event changed for transition ${t.id}; recovery journal was preserved`)}return{started:r[0]?.event??null,transitioned:n[0]?.event??null}}async function wu(e,t,i){if(await Na(e,t))throw new Error(`Native schema migration is incomplete for ${t}; run doctor --repair`);await Kl(e,t);let r=await Bi(e,t);if(!r)return null;let n=H(e,t),a=Ak(await it(n,r.nextRun.trajectoryRef),r),[o,s]=await Promise.all([Oe(n),De(e,t)]),c=Ck(o,r),l=xk(s,r);if((a.started||a.transitioned)&&(c!=="next"||l!=="next"))throw new Error(`Native trajectory is ahead of transition state for ${r.change}; recovery journal was preserved`);if(c==="previous"&&(await hn(n,r.nextRun),await i?.afterRunStateWritten?.(r)),!bi(await Oe(n),r.nextRun))throw new Error(`Native transition Run content changed while continuing ${r.change}; recovery journal was preserved`);if(l==="previous"){let p=await ru(e,r.nextState,r.previousState.revision);if(!bi(p,r.nextState))throw new Error(`Native transition change write diverged for ${r.change}; recovery journal was preserved`);await i?.afterChangeStateWritten?.(r)}if(!bi(await De(e,t),r.nextState))throw new Error(`Native transition change content changed while continuing ${r.change}; recovery journal was preserved`);let u=await Bi(e,t);if(!u||!bi(u,r))throw new Error(`Native transition journal changed while continuing ${r.change}; it was preserved`);let d=Ak(await it(n,r.nextRun.trajectoryRef),r);r.previousRun===null&&(d.started||await jr({changeDir:n,run:r.nextRun,type:"run_started",data:{runtime:"comet-native",phase:r.previousState.phase,transitionId:r.id},now:new Date(r.createdAt)}));let f=d.transitioned;f||(f=await jr({changeDir:n,run:r.nextRun,type:"state_transitioned",data:{...r.eventData,transitionId:r.id},now:new Date(r.createdAt)})),await yn({changeDir:n,run:r.nextRun,trajectoryOffset:f.sequence,evidenceHash:r.evidenceHash,now:new Date(r.createdAt)});let[h,v]=await Promise.all([Oe(n),De(e,t)]);Ck(h,{...r,previousRun:r.nextRun}),xk(v,{...r,previousState:r.nextState});let m=await Bi(e,t);if(!m||!bi(m,r))throw new Error(`Native transition journal changed while continuing ${r.change}; it was not removed`);return await G0.rm(Ue(e,t),{force:!0}),r.nextState}async function $k(e,t,i){return se(e,`continue transition ${t}`,()=>Nn(e,t,`continue transition ${t}`,()=>wu(e,t,i)))}import Ok from"node:path";var oH="comet.native.contract.v1",sH="comet.native.acceptance-set.v1",Hk=/^[a-f0-9]{64}$/u,Ss={maxAcceptanceCriteria:Bo.maxCriteria};function Dk(e,t){let i=Ok.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||Ok.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized project-relative ref`);return e}function Lk(e){return D("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
205
+ `))}function cH(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.capability))throw new Error(`Invalid Native contract capability: ${e.capability}`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Invalid Native contract operation for ${e.capability}`);if(e.operation==="remove"){if(e.source!==null||e.markdown!==null||!e.baseHash?.match(Hk))throw new Error(`Remove contract ${e.capability} requires only a base hash`);return{snapshot:{capability:e.capability,operation:"remove",source:null,baseHash:e.baseHash,contentHash:null},markdown:null}}if(e.source===null||e.markdown===null)throw new Error(`${e.operation} contract ${e.capability} requires source content`);if(e.operation==="create"&&e.baseHash!==null)throw new Error(`Create contract ${e.capability} requires a null base hash`);if(e.operation==="replace"&&!e.baseHash?.match(Hk))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=Dk(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:Lk(e.markdown)},markdown:e.markdown}}function lH(e,t){return Mk(e.id,t.id)}function Mk(e,t){return e<t?-1:e>t?1:0}function Fk(e){let t=Dk(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(cH).sort((d,f)=>Mk(d.snapshot.capability,f.snapshot.capability)),r=i.map(({snapshot:d})=>d.capability);if(new Set(r).size!==r.length)throw new Error("Native contract contains duplicate capabilities");let n=[t,...i.flatMap(({snapshot:d})=>d.source===null?[]:[d.source])];if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate artifact sources");let a=gl(e.briefMarkdown,t,Ss.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(...wl(f,d.source,Ss.maxAcceptanceCriteria-a.length)),a.push(..._y(f,d.source,Ss.maxAcceptanceCriteria-a.length)));if(a.sort(lH),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>Ss.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${Ss.maxAcceptanceCriteria}-criterion acceptance budget`);let o=a.map(({id:d})=>d);if(new Set(o).size!==o.length)throw new Error("Native contract contains duplicate acceptance criteria");let s={source:t,contentHash:Lk(e.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=D(sH,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:D(oH,u)}}var yu={maxSpecs:64,maxFileBytes:xo,maxTotalBytes:4*1024*1024};async function ja(e){if(e.specChanges.length>yu.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await Z({root:e.changeDir,ref:e.briefRef,maxBytes:yu.maxFileBytes}),i=t.size,r=[];for(let n of e.specChanges){if(n.operation==="remove"){r.push({capability:n.capability,operation:"remove",source:null,baseHash:n.base_hash,markdown:null});continue}if(!n.source)throw new Error(`Native contract ${n.capability} has no proposed spec source`);let a=await Z({root:e.changeDir,ref:n.source,maxBytes:yu.maxFileBytes});if(i+=a.size,i>yu.maxTotalBytes)throw new Error("Native contract exceeds its total byte budget");r.push({capability:n.capability,operation:n.operation,source:a.ref,baseHash:n.base_hash,markdown:a.text})}return{contract:Fk({briefSource:t.ref,briefMarkdown:t.text,specs:r}),sourceCount:r.filter(n=>n.source!==null).length+1,totalBytes:i}}import{execFile as xH}from"node:child_process";import{promisify as AH}from"node:util";var FJ=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");import{promises as vH}from"fs";import $a from"path";var Or={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},Oa=/^[a-f0-9]{64}$/u;function Nu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function bu(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function $r(e,t,i=2e3){if(typeof e!="string"||e.length===0||e.length>i)throw new Error(`${t} must be a non-empty string of at most ${i} characters`);return e}function Bk(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Fp(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function uH(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||$a.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=$a.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function Bp(e,t){return $a.join(H(e,t),"checkpoints","progress.json")}function Hr(e,t){return $a.join(H(e,t),"checkpoint-journal.json")}function Vp(e,t,i){if(!Oa.test(i))throw new Error("Native checkpoint manifest hash is invalid");return $a.join(H(e,t),"checkpoints","manifests",`${i}.json`)}function dH(e){if(!Oa.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function qp(e,t,i){let r=await re({root:e,file:t,maxBytes:Or.maxDocumentBytes,label:i});return JSON.parse(r.bytes.toString("utf8"))}function fH(e,t){let i=Nu(e,`checkpoint manifest artifact ${t}`);bu(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let r=uH($r(i.path,`checkpoint artifact ${t} path`,4096)),n=li(r);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${r}`);if(typeof i.hash!="string"||!Oa.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:r,hash:i.hash,size:Fp(i.size,`checkpoint artifact ${t} size`)}}function ku(e,t){let i=Nu(e,"Native checkpoint manifest");if(bu(i,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),i.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(i.change!==t)throw new Error("Native checkpoint manifest change mismatch");if(!Array.isArray(i.artifacts))throw new Error("Native checkpoint manifest artifacts must be an array");if(i.artifacts.length>Or.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let r=i.artifacts.map(fH),n=[...r].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(r)!==JSON.stringify(n))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(r.map(o=>o.path)).size!==r.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=Fp(i.totalBytes,"checkpoint manifest totalBytes");if(r.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");if(a>Or.maxTotalBytes)throw new Error("Native checkpoint manifest totalBytes exceeds its budget");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:r,totalBytes:a}}function Wp(e){return L(JSON.stringify(ku(e,e.change)))}function zp(e,t){let i=Nu(e,"Native progress checkpoint");if(bu(i,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),i.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(i.change!==t)throw new Error("Native checkpoint change mismatch");let r=i.phase;if(r!=="shape"&&r!=="build"&&r!=="verify"&&r!=="archive")throw new Error("Native checkpoint phase is invalid");let n=Bk(i.previousRevision,"Native checkpoint previousRevision"),a=Bk(i.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=$r(i.manifestHash,"Native checkpoint manifestHash",64);if(!Oa.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=dH(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=$r(i.inputHash,"Native checkpoint inputHash",64);if(!Oa.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=$r(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=Fp(i.artifactCount,"Native checkpoint artifactCount");if(u>Or.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=$r(i.summary,"Native checkpoint summary"),f=$r(i.nextAction,"Native checkpoint nextAction");if($t(d)!==d||$t(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:$r(i.id,"Native checkpoint id",128),change:t,phase:r,previousRevision:n,stateRevision:a,summary:d,nextAction:f,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function hH(e,t){let i=Nu(e,"Native checkpoint journal");if(bu(i,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),i.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(i.change!==t)throw new Error("Native checkpoint journal change mismatch");let r=lt(i.previousState),n=lt(i.nextState),a=zp(i.checkpoint,t),o=ku(i.manifest,t),s=$r(i.inputHash,"Native checkpoint journal inputHash",64),c=L(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!Oa.test(s)||s!==a.inputHash||s!==c||i.id!==a.id||i.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(r.name!==t||n.name!==t||n.revision!==r.revision+1||a.previousRevision!==r.revision||a.stateRevision!==n.revision||a.phase!==n.phase||a.manifestHash!==Wp(o)||a.artifactCount!==o.artifacts.length)throw new Error("Native checkpoint journal state mismatch");return{schema:"comet.native.checkpoint-journal.v1",id:a.id,change:t,inputHash:s,createdAt:a.createdAt,previousState:r,nextState:n,checkpoint:a,manifest:o}}async function pH(e,t,i){let r=$a.resolve(e.projectRoot,...t.split("/"));if(!O(e.projectRoot,r)||O(e.nativeRoot,r)||O(e.runtimeDir,r))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=eh(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await re({root:e.projectRoot,file:r,maxBytes:Or.maxFileBytes,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot,e.runtimeDir],hooks:{afterParentChainCaptured:()=>i?.afterParentChainCaptured?.(t),afterOpen:()=>i?.afterOpen?.(t),beforeRead:()=>i?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function mH(e,t){let i=Bp(e,t),r=j(e,i);await T(r,i);try{return zp(await qp(r,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Jp(e,t,i){let r=Vp(e,t,i),n=j(e,r);await T(n,r);let a=await qp(n,r,"Native checkpoint manifest"),o=ku(a,t);if(Gp(e,o),Wp(o)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function Dr(e,t){let i=Hr(e,t),r=j(e,i);await T(r,i);try{let n=hH(await qp(r,i,"Native checkpoint journal"),t);return Gp(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Vk(e,t,i,r){let n=ku(i,t);Gp(e,n);let a=Wp(n),o=Vp(e,t,a),s=j(e,o);await T(s,o);try{let c=await Jp(e,t,a);if(JSON.stringify(c)!==JSON.stringify(n))throw new Error("Native checkpoint manifest hash collision")}catch(c){if(c.code!=="ENOENT")throw c}return await ee(o,n,{containedRoot:s,beforeCommit:r?.beforeCommit}),a}function Gp(e,t){for(let i of t.artifacts){let r=eh(e,i.path);if(r)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${r}): ${i.path}`)}}async function qk(e,t){let i=zp(t,t.change),r=await Jp(e,i.change,i.manifestHash),n=L(JSON.stringify({summary:i.summary,nextAction:i.nextAction,artifacts:r.artifacts}));if(i.inputHash!==n||i.artifactCount!==r.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");let a=Bp(e,t.change),o=j(e,a);await T(o,a),await ee(a,i,{containedRoot:o})}async function Wk(e){let t;try{t=await mH(e.paths,e.name)}catch(a){return{checkpoint:null,manifest:null,freshness:"stale",reasons:["checkpoint-progress-invalid"],findings:[{code:"checkpoint-progress-invalid",message:`Native progress checkpoint is invalid: ${a.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint file aside before retrying`,path:Bp(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let i=[],r=[];t.stateRevision!==e.stateRevision&&i.push("state-revision-changed");let n=null;try{n=await Jp(e.paths,e.name,t.manifestHash);let a=L(JSON.stringify({summary:t.summary,nextAction:t.nextAction,artifacts:n.artifacts}));if(t.inputHash!==a||t.artifactCount!==n.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");for(let o of n.artifacts)try{let s=await pH(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&i.push(`artifact-changed:${o.path}`)}catch{i.push(`artifact-unavailable:${o.path}`)}}catch(a){i.push("checkpoint-manifest-invalid"),r.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:Vp(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:i.length===0?"fresh":"stale",reasons:i,findings:r}}async function zk(e,t,i){let r=await Dr(e,t);if(!r)return null;if(await Vk(e,r.change,r.manifest)!==r.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await ru(e,r.nextState,r.previousState.revision,{allowPendingCheckpointRecovery:!0}),await i?.afterStateWritten?.(r),await qk(e,r.checkpoint),await i?.afterProgressWritten?.(r),await vH.rm(Hr(e,t),{force:!0}),r}async function Jk(e,t,i){return se(e,`continue checkpoint ${t}`,()=>Nn(e,t,`continue checkpoint ${t}`,async()=>(await wu(e,t),zk(e,t,i))))}import{constants as Up,promises as Ot}from"node:fs";import Ha from"node:path";var gH=/^[a-f0-9]{64}$/u,wH=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,Es=512*1024;function yH(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Su(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return vt(i,r)?z(i,r):z(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function NH(e,t){let i=Ha.resolve(e),r=Ha.resolve(t);if(!O(i,r))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=i;for(let o of["",...Ha.relative(i,r).split(Ha.sep).filter(Boolean)]){o&&(a=Ha.join(a,o));let s=await Ot.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await Ot.realpath(a);if(n.length>0&&!O(n[0].realPath,c))throw new Error("Native check receipt parent resolves outside the Native root");n.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs})}return n}async function Gk(e){for(let t of e){let i=await Ot.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!yH(t,i)||await Ot.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function bH(e){if(!gH.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function kH(e){let t=wH.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function SH(e,t,i){return fr(H(e,t),bH(i))}async function EH(e,t,i){let r=await NH(i,Ha.dirname(e)),n=await Ot.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(n.size>Es)throw new Error(`Native check receipt exceeds ${Es} bytes`);let[a,o]=await Promise.all([Ot.realpath(t),Ot.realpath(e)]);if(!O(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":Up.O_RDONLY|Up.O_NOFOLLOW|Up.O_NONBLOCK,c=await Ot.open(e,s).catch(l=>{throw l.code==="ELOOP"||l.code==="ENXIO"?new Error("Native check receipt became unsafe while opening"):l});try{let[l,u,d]=await Promise.all([c.stat(),Ot.lstat(e),Ot.realpath(e)]);if(await Gk(r),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Su(n,l)||!Su(l,u))throw new Error("Native check receipt changed while opening");let f=[],h=0,v=Buffer.allocUnsafe(16*1024);for(;;){let g=Es+1-h,y=await c.read(v,0,Math.min(v.length,g),null);if(y.bytesRead===0)break;if(h+=y.bytesRead,h>Es)throw new Error(`Native check receipt exceeds ${Es} bytes`);f.push(Buffer.from(v.subarray(0,y.bytesRead)))}let[m,p,b]=await Promise.all([c.stat(),Ot.lstat(e),Ot.realpath(e)]);if(await Gk(r),!p.isFile()||p.isSymbolicLink()||b!==o||!O(a,b)||!Su(l,m)||!Su(l,p))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,h).toString("utf8"))}finally{await c.close()}}async function Uk(e,t,i){let r=kH(i),n=H(e,t),a=SH(e,t,r),o=j(e,a);await T(o,a);let s=lu(await EH(a,n,o));if(s.change!==t||s.receiptHash!==r)throw new Error("Native check receipt ref/hash/change mismatch");return s}var Ps=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var OG=64*1024;var HG=3600*1e3;var DG=AH(xH);var _H=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function Kk(e,t){let i=[];for(let r of _H){let n=e.bindings[r],a=t[r];n!==a&&i.push(`${r}: expected ${JSON.stringify(a)}, got ${JSON.stringify(n)}`)}return{ok:i.length===0,mismatches:i}}async function Yk(e){if(e.receipt.kind!=="static-inspection")return null;let t=await Uk(e.paths,e.state.name,e.receipt.evidence.checkReceiptRef);if(t.receiptHash!==e.receipt.evidence.checkReceiptHash)throw new Error("Native static receipt dependency hash mismatch");return t}var Lr=class extends Error{details;constructor(t){let i=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(r=>`${r.ref}${r.acceptanceId?`[${r.acceptanceId}]`:""} -> ${r.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=t}};function TH(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}async function IH(e){let t=TH(e.bundle.baseline),i=await zh(e.paths,t,{origin:"explicit",now:e.now});return mp({baseline:t,current:i,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason,externalDrift:e.bundle.authority.externalDrift}).scope.currentProjectionHash}async function Qk(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await ws(e.paths,e.state.name,e.state.implementation_scope),i=await ja({changeDir:ne(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),r=await IH({paths:e.paths,bundle:t,now:e.now}),n=[];return i.contract.contractHash!==t.scope.contractHash&&n.push("verification-contract-stale"),r!==t.scope.currentProjectionHash&&n.push("verification-implementation-stale"),{bundle:t,contract:i.contract,contractHash:i.contract.contractHash,acceptanceHash:i.contract.acceptanceHash,findingCodes:n}}async function Zk(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await Qk(e),i=[...new Set(t.findingCodes)].sort();return{freshness:i.length===0?"fresh":"stale",findingCodes:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"]}}}async function jH(e){let t=await Z({root:ne(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:Iy(t.text)}}function $H(e){let{receipt:t,implementationScope:i}=e,r=[],n=pp({baseline:i.baseline,current:i.current,declaredArtifacts:i.scope.declaredArtifacts}).filter(o=>o.attributedTo.length>0&&o.after!==null),a=n.reduce((o,s)=>o+s.after.size,0);return(t.stale||t.sourceRevision!==e.sourceRevision||t.contract.expectedHash!==e.contractHash||t.contract.beforeHash!==e.contractHash||t.contract.afterHash!==e.contractHash||t.implementation.scopeHash!==i.scope.scopeHash||t.implementation.expectedSnapshotHash!==i.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==i.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==i.scope.currentProjectionHash||t.counts.filesSelected!==n.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==n.length||t.counts.bytesScanned!==a))&&r.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&r.push("verification-receipt-outcome-mismatch"),r}function OH(e){return{change:e.state.name,sourceRevision:e.sourceRevision??e.state.revision,contractHash:e.contractHash,scopeHash:e.implementationScope.scope.scopeHash,snapshotHash:e.implementationScope.scope.currentProjectionHash,artifactHash:kp(e.implementationScope.scope.declaredArtifacts)}}async function Xk(e){let t=await ys(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let r=Kk(t,e.expectedBindings);if(i.push(...r.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&i.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),i.length>0)throw new Lr([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:i}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let n=await Yk({paths:e.paths,state:e.state,receipt:t});if(n){let a=$H({receipt:n,sourceRevision:e.expectedBindings.sourceRevision,result:e.result,contractHash:e.contractHash,implementationScope:e.implementationScope});if(a.length>0)throw new Error(`Native static receipt dependency is invalid: ${a.join(", ")}`)}return t}async function HH(e){let t=OH({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let r of e.requiredReceiptRefs){let n=await Xk({...e,ref:r,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof Lr)return i.push(...a.details),null;throw a});if(n!==null&&n.kind!=="static-inspection")throw new Error("Native required-check evidence must be a static-inspection receipt")}for(let r of e.trace.entries)if(r.status!=="missing")for(let n of r.evidenceRefs){let a=await Xk({...e,result:r.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:r.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof Lr)return i.push(...o.details),null;throw o});if(a!==null){if(a.kind!=="automated-check"&&a.kind!=="manual-evidence")throw new Error("Native acceptance evidence must be automated-check or manual-evidence");if(r.status==="failed"&&a.status==="passed")throw new Error("Native failed acceptance evidence must reference a non-passing receipt")}}if(i.length>0)throw new Lr(i)}function Kp(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function Eu(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:Kp(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([Qk(e),Ta(e.paths,e.state.name,e.state.verification_evidence)]);if(i.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:Kp(e.state.verification_result,"stale"),envelope:null};let r=await jH({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),n=[...t.findingCodes];(r.hash!==i.reportHash||r.ref!==i.reportRef)&&n.push("verification-report-stale"),(i.result!==e.state.verification_result||i.implementationScopeRef!==e.state.implementation_scope||i.partialAllowanceRef!==e.state.partial_allowance||i.sourceRevision>=e.state.revision||i.contractHash!==t.bundle.scope.contractHash||i.acceptanceCriteriaHash!==t.acceptanceHash)&&n.push("verification-state-mismatch");try{await HH({paths:e.paths,state:e.state,result:i.result,trace:i.acceptanceTrace,requiredReceiptRefs:i.requiredReceiptRefs,contractHash:i.contractHash,implementationScope:t.bundle,sourceRevision:i.sourceRevision})}catch{n.push("verification-receipt-invalid")}let a=[...new Set(n)].sort(),o=a.length>0?"stale":i.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:i.contractHash,acceptanceHash:i.acceptanceCriteriaHash,implementationScopeHash:i.implementationScopeHash,reportHash:i.reportHash,envelopeHash:i.envelopeHash,partialAllowanceHash:i.partialAllowanceHash,skippedAcceptanceCount:i.acceptanceTrace.skipped},envelope:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:Kp(e.state.verification_result,"invalid"),envelope:null}}}function LH(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function tS(e){try{return await DH.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function MH(e,t){try{return(await Z({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function FH(e,t,i){let r=nu(e,i.capability);if(!O(e.nativeRoot,r))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let n=eS.relative(e.nativeRoot,r).replaceAll("\\","/"),a=await MH(e.nativeRoot,n),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await Z({root:ne(e,t),ref:i.source})).hash}return{capability:i.capability,operation:i.operation,expectedBaseHash:i.operation==="create"?null:i.base_hash,actualBaseHash:a,proposedHash:o}}async function BH(e,t){return tS(Ue(e,t))}async function Pu(e){let t=e.now??new Date,i=await De(e.paths,e.name),r=await kt(e.paths,e.name),n=await ye(e.paths.projectRoot),a=LH(i.name,t),o=eS.resolve(e.paths.nativeRoot,...a.split("/"));if(!O(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,f,h]=await Promise.all([Promise.all(i.spec_changes.map(v=>FH(e.paths,i.name,v))),Eu({paths:e.paths,state:i,now:t}),hu(e.paths,i.name),Na(e.paths,i.name),ba(e.paths,i.name),BH(e.paths,i.name),tS(o)]);return Nb({change:i.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:i.schema,revision:i.revision,phase:i.phase,archived:i.archived,pendingJournal:u||d||f,targetRef:a,targetExists:h,specs:s,evidence:c.evidence,workspace:r?.schema==="comet.native.workspace.v3"?{schema:r.schema,isolation:r.isolation,changeBranch:r.changeBranch,targetBranch:r.targetBranch,finish:r.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}import{promises as Yp}from"node:fs";import Vi from"node:path";var VH="comet.native.archive-tree.v1",qH={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};function nS(e){let t={...qH,...e};for(let[i,r]of Object.entries(t))if(!Number.isSafeInteger(r)||r<=0)throw new Error(`Native Archive content limit ${i} must be a positive safe integer`);return t}function iS(e){return JSON.stringify(e.map(t=>({name:t.name,kind:t.isDirectory()?"directory":t.isFile()?"file":t.isSymbolicLink()?"symlink":"other"})).sort((t,i)=>t.name.localeCompare(i.name)))}function rS(e,t,i,r){if(i.entryCount+=1,i.entryCount>r.maxEntries)throw new Error(`Native Archive content exceeds ${r.maxEntries} entries`);if(Buffer.byteLength(t.ref,"utf8")>r.maxRefBytes)throw new Error(`Native Archive content ref exceeds ${r.maxRefBytes} bytes: ${t.ref}`);let n=Buffer.byteLength(JSON.stringify(t),"utf8");if(i.manifestBytes+=n+(e.length===0?0:1),i.manifestBytes+2>r.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${r.maxManifestBytes} bytes`);e.push(t)}async function aS(e,t,i,r,n,a){if(a>n.maxDepth)throw new Error(`Native Archive content exceeds depth ${n.maxDepth}`);let o=await wt({root:e,directory:t,label:`Native Archive content directory ${Vi.relative(e,t)||"."}`,maxEntries:n.maxEntries}),s=iS(o.entries),c=[...o.entries];c.sort((u,d)=>u.name.localeCompare(d.name));for(let u of c){await o.verify();let d=Vi.join(t,u.name),f=Vi.relative(e,d).replaceAll("\\","/"),h=await Yp.lstat(d);if(u.isSymbolicLink()||h.isSymbolicLink())throw new Error(`Native Archive content must not contain symlinks or junctions: ${f}`);if(u.isDirectory()&&h.isDirectory()){rS(i,{ref:f,kind:"directory"},r,n),await aS(e,d,i,r,n,a+1);continue}if(!u.isFile()||!h.isFile())throw new Error(`Native Archive content must contain only files and directories: ${f}`);let v=await re({root:e,file:d,maxBytes:n.maxFileBytes,label:`Native Archive content file ${f}`});if(r.totalBytes+=v.size,r.totalBytes>n.maxTotalBytes)throw new Error(`Native Archive content exceeds ${n.maxTotalBytes} total file bytes`);rS(i,{ref:f,kind:"file",hash:v.hash,size:v.size},r,n),await o.verify()}await o.verify();let l=await wt({root:e,directory:t,label:`Native Archive content directory ${Vi.relative(e,t)||"."}`,maxEntries:n.maxEntries});if(iS(l.entries)!==s)throw new Error(`Native Archive content directory changed while reading: ${Vi.relative(e,t)||"."}`);await Promise.all([o.verify(),l.verify()])}async function oS(e,t={}){let i=nS(t);e=Vi.resolve(e);let r=await Yp.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`Native Archive move source must be a real directory: ${e}`);let n=[];await aS(e,e,n,{entryCount:0,totalBytes:0,manifestBytes:0},i,0);let o=JSON.stringify(n);if(Buffer.byteLength(o,"utf8")>i.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${i.maxManifestBytes} bytes`);return L(`${VH}\0${o}`)}async function ai(e,t={}){let i=nS(t);e=Vi.resolve(e);let r;try{r=await Yp.lstat(e)}catch(n){if(n.code==="ENOENT")return null;throw n}if(r.isSymbolicLink())throw new Error(`Native Archive transaction path must not be a symlink or junction: ${e}`);if(r.isFile())return{kind:"file",hash:(await re({root:Vi.dirname(e),file:e,maxBytes:i.maxFileBytes,label:`Native Archive transaction file ${Vi.basename(e)}`})).hash};if(r.isDirectory())return{kind:"directory",hash:await oS(e,i)};throw new Error(`Native Archive transaction path has an unsupported file type: ${e}`)}import{promises as rt}from"node:fs";import Ae from"node:path";var Qp=16*1024*1024,WH=256*1024,zH=16*1024,Rs="comet.native.archive-cas.v1";function JH(e,t){let i="runtime/",r=t.startsWith(i),n=r?e.runtimeDir:e.nativeRoot,a=r?t.slice(i.length):t,o=Ae.resolve(n,...a.split("/"));if(!O(n,o))throw new Error(`Unsafe Native Archive transaction ref: ${t}`);return o}async function Le(e,t){let i=JH(e,t);return T(j(e,i),i)}function Mr(e,t,i="file"){return t===null?e===null:e?.kind===i&&e.hash===t}function Da(e){return e===null?"missing":`${e.kind}:${e.hash}`}async function ft(e){let t=await ai(e.target);if(!Mr(t,e.expectedHash,e.expectedKind))throw new Error(`${e.label} content changed: expected ${e.expectedHash??"missing"}, got ${Da(t)}`);return t}async function Zp(e,t){let i=await hi(e,t),r=await re({root:e.runtimeDir,file:i.journal,maxBytes:WH,label:`Native Archive transaction journal ${t}`}),n=jl(JSON.parse(r.bytes.toString("utf8")));if(n.id!==t)throw new Error(`Invalid Native Archive transaction journal: ${t}`);return n}async function Ru(e,t,i){let r=jl({...t,status:i}),n=await hi(e,r.id);return await ee(n.journal,r,{containedRoot:e.runtimeDir}),r}function Cu(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}function sS(e){return{...Cu(e),ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Fr(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs}function GH(e,t){return Fr(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function ie(e){try{return await rt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function ki(e){let t=await rt.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let i=sS(t),r=await re({root:j(e.paths,e.file),file:e.file,maxBytes:Qp,label:e.label}),n=await rt.lstat(e.file);if(!n.isFile()||n.isSymbolicLink()||!GH(i,sS(n))||r.hash!==e.expectedHash)throw new Error(`${e.label} content changed or object identity changed while binding`);return{identity:Cu(n),size:r.size}}function UH(e,t,i,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Archive CAS ${t.id} ${i} record must be an object`);let n=e;if(Object.keys(n).sort().join(",")!=="hash,identity,operationId,role,schema")throw new Error(`Archive CAS ${t.id} ${i} record has an invalid shape`);let o=n.identity;if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`Archive CAS ${t.id} ${i} identity must be an object`);let s=o;if(Object.keys(s).sort().join(",")!=="birthtimeMs,dev,ino")throw new Error(`Archive CAS ${t.id} ${i} identity has an invalid shape`);for(let c of["dev","ino","birthtimeMs"])if(typeof s[c]!="number"||!Number.isFinite(s[c])||s[c]<0)throw new Error(`Archive CAS ${t.id} ${i} identity ${c} is invalid`);if(n.schema!==Rs||n.operationId!==t.id||n.role!==i||n.hash!==r)throw new Error(`Archive CAS ${t.id} ${i} record is not transaction-bound`);return{schema:Rs,operationId:t.id,role:i,hash:r,identity:{dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs}}}async function Si(e,t,i,r){let n=await hi(e,t.id),a=Ae.join(n.backups,".cas"),o=`.${Ae.basename(r)}.comet-archive-cas-${t.id}-${i.id}`,s={directory:a,originalRecord:Ae.join(a,`${i.id}.original.json`),postRecord:Ae.join(a,`${i.id}.post.json`),candidate:Ae.join(a,`${i.id}.candidate`),originalQuarantine:Ae.join(Ae.dirname(r),`${o}.original`),rollbackQuarantine:Ae.join(Ae.dirname(r),`${o}.rollback`)};return await Promise.all(Object.values(s).map(c=>T(j(e,c),c))),s}async function Ht(e){if(!await ie(e.file))return null;let t=await re({root:e.paths.runtimeDir,file:e.file,maxBytes:zH,label:`Archive CAS ${e.operation.id} ${e.role} record`});return UH(JSON.parse(t.bytes.toString("utf8")),e.operation,e.role,e.expectedHash)}async function xu(e){let t=await Ht(e);if(t){if(!Fr(t.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} object identity changed`);return t}await fi({root:e.paths.runtimeDir,directory:Ae.dirname(e.file),label:`Archive CAS ${e.operation.id} records`});let i={schema:Rs,operationId:e.operation.id,role:e.role,hash:e.expectedHash,identity:e.identity};try{await ee(e.file,i,{containedRoot:e.paths.runtimeDir,exclusive:!0})}catch(n){if(n.code!=="EEXIST")throw n}let r=await Ht(e);if(!r||!Fr(r.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} record changed`);return r}async function Re(e){let t=await ki({paths:e.paths,file:e.file,expectedHash:e.record.hash,label:e.label});if(!Fr(e.record.identity,t.identity))throw new Error(`${e.label} object identity changed`)}async function KH(e){let t=await ki({paths:e.paths,file:e.file,expectedHash:e.expectedHash,label:e.label}),i=await xu({paths:e.paths,file:e.recordFile,operation:e.operation,role:e.role,expectedHash:e.expectedHash,identity:t.identity});return await Re({paths:e.paths,file:e.file,operation:e.operation,record:i,label:e.label}),i}async function YH(e){if(!await ie(e.quarantine)||await ie(e.target))return;let t=await Zt({root:j(e.paths,e.target),directory:Ae.dirname(e.target),label:`Archive CAS ${e.operation.id} quarantine restoration`});await t.verify();try{await rt.link(e.quarantine,e.target)}catch(n){if(n.code==="EEXIST")return;throw n}await t.verify();let[i,r]=await Promise.all([rt.lstat(e.quarantine),rt.lstat(e.target)]);if(!Fr(Cu(i),Cu(r)))throw new Error(`Archive CAS ${e.operation.id} could not restore quarantined content`);await rt.unlink(e.quarantine),await t.verify()}async function dS(e){if(await ie(e.quarantine)){await Re({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`});return}let t=await Zt({root:j(e.paths,e.target),directory:Ae.dirname(e.target),label:`Archive ${e.phase} target ${e.operation.target}`});await Re({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`}),await e.hooks?.afterArchiveTargetBound?.(e.phase,e.operation,e.target),await t.verify(),await Re({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`});try{await rt.rename(e.target,e.quarantine),await t.verify(),await Re({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`})}catch(i){throw await YH(e),new Error(`Archive ${e.phase} target ${e.operation.target} changed during quarantine`,{cause:i})}await e.hooks?.afterArchiveTargetQuarantined?.(e.phase,e.operation,e.quarantine)}async function bn(e){if(!await ie(e.file))return;await Re(e);let t=await Zt({root:j(e.paths,e.file),directory:Ae.dirname(e.file),label:e.label});await t.verify(),await Re(e),await rt.unlink(e.file),await t.verify()}async function cS(e,t,i){if(!t.backup||t.expectedTargetHash===null)return;let r=await Le(e,t.target),n=await Le(e,t.backup),a=await ai(n);if(a!==null){if(!Mr(a,t.expectedTargetHash))throw new Error(`Archive transaction backup content changed: ${t.backup}`);return}await ft({target:r,expectedHash:t.expectedTargetHash,label:`Archive transaction target ${t.target}`}),await Nr({sourceRoot:j(e,r),source:r,targetRoot:j(e,n),target:n,maxBytes:Qp,label:`Archive transaction backup ${t.backup}`,expectedHash:t.expectedTargetHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>i?.afterProtectedCopySourceParentCaptured?.("backup",t.target)}}),await ft({target:n,expectedHash:t.expectedTargetHash,label:`Archive transaction backup ${t.backup}`})}async function fS(e){let t=e.operation.expectedTargetHash;if(t===null)throw new Error(`Archive operation ${e.operation.id} has no original target to quarantine`);let i=await Si(e.paths,e.journal,e.operation,e.target),r=await Ht({paths:e.paths,file:i.originalRecord,operation:e.operation,role:"original",expectedHash:t});if(await ie(i.originalQuarantine)){if(!r)throw new Error(`Archive apply quarantine ${e.operation.target} has no bound object identity`);return await Re({paths:e.paths,file:i.originalQuarantine,operation:e.operation,record:r,label:`Archive apply quarantine ${e.operation.target}`}),await cS(e.paths,e.operation,e.hooks),{record:r,quarantine:i.originalQuarantine}}if(!await ie(e.target))throw new Error(`Archive apply target ${e.operation.target} disappeared before quarantine`);return r??=await KH({paths:e.paths,file:e.target,recordFile:i.originalRecord,operation:e.operation,role:"original",expectedHash:t,label:`Archive apply target ${e.operation.target}`}),await Re({paths:e.paths,file:e.target,operation:e.operation,record:r,label:`Archive apply target ${e.operation.target}`}),await cS(e.paths,e.operation,e.hooks),await dS({paths:e.paths,operation:e.operation,phase:"apply",target:e.target,quarantine:i.originalQuarantine,record:r,hooks:e.hooks}),{record:r,quarantine:i.originalQuarantine}}async function lS(e){let t=await Si(e.paths,e.journal,e.operation,e.target);return await ie(t.candidate)?(await ki({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`}),t.candidate):(await fi({root:e.paths.runtimeDir,directory:t.directory,label:`Archive CAS ${e.operation.id} records`}),await Nr({sourceRoot:j(e.paths,e.staged),source:e.staged,targetRoot:e.paths.runtimeDir,target:t.candidate,maxBytes:Qp,label:`Archive transaction staged file ${e.operation.staged}`,expectedHash:e.operation.stagedHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>e.hooks?.afterProtectedCopySourceParentCaptured?.("apply",e.operation.staged)}}),t.candidate)}async function XH(e){let t=e.operation.stagedHash,i=await Si(e.paths,e.journal,e.operation,e.target),r=await Ht({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t});if(r&&await ie(e.target))return await Re({paths:e.paths,file:e.target,operation:e.operation,record:r,label:`Archive write target ${e.operation.target}`}),await ie(i.candidate)&&await bn({paths:e.paths,file:i.candidate,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r;if(await ie(e.target)){let c=await lS(e),l=await ki({paths:e.paths,file:c,expectedHash:t,label:`Archive write candidate ${e.operation.target}`}),u=await ki({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!Fr(l.identity,u.identity))throw new Error(`Archive write target ${e.operation.target} is occupied by an external object`);return r=await xu({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:u.identity}),await bn({paths:e.paths,file:c,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r}let n=await lS(e),a=await ki({paths:e.paths,file:n,expectedHash:t,label:`Archive write candidate ${e.operation.target}`});await fi({root:j(e.paths,e.target),directory:Ae.dirname(e.target),label:`Archive write target ${e.operation.target}`});let o=await Zt({root:j(e.paths,e.target),directory:Ae.dirname(e.target),label:`Archive write target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("apply",e.operation,e.target),await o.verify(),await Re({paths:e.paths,file:n,operation:e.operation,record:{schema:Rs,operationId:e.operation.id,role:"post",hash:t,identity:a.identity},label:`Archive write candidate ${e.operation.target}`});try{await rt.link(n,e.target)}catch(c){throw c.code==="EEXIST"?new Error(`Archive write target ${e.operation.target} was created before exclusive install`,{cause:c}):c}await o.verify(),await e.hooks?.afterArchiveTargetInstalled?.("apply",e.operation,e.target);let s=await ki({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!Fr(a.identity,s.identity))throw new Error(`Archive write target ${e.operation.target} changed during install`);return r=await xu({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:s.identity}),await bn({paths:e.paths,file:n,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r}async function QH(e,t,i,r){let n=await Le(e,i.target),a=await Le(e,i.staged);if(await ft({target:a,expectedHash:i.stagedHash,label:`Archive transaction staged file ${i.staged}`}),i.expectedTargetHash!==null){let o=await Si(e,t,i,n);(!await Ht({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash})||!await ie(n))&&await fS({paths:e,journal:t,operation:i,target:n,hooks:r})}else{let o=await ai(n);if(o!==null&&!Mr(o,i.stagedHash))throw new Error(`Archive transaction target ${i.target} changed before create: ${Da(o)}`)}await XH({paths:e,journal:t,operation:i,staged:a,target:n,hooks:r}),await ft({target:n,expectedHash:i.stagedHash,label:`Archive transaction target ${i.target}`})}async function ZH(e,t,i,r){let n=await Le(e,i.target);await fS({paths:e,journal:t,operation:i,target:n,hooks:r}),await ft({target:n,expectedHash:null,label:`Archive transaction target ${i.target}`})}async function eD(e,t){let i=await Le(e,t.source),r=await Le(e,t.target),[n,a]=await Promise.all([ai(i),ai(r)]);if(!(n===null&&Mr(a,t.expectedSourceHash,"directory"))){if(!Mr(n,t.expectedSourceHash,"directory")||a!==null)throw new Error(`Archive transaction move ${t.id} content changed: source=${Da(n)}, target=${Da(a)}`);await rt.mkdir(Ae.dirname(r),{recursive:!0}),await rt.rename(i,r),await ft({target:r,expectedHash:t.expectedSourceHash,expectedKind:"directory",label:`Archive transaction move target ${t.target}`})}}async function tD(e,t,i,r){return i.type==="write"?QH(e,t,i,r):i.type==="remove"?ZH(e,t,i,r):eD(e,i)}function iD(e){let t=0,i=!1,r=[];for(let n of e.events){if(n.type!=="operation-started"&&n.type!=="operation-completed")continue;let a=e.journal.operations[t];if(!a||n.operationId!==a.id)throw new Error(`Native Archive transaction ${e.journal.id} operation events are out of order`);if(n.type==="operation-started"){i=!0;continue}if(!i)throw new Error(`Native Archive transaction ${e.journal.id} completed an operation before it started`);r.push(a.id),t+=1,i=!1}return r}async function rD(e,t,i,r){let n=await Le(e,i.target);if(i.type==="write"){let a=await Le(e,i.staged);await ft({target:a,expectedHash:i.stagedHash,label:`Completed Archive staged file ${i.staged}`});let o=await Si(e,t,i,n),s=await Ht({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!s)throw new Error(`Completed Archive target ${i.target} has no CAS identity`);if(await Re({paths:e,file:n,operation:i,record:s,label:`Completed Archive target ${i.target}`}),i.expectedTargetHash!==null){await ft({target:await Le(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let c=await Ht({paths:e,file:o.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!c)throw new Error(`Completed Archive target ${i.target} has no original CAS identity`);if(await ie(o.originalQuarantine))await Re({paths:e,file:o.originalQuarantine,operation:i,record:c,label:`Completed Archive original quarantine ${i.target}`});else if(!r)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`)}return}if(i.type==="remove"){await ft({target:n,expectedHash:null,label:`Completed Archive target ${i.target}`}),await ft({target:await Le(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let a=await Si(e,t,i,n),o=await Ht({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!o)throw new Error(`Completed Archive remove ${i.target} has no original CAS identity`);if(await ie(a.originalQuarantine))await Re({paths:e,file:a.originalQuarantine,operation:i,record:o,label:`Completed Archive original quarantine ${i.target}`});else if(!r)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`);return}r||(await ft({target:await Le(e,i.source),expectedHash:null,label:`Completed Archive move source ${i.source}`}),await ft({target:n,expectedHash:i.expectedSourceHash,expectedKind:"directory",label:`Completed Archive move target ${i.target}`}))}async function hS(e,t,i){let r=t.status==="prepared"?await Ru(e,t,"applying"):t;if(r.status!=="applying")throw new Error(`Native Archive transaction ${r.id} cannot apply from ${r.status}`);let n=await kr(e,r.id),a=iD({journal:r,events:n}),o=new Set(a),s=n.some(l=>l.type==="archive-finalization-started");for(let l of r.operations.slice(0,a.length))await rD(e,r,l,s);let c=o.size;for(let l of r.operations)o.has(l.id)||(l.id==="archive-change"&&await i?.beforeArchiveChangeMove?.(l),await Tt(e,r.id,"operation-started",l.id),await tD(e,r,l,i),await Tt(e,r.id,"operation-completed",l.id),c+=1,await i?.afterOperation?.(l,c));return r=await Zp(e,r.id),r}async function nD(e){try{return await Re(e),!0}catch{return!1}}async function aD(e){await Re({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});let t=await Zt({root:j(e.paths,e.target),directory:Ae.dirname(e.target),label:`Archive rollback target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("rollback",e.operation,e.target),await t.verify(),await Re({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});try{await rt.link(e.quarantine,e.target)}catch(i){throw i.code==="EEXIST"?new Error(`Archive rollback target ${e.operation.target} was created before exclusive restore`,{cause:i}):i}await t.verify(),await e.hooks?.afterArchiveTargetInstalled?.("rollback",e.operation,e.target),await Re({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive rollback target ${e.operation.target}`})}async function Xp(e){if(e.operation.type!=="write")return;let t=await Si(e.paths,e.journal,e.operation,e.target);if(!await ie(t.candidate))return;let i=await ki({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`});await bn({paths:e.paths,file:t.candidate,operation:e.operation,record:{schema:Rs,operationId:e.operation.id,role:"post",hash:e.operation.stagedHash,identity:i.identity},label:`Archive write candidate ${e.operation.target}`})}async function oD(e,t,i,r){let n=await Le(e,i.target),a=await Si(e,t,i,n),o=i.expectedTargetHash,s=o===null?null:await Ht({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:o}),c=i.type==="write"?await Ht({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash}):null;if(i.type==="write"&&!c&&await ie(a.candidate)&&await ie(n)){let l=await ki({paths:e,file:a.candidate,expectedHash:i.stagedHash,label:`Archive write candidate ${i.target}`}),u=await ki({paths:e,file:n,expectedHash:i.stagedHash,label:`Archive rollback target ${i.target}`});Fr(l.identity,u.identity)&&(c=await xu({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash,identity:u.identity}))}if(await ie(a.rollbackQuarantine)){if(!c)throw new Error(`Archive rollback quarantine ${i.target} has no CAS identity`);await Re({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`})}if(await ie(n)&&!(s!==null&&await nD({paths:e,file:n,operation:i,record:s,label:`Archive rollback target ${i.target}`}))){if(!c){if(!s){let u=await ai(n);if(Mr(u,o)){await Xp({paths:e,journal:t,operation:i,target:n});return}}throw new Error(`Archive rollback target ${i.target} is occupied by an external object`)}await dS({paths:e,operation:i,phase:"rollback",target:n,quarantine:a.rollbackQuarantine,record:c,hooks:r})}if(o===null){if(await ie(n))throw new Error(`Archive rollback create target ${i.target} could not be removed`)}else if(!await ie(n)){if(!s||!await ie(a.originalQuarantine))throw new Error(`Archive rollback original target ${i.target} cannot be recovered safely`);await aD({paths:e,operation:i,target:n,quarantine:a.originalQuarantine,record:s,hooks:r})}s&&await ie(a.originalQuarantine)&&await bn({paths:e,file:a.originalQuarantine,operation:i,record:s,label:`Archive rollback original quarantine ${i.target}`}),c&&await ie(a.rollbackQuarantine)&&await bn({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`}),await Xp({paths:e,journal:t,operation:i,target:n}),await ft({target:n,expectedHash:o,label:`Archive rollback target ${i.target}`})}async function sD(e,t){let i=await Le(e,t.source),r=await Le(e,t.target),[n,a]=await Promise.all([ai(i),ai(r)]);if(!(Mr(n,t.expectedSourceHash,"directory")&&a===null)){if(n!==null||!Mr(a,t.expectedSourceHash,"directory"))throw new Error(`Archive rollback move ${t.id} content changed: source=${Da(n)}, target=${Da(a)}`);await rt.mkdir(Ae.dirname(i),{recursive:!0}),await rt.rename(r,i)}}async function pS(e,t,i){let r=await kr(e,t.id);if(r.some(o=>o.type==="archive-finalization-started"||o.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let n=await Ru(e,t,"rolling-back");await Tt(e,n.id,"rollback-started");let a=new Set(r.filter(o=>o.type==="operation-started"||o.type==="operation-completed").map(o=>o.operationId));for(let o of[...n.operations].reverse())a.has(o.id)&&(o.type==="move"?await sD(e,o):await oD(e,n,o,i));return await Tt(e,n.id,"rollback-completed"),n=await Ru(e,n,"rolled-back"),n}async function uS(e,t,i){let r=await Le(e,i.target);if(i.type==="write"){let n=await Si(e,t,i,r),a=await Ht({paths:e,file:n.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!a)throw new Error(`Archive commit target ${i.target} has no CAS identity`);await Re({paths:e,file:r,operation:i,record:a,label:`Archive commit target ${i.target}`});return}await ft({target:r,expectedHash:null,label:`Archive commit target ${i.target}`})}async function cD(e,t){for(let i of t.operations){if(i.type==="move")continue;let r=await Le(e,i.target),n=await Si(e,t,i,r);if(await ie(n.rollbackQuarantine))throw new Error(`Archive commit found an unfinished rollback for ${i.target}`);if(await uS(e,t,i),i.expectedTargetHash!==null){let a=await Ht({paths:e,file:n.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!a)throw new Error(`Archive commit target ${i.target} has no original CAS identity`);await ie(n.originalQuarantine)&&await bn({paths:e,file:n.originalQuarantine,operation:i,record:a,label:`Archive commit original quarantine ${i.target}`})}await Xp({paths:e,journal:t,operation:i,target:r})}for(let i of t.operations)i.type!=="move"&&await uS(e,t,i)}async function Au(e,t,i){return i==="commit"&&await cD(e,t),await Tt(e,t.id,i),i==="commit"?Ru(e,t,"committed"):t}var TU=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});import{promises as lD}from"fs";import uD from"path";var em="comet.selection.v2",dD=16*1024;function _u(e){return uD.join(e,".comet","current-change.json")}function fD(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function mS(e){return e===null||typeof e=="string"}function hD(e){let t;try{t=JSON.parse(e)}catch(i){throw new Error(`current change selection contains invalid JSON: ${i instanceof Error?i.message:String(i)}`,{cause:i})}if(!fD(t))throw new Error("current change selection must be a JSON object");if(t.version===1){if(typeof t.change!="string")throw new Error("legacy current change selection change must be a string");if(t.branch!==void 0&&!mS(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:em,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==em)throw new Error(`current change selection schema must be ${em}`);if(t.workflow!=="native"&&t.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof t.change!="string")throw new Error("current change selection change must be a string");if(!mS(t.branch))throw new Error("current change selection branch must be a string or null");if(t.workflow==="native"&&t.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:t,legacy:!1}}async function tm(e){let t;try{let r=_u(e),{bytes:n}=await rn(r,dD,{label:"current change selection"});t=n.toString("utf8")}catch(r){if(r.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${r instanceof Error?r.message:String(r)}`,{cause:r})}return{status:"selected",...hD(t)}}async function vS(e){await lD.rm(_u(e),{force:!0})}async function gS(e,t,i){let r=await tm(e);return r.status!=="selected"||r.selection.workflow!==t||r.selection.change!==i?!1:(await vS(e),!0)}import{promises as Sn}from"node:fs";import qr from"node:path";var cm=Tn(en(),1);import{promises as DS}from"node:fs";import Dt from"node:path";import{execFileSync as pD}from"node:child_process";var mD=3e4,vD=8*1024*1024,im=class extends Error{constructor(i,r,n){super(`git ${r.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=i;this.args=r;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr};function gD(e,t){try{return pD("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:mD,maxBuffer:vD,windowsHide:!0})}catch(i){let r=typeof i.stderr=="string"?i.stderr.trim():Buffer.isBuffer(i.stderr)?i.stderr.toString("utf8").trim():"";throw new im(e,t,r)}}function Ce(e,t){return gD(e,t).trim()}function Cs(e){return Ce(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}import Me from"node:path";import{promises as ju}from"node:fs";import Tu from"node:path";function wS(...e){if(e.length===0)return Tu.resolve();if(Tu.win32.isAbsolute(e[0])){let t=Tu.win32.resolve(...e);return process.platform==="win32"?t:t.replace(/\\/gu,"/")}return Tu.resolve(...e)}var Iu=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var nm="comet.native.supervisor.v2",wD=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function yD(e,t){let i=Me.relative(Me.resolve(e),Me.resolve(t));return i===""||!Me.isAbsolute(i)&&!i.startsWith(`..${Me.sep}`)}function ND(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native Supervisor parent name: ${e}`);return`comet/supervisor/${e}/integration`}function bD(e,t,i){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(i))throw new Error("Native Supervisor parent and child names are invalid");return wS(e,".worktrees",`${t}-${i}`)}function kS(e,t){return Me.join(We(e,t),"supervisor")}function SS(e,t){return Me.join(kS(e,t),"state.json")}function ES(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!==nm)throw new Error(`Native Supervisor state schema must be ${nm}`);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(La(t.integration.targetCommit,"Native Supervisor target commit"),La(t.integration.headCommit,"Native Supervisor integration head commit"),!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let i=new Set,r=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(i.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(i.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.projectRoot!==void 0&&n.projectRoot!==null&&(typeof n.projectRoot!="string"||n.projectRoot.length===0))throw new Error(`Native Supervisor child ${n.name} projectRoot is invalid`);for(let[a,o]of[["base",n.baseCommit],["candidate",n.candidateCommit],["verified",n.verifiedCommit],["integration",n.integrationCommit]])o!==null&&La(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(La(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),r.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(r.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.role==="builder"&&n.status!=="active"||n.task.role==="verifier"&&!["active","needs-reverify"].includes(n.status))throw new Error(`Native Supervisor child ${n.name} task status is invalid`)}}}async function Ei(e,t){try{let i=await ju.readFile(SS(e,t),"utf8"),r=JSON.parse(i);return ES(r),r}catch(i){if(i.code==="ENOENT")return null;throw i}}async function kn(e,t){ES(t),await ju.mkdir(e.changesRuntimeDir,{recursive:!0}),await ee(SS(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function La(e,t){if(!wD.test(e))throw new Error(`${t} must be a Git commit`)}function xs(e){return structuredClone(e)}function am(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){La(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:r})=>r)),i=e.contract.children.map(r=>({name:r.name,summary:r.summary,dependsOn:[...r.depends_on],status:r.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null}));for(let r of i)for(let n of r.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${r.name} depends on unknown child ${n}`);return{schema:nm,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:i,history:[],finalVerification:{status:"pending",summary:null}}}async function om(e){let t=ND(e.parent),i=Ai(e.paths.projectRoot,t);if(!i)return null;let r=Ai(e.paths.projectRoot,e.targetBranch);if(!r)return null;let n=Jt(e.paths.projectRoot).map(o=>Me.resolve(o)).find(o=>fe(o).currentBranch===t);if(!n)return null;let a=PS({parent:e.parent,targetBranch:e.targetBranch,targetCommit:r,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(i!==r){for(let o of a.children)o.status=o.dependsOn.length===0?"blocked":"pending",o.blocker=o.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;a.integration.headCommit=i}return am(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function $u(e){if(!Cs(e.integration.worktree))throw new Error("Native Supervisor integration worktree must be clean");let t=Ce(e.integration.worktree,["rev-parse","--show-toplevel"]);if(Me.resolve(t)!==Me.resolve(e.integration.worktree))throw new Error("Native Supervisor integration worktree identity is invalid");let i=Ce(e.integration.worktree,["branch","--show-current"]);if(i!==e.integration.branch)throw new Error(`Native Supervisor integration branch mismatch: expected ${e.integration.branch}, got ${i||"(detached)"}`);return Ce(e.integration.worktree,["rev-parse","HEAD"])}async function kD(e){let t=Ai(e.paths.projectRoot,e.state.integration.targetBranch);if(!t||t===e.state.integration.targetCommit)return null;let i=e.state;if($u(i)!==i.integration.headCommit)throw new Error("Native Supervisor integration head changed before target refresh");try{Ce(i.integration.worktree,["merge","--no-edit",i.integration.targetBranch])}catch(o){throw new Error(`Native Supervisor target drift requires conflict resolution in ${i.integration.worktree}`,{cause:o})}let n=Ce(i.integration.worktree,["rev-parse","HEAD"]),a=xs(i);return a.integration.headCommit=n,a.finalVerification={status:"pending",summary:null},am(a,{kind:"target-refreshed",child:null,runId:null,summary:`Target ${i.integration.targetBranch} was refreshed before delivery`}),a.stateVersion+=1,await kn(e.paths,a),a}function SD(e,t){if(La(t.headCommit,"Native Supervisor final verification head commit"),t.summary.trim().length===0)throw new Error("Native Supervisor final verification summary must not be empty");let i=xs(e);if(t.headCommit!==i.integration.headCommit)throw new Error("Native Supervisor final verification head is stale");if(t.status==="passed"){if(i.children.some(({status:r})=>r!=="integrated"))throw new Error("Native Supervisor cannot pass final verification before all children integrate");if(t.layers.parentChecks.length===0)throw new Error("Native Supervisor parent verification requires executed parent checks");if(t.layers.childVerification!=="complete"||t.layers.parentIntegration!=="complete"||t.layers.incomplete.length>0)throw new Error("Native Supervisor final verification evidence is incomplete")}return i.finalVerification={status:t.status,summary:t.summary,layers:{childVerification:t.layers.childVerification,parentIntegration:t.layers.parentIntegration,parentChecks:[...t.layers.parentChecks],notRerun:[...t.layers.notRerun],incomplete:[...t.layers.incomplete]}},i.stateVersion+=1,i}function RS(e){let t=$u(e);if(t===e.integration.headCommit)return e;try{Ce(e.integration.worktree,["merge-base","--is-ancestor",e.integration.headCommit,t])}catch{throw new Error("Native Supervisor integration head is not a descendant of the recorded integration head")}let i=xs(e);return i.integration.headCommit=t,am(i,{kind:"integration-head-reconciled",child:null,runId:null,summary:"Parent-level commits were included in final verification"}),i.stateVersion+=1,i}function CS(e,t){let i=t.verification;if(i===null||t.verification_result==="pending")throw new Error("Native Supervisor final verification has no persisted Portable result");let r=$u(e),n=e.children.every(({status:o,verification:s})=>(o==="integrated"||o==="archived")&&s!==null),a=i.checks.length>0&&i.checks.every(({status:o})=>o==="passed");return SD(e,{status:t.verification_result==="pass"?"passed":t.verification_result==="blocked"?"incomplete":"failed",summary:i.summary.text,headCommit:r,layers:{childVerification:n?"complete":"incomplete",parentIntegration:a?"complete":"incomplete",parentChecks:i.checks.map(({name:o})=>o.text),notRerun:e.children.flatMap(({verification:o})=>o?.checks??[]),incomplete:i.checks.filter(({status:o})=>o!=="passed").map(({name:o})=>o.text)}})}async function As(e){let i=await Ei(e.paths,e.state.parent)??e.state;if(i.stateVersion!==e.state.stateVersion)throw new Error("Native Supervisor state changed before delivery; reload status first");if(i.finalVerification.status!=="passed")throw new Error("Native Supervisor delivery requires a passed final verification");if(!i.children.every(({status:v})=>v==="integrated"||v==="archived"))throw new Error("Native Supervisor delivery requires every child to be integrated");let n=Jt(e.paths.projectRoot).map(v=>Me.resolve(v)).find(v=>fe(v).currentBranch===i.integration.targetBranch);if(!n)throw new Error(`Native Supervisor target branch worktree is unavailable: ${i.integration.targetBranch}`);if(!Cs(n))throw new Error(`Native Supervisor target worktree is not clean: ${n}`);let a=Ce(n,["rev-parse","HEAD"]);if((()=>{try{return Ce(n,["merge-base","--is-ancestor",i.integration.headCommit,a]),!0}catch{return!1}})()){let v=await NS({paths:e.paths,state:i,targetCommit:a});if(await bS({paths:e.paths,plan:v}),i.children.every(({status:p})=>p==="archived"))return await rm(e.paths,i.parent),{state:i,targetRoot:n,targetCommit:a};let m=xs(i);for(let p of m.children)p.status="archived";return m.stateVersion+=1,await kn(e.paths,m),await rm(e.paths,i.parent),{state:m,targetRoot:n,targetCommit:a}}let c=$u(i);if(c!==i.integration.headCommit)throw new Error("Native Supervisor integration head changed after final verification");let l=Ai(e.paths.projectRoot,i.integration.targetBranch),u=(()=>{if(!l)return!1;try{return Ce(i.integration.worktree,["merge-base","--is-ancestor",l,c]),!0}catch{return!1}})();if(l!==c&&!u&&l!==i.integration.targetCommit&&await kD({paths:e.paths,state:i}))throw new Error("Native Supervisor target changed; parent integration checks must be rerun before delivery");let d=await NS({paths:e.paths,state:i,targetCommit:c});l!==c&&Ce(n,["merge","--ff-only",i.integration.branch]);let f=Ce(n,["rev-parse","HEAD"]);if(f!==c)throw new Error("Native Supervisor target did not receive the verified integration head");let h=xs(i);for(let v of h.children)v.status="archived";return await bS({paths:e.paths,plan:d}),h.stateVersion+=1,await kn(e.paths,h),await rm(e.paths,i.parent),{state:h,targetRoot:n,targetCommit:f}}function xS(e,t){return Me.join(kS(e,t),"cleanup.json")}function yS(e){let t=Jt(e.paths.projectRoot).map(s=>Me.resolve(s)),i=Me.resolve(process.cwd()),r=[{root:e.state.integration.worktree,branch:e.state.integration.branch},...e.state.children.map(({name:s})=>({root:bD(e.paths.projectRoot,e.state.parent,s),branch:`comet/supervisor/${e.state.parent}/${s}`}))].map(s=>({...s,root:Me.resolve(s.root)})),n=e.targetCommit,a=[e.state.integration.branch,...e.state.children.map(({name:s})=>`comet/supervisor/${e.state.parent}/${s}`)],o=r.flatMap(s=>{let c=t.find(l=>l===s.root);return c?[{...s,root:c}]:[]});for(let s of o){if(yD(s.root,i))throw new Error(`Native Supervisor cannot clean the current worktree: ${s.root}`);if(!Cs(s.root))throw new Error(`Native Supervisor cleanup requires a clean worktree: ${s.root}`);let c=fe(s.root).currentBranch;if(!c)throw new Error(`Native Supervisor worktree is detached: ${s.root}`);if(c!==s.branch)throw new Error(`Native Supervisor cleanup found unexpected branch ${c} for ${s.root}; expected ${s.branch}`);try{Ce(e.paths.projectRoot,["merge-base","--is-ancestor",c,n])}catch{throw new Error(`Native Supervisor cleanup found unintegrated branch ${c}`)}}for(let s of a)if(Co(e.paths.projectRoot,s))try{Ce(e.paths.projectRoot,["merge-base","--is-ancestor",s,n])}catch{throw new Error(`Native Supervisor cleanup found unintegrated branch ${s}`)}return{parent:e.state.parent,targetCommit:e.targetCommit,worktrees:o.map(({root:s})=>s),expectedBranches:Object.fromEntries(o.map(({root:s,branch:c})=>[s,c])),branches:a}}async function NS(e){let t=xS(e.paths,e.state.parent);try{let r=JSON.parse(await ju.readFile(t,"utf8"));if(r.parent===e.state.parent&&r.targetCommit===e.targetCommit&&Array.isArray(r.worktrees)&&r.expectedBranches&&typeof r.expectedBranches=="object"&&Array.isArray(r.branches)){let n=yS(e);return{parent:r.parent,targetCommit:r.targetCommit,worktrees:[...new Set([...r.worktrees,...n.worktrees])],expectedBranches:{...r.expectedBranches,...n.expectedBranches},branches:[...new Set([...r.branches,...n.branches])]}}}catch(r){if(r.code!=="ENOENT")throw r}let i=yS(e);return await ee(t,i,{containedRoot:e.paths.changesRuntimeDir}),i}async function bS(e){for(let t of e.plan.worktrees){if(!Jt(e.paths.projectRoot).map(a=>Me.resolve(a)).includes(Me.resolve(t)))continue;let r=e.plan.expectedBranches[t];if(!r)throw new Error(`Native Supervisor cleanup has no expected branch for ${t}`);let n=fe(t).currentBranch;if(n!==r)throw new Error(`Native Supervisor cleanup found unexpected branch ${n??"(detached)"} for ${t}; expected ${r}`);Ce(e.paths.projectRoot,["worktree","remove",t])}for(let t of e.plan.branches)Co(e.paths.projectRoot,t)&&Ce(e.paths.projectRoot,["branch","-d",t])}async function rm(e,t){await ju.rm(xS(e,t),{force:!0})}function AS(e){let t=e.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.dependsOn],covers:[],status:i.status,phase:null,projectRoot:i.projectRoot??i.task?.projectRoot??null,message:i.blocker}));return{contractHash:null,confirmed:!0,parentBranch:e.integration.branch,children:t,readyChildren:t.filter(({status:i})=>i==="ready").map(({name:i})=>i),allDone:t.every(({status:i})=>i==="integrated"||i==="archived")}}var _S="children.yaml",_s="comet.native.children.v1",Ma="comet.native.children.v2",LS=Ma,ED=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,TS=new Set(["schema","children"]),PD=new Set(["schema","acceptance_index","children"]),RD=new Set(["name","depends_on","covers"]),CD=new Set(["name","summary","depends_on"]),xD=new Set(["name","depends_on","covers"]);function Hu(e,t,i=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${i}`);return e}function Ou(e,t,i){let r=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(r.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...r.length>0?[`unexpected ${r.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${i} fields are invalid: ${a.join("; ")}`)}}function IS(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((i,r)=>i.localeCompare(r,"en"))}function sm(e,t){let i=Dt.normalize(Dt.resolve(e)),r=Dt.normalize(Dt.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function AD(e){let t=new Map(e.map(a=>[a.name,a])),i=new Set,r=new Set,n=a=>{if(!r.has(a)){if(i.has(a))throw new Error(`Native children dependency cycle includes ${a}`);i.add(a);for(let o of t.get(a).depends_on)n(o);i.delete(a),r.add(a)}};for(let a of e)n(a.name)}function jS(e,t,i=t){let r=new Set(t);for(let o of e){let s=o.covers.filter(c=>!r.has(c));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=i.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function _D(e,t,i){let r={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===LS&&e.acceptance_index){let n=i.requiredAcceptanceIds??t??[],a=i.allowedAcceptanceIds??n,o=Object.keys(e.acceptance_index);r.missing=n.filter(l=>!(l in e.acceptance_index)),r.extra=o.filter(l=>!a.includes(l));let s=new Map((i.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of o){let u=s.get(l),d=e.acceptance_index[l];u&&d&&(d.source!==u.source||d.text!==u.text)&&r.mismatched.push(l)}let c=new Set(o);for(let l of e.children)r.unknownCovers.push(...l.covers.filter(u=>!c.has(u)));return r.uncovered=o.filter(l=>!$S(e.children,l)),OS(r)?r:null}if(e.schema===_s&&t){let n=new Set(t);for(let a of e.children)r.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return r.uncovered=t.filter(a=>!$S(e.children,a)),OS(r)?r:null}return null}function $S(e,t){return e.some(i=>i.covers.includes(t))}function OS(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function lm(e){let t=new Set(e.acceptance.map(({id:n})=>n)),i=new Set(e.acceptance.filter(({source:n})=>n===e.brief).map(({id:n})=>n)),r=new Set(i);for(let n of e.history.filter(({outcome:a})=>a==="fail"))for(let a of n.unresolved_ids)t.has(a)&&r.add(a);if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let n=[...e.history].reverse().find(({outcome:a})=>a==="fail");for(let a of n?.unresolved_ids??[])i.add(a)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...i],allowedAcceptanceIds:[...r]}}function TD(e){let t=Hu(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),i={};for(let[r,n]of Object.entries(t)){let a=Hu(n,`Native children acceptance_index.${r}`);if(Ou(a,new Set(["source","text"]),`Native children acceptance_index.${r}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${r}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${r}.text must be a non-empty string`);i[r]={source:a.source,text:a.text}}return i}function ID(e,t,i){let r=i.requiredAcceptanceIds??t??[],n=i.allowedAcceptanceIds??r,a=Object.keys(e),o=r.filter(l=>!(l in e)),s=a.filter(l=>!n.includes(l));if(o.length>0||s.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${o.join(", ")||"none"}; extra ${s.join(", ")||"none"}`);let c=new Map((i.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of a){let u=c.get(l);if(!u)continue;let d=e[l];if(d.source!==u.source||d.text!==u.text){let f=["source","text"].filter(h=>d[h]!==u[h]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${f.join(", ")} exactly from the current acceptance catalog`)}}}function jD(e,t,i={}){let r=(0,cm.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${r.errors[0].message}`);let n=Hu(r.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==_s&&a!==Ma)throw Ou(n,TS,"Native children contract"),new Error(`Native children schema must be ${_s} or ${Ma}`);let o=a===_s?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(Ou(n,o==="indexed-v2"?PD:TS,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let c=n.children.map((f,h)=>{let v=Hu(f,`Native child ${h}`);if(Ou(v,o==="indexed-v2"?xD:o==="summary-v2"?CD:RD,`Native ${s} child fields (child ${h})`),typeof v.name!="string"||!ED.test(v.name))throw new Error(`Native child ${h} name is invalid`);let m=o==="summary-v2";if(m){if(typeof v.summary!="string"||v.summary.trim().length===0)throw new Error(`Native child ${v.name} summary must be a non-empty string`);if(v.summary.length>2e3)throw new Error(`Native child ${v.name} summary exceeds 2000 characters`)}return{name:v.name,summary:m?v.summary:null,depends_on:IS(v.depends_on,`Native child ${v.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?IS(v.covers,`Native child ${v.name} covers`):[]}}),l=c.map(({name:f})=>f);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let u=new Set(l);for(let f of c){let h=f.depends_on.filter(v=>!u.has(v));if(h.length>0)throw new Error(`Native child ${f.name} depends on unknown child: ${h.join(", ")}`)}AD(c);let d=i.policy==="advisory";if(a===LS){if(o==="indexed-v2"){let f=TD(n.acceptance_index);d||ID(f,t,i);let h=Object.keys(f);return d||jS(c,h,h),{schema:Ma,acceptance_index:f,children:c}}return{schema:Ma,children:c}}return t&&!d&&jS(c,t),{schema:_s,children:c}}async function um(e){let t=Dt.join(e.changeDir,_S);try{await DS.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let i=await Z({root:e.changeDir,ref:_S}),r=e.policy==="advisory",n=r?{...e.validation,policy:"advisory"}:e.validation??{},a=jD(i.text,e.acceptanceIds,n);return{contract:a,size:i.size,drift:r?_D(a,e.acceptanceIds,e.validation??{}):null}}function $D(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let i=e.slice(t.index+t[0].length);return i.split(/^#\s+/mu,1)[0]??i}function OD(e){let t=$D(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let i=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),r=t.match(/\bChild\s+\d+\b/giu);return Math.max(i?.length??0,r?.length??0)>=2}async function MS(e){try{let t=await Z({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return OD(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function dm(e){return D("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:i,text:r})=>({id:t,source:i,text:r})),children:e.children})}async function HD(e){let t=Jt(e.projectRoot);t.some(r=>sm(r,e.projectRoot))||t.push(e.projectRoot);let i=[];for(let r of[...new Set(t.map(n=>Dt.resolve(n)))]){let n=await ye(r);n&&i.push({projectRoot:r,paths:await qe(r,n.native.artifact_root),parent:sm(r,e.projectRoot)})}return i.some(({parent:r})=>r)||i.push({projectRoot:e.projectRoot,paths:e,parent:!0}),i}async function DD(e,t){let i=Dt.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Ze(i)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function LD(e,t){let i;try{i=await DS.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[];for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=Dt.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await Ze(o);t.has(s.name)&&r.push({file:o,state:s})}catch{}return r}function MD(e,t,i){let r=Dt.relative(e.projectRoot,t);if(!r||r===".."||r.startsWith(`..${Dt.sep}`))return null;let n=r.split(Dt.sep).join("/");try{let a=(0,cm.parseDocument)(Ce(e.projectRoot,["show",`${i}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:ct(a.toJS({mapAsMap:!1}))}catch{return null}}function FD(e,t,i){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==i||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${i??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function HS(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Ts(e){let t=Dt.join(e.paths.changesDir,e.state.name),i=await MS(t),r=await um({changeDir:t,validation:lm(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:p})=>p)}:{},policy:"advisory"});if(!r)return e.state.children_contract_hash?{...i?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:i?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null;let n=dm({acceptance:e.state.acceptance,children:r.contract}),a=e.state.workspace.change_branch,o=e.state.phase!=="shape"&&e.state.children_contract_hash===n&&!r.drift;if(r.contract.schema===Ma){let p=await Ei(e.paths,e.state.name);if(!p){let y=e.state.workspace.target_branch??e.state.workspace.change_branch;if(y){let E=await om({paths:e.paths,parent:e.state.name,targetBranch:y,contract:r.contract});E&&(p=E,await kn(e.paths,E))}}if(p){let y=AS(p);return e.state.children_contract_hash!==n||r.drift?{...y,schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:!1,readyChildren:[],allDone:!1,children:y.children.map(E=>({...E,message:r.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...y,schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o}}let b=new Map(r.contract.children.map(y=>[y.name,y])),g=r.contract.children.map(y=>({name:y.name,summary:y.summary,dependsOn:[...y.depends_on],covers:[],status:o&&y.depends_on.every(E=>r.contract.children.filter(({name:k})=>k!==y.name).every(({name:k})=>k!==E))?"ready":"pending",phase:null,projectRoot:null,message:o?null:"Parent Shape confirmation is required"}));for(let y of g){if(y.status!=="ready")continue;b.get(y.name).depends_on.length>0&&(y.status="pending")}return{schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:g,readyChildren:g.filter(({status:y})=>y==="ready").map(({name:y})=>y),allDone:!1}}let s=await HD(e.paths),c=new Set(r.contract.children.map(({name:p})=>p)),l=new Map,u=new Map;for(let p of s){let b=p.parent&&a?`refs/heads/${a}`:"HEAD";for(let g of await LD(p,c)){let y={...g,source:p,committedState:MD(p,g.file,b)};l.set(g.state.name,[...l.get(g.state.name)??[],y])}for(let g of c){let y=await DD(p,g);y&&u.set(g,[...u.get(g)??[],{source:p,state:y}])}}let d=new Map;for(let p of r.contract.children){let b=(l.get(p.name)??[]).find(({source:E,committedState:k})=>E.parent&&k?.name===p.name&&HS(k,a));if(b){d.set(p.name,{kind:"done",phase:b.state.phase,projectRoot:b.source.projectRoot,message:null});continue}let g=l.get(p.name)?.[0];if(g){d.set(p.name,{kind:"blocked",phase:g.state.phase,projectRoot:g.source.projectRoot,message:`Native child ${p.name} is archived but not merged into parent branch ${a??"(missing)"}`});continue}let y=u.get(p.name)??[];y.length>1?d.set(p.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${p.name} has multiple active workspace owners`}):y[0]&&d.set(p.name,FD(y[0].state,y[0].source,a))}let f=new Map(r.contract.children.map(p=>[p.name,p])),h=new Map,v=p=>{let b=h.get(p);if(b)return b;let g=f.get(p),E=g.depends_on.map(v).every(({status:P})=>P==="done"),k=d.get(p),S=k?.kind==="active"&&E?g.depends_on.filter(P=>!(l.get(P)??[]).some(({source:F,committedState:$})=>sm(F.projectRoot,k.projectRoot)&&$?.name===P&&HS($,a))):[],R,N=k?.message??null;k?.kind==="done"?(R=E?"done":"blocked",E||(N=`Native child ${p} was merged before its dependencies`)):k?.kind==="active"?(R=E&&S.length===0?"active":"blocked",E?S.length>0&&(N=`Native child ${p} does not include merged dependencies: ${S.join(", ")}`):N=`Native child ${p} started before its dependencies merged`):k?.kind==="blocked"?R="blocked":(R=o&&E?"ready":"pending",o||(N="Parent Shape confirmation is required"));let w={name:p,summary:g.summary,dependsOn:[...g.depends_on],covers:[...g.covers],status:R,phase:k?.phase??null,projectRoot:k?.projectRoot??null,message:N};return h.set(p,w),w},m=r.contract.children.map(({name:p})=>v(p));return{schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:m,readyChildren:m.filter(({status:p})=>p==="ready").map(({name:p})=>p),allDone:m.every(({status:p})=>p==="done")}}var Is="skill-coordinated";function VD(e){return e.state_version+1}function qD(e){return e.map(t=>({...t,result:"pending",reason:null}))}function WD(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:Ii(e.summary),completed_at:e.completedAt}}function fm(e){let t=ct(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let i=(e.now??new Date).toISOString(),r=on(t,WD({state:t,outcome:"recovery",summary:e.reason,completedAt:i})),n=new Set(t.loop.previous_unresolved_ids),a=n.size===0?qD(t.acceptance):t.acceptance.map(o=>n.has(o.id)?{...o,result:"pending",reason:null}:o);return ct({...r,phase:"build",status:"active",state_version:VD(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 BS}from"node:fs";import js from"node:path";function Du(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Lu(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Pi(e,t,i=!1){if(typeof e!="string"||!i&&e.length===0)throw new Error(`${t} must be ${i?"a string":"a non-empty string"}`);return e}function FS(e,t){return e===null?null:Pi(e,t)}function Fu(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function zD(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 JD(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Mu(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function hm(e,t){if(e===null)return null;let i=Pi(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO timestamp`);return i}function pm(e,t){let i=Pi(e,t);if(!js.isAbsolute(i))throw new Error(`${t} must be absolute`);return js.resolve(i)}function GD(e,t){let i=`Native local checks[${t}]`,r=Du(e,i);if(Lu(r,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),i),!Array.isArray(r.argv)||r.argv.length===0)throw new Error(`${i}.argv must be a non-empty array`);let n=r.argv.map((l,u)=>Pi(l,`${i}.argv[${u}]`,!0)),a=Mu(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=hm(r.startedAt,`${i}.startedAt`),s=hm(r.completedAt,`${i}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${i} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${i} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${i} completed check requires startedAt and completedAt`);let c=Fu(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:Pi(r.id,`${i}.id`),name:Pi(r.name,`${i}.name`),operationId:Pi(r.operationId,`${i}.operationId`),status:a,repeatable:JD(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:Fu(r.executionCount,`${i}.executionCount`),argv:n,cwd:pm(r.cwd,`${i}.cwd`),exitCode:zD(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:Pi(r.log,`${i}.log`)}}function mm(e){let t="Native local execution state",i=Du(e,t);if(Lu(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),i.schema!==Vo)throw new Error(`Native local execution schema must be ${Vo}`);let r=Du(i.workspace,"Native local workspace");Lu(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=Du(i.execution,"Native local execution");Lu(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=hm(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Pi(o.operationId,"Native local execution.operationId"),stage:Mu(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Mu(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:FS(o.executionId,"Native local execution.executionId"),status:Mu(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Fu(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(i.checks))throw new Error("Native local checks must be an array");let a=i.checks.map(GD);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:Vo,change:Pi(i.change,"Native local change"),basedOnStateVersion:Fu(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:pm(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:pm(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:FS(r.branch,"Native local workspace.branch")},execution:n,checks:a}}function Br(e){return mm({schema:Vo,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:js.resolve(e.projectRoot),worktreeRoot:js.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function Bu(e){let t;try{t=await BS.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}let i;try{i=JSON.parse(t)}catch(r){throw new Error(`Native local execution state is invalid JSON: ${r.message}`,{cause:r})}return mm(i)}async function qi(e,t,i={}){let r=mm(t);await BS.mkdir(js.dirname(e),{recursive:!0}),await ee(e,r,i)}import{promises as UD}from"node:fs";function Vr(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
206
+ `).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function Wi(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function KD(e){return e.archived?qt(e.language,"Archived","已归档"):e.phase==="verify"&&e.loop.next_action==="confirm-skill-coordinated-pass"?qt(e.language,"Verification passed; your confirmation is required","验收通过,需要你确认"):e.phase==="archive"&&e.loop.next_action==="archive"?qt(e.language,"Verification passed; ready to archive","验收通过,可归档"):qt(e.language,"Verification passed","验收通过")}function YD(e){let t=e.language;return e.verification?.assurance==="semantic-verification-unavailable"?qt(t,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查"):e.verification_result==="pass"?KD(e):e.verification_result==="blocked"?qt(t,"Blocked","已阻塞"):e.verification_result==="fail"?qt(t,"Failed","未通过"):qt(t,"Pending","待处理")}function XD(e){let t=e.verification?.assurance??(e.builder_handoff?.identity_provider===Is?Is:"host-attested"),i=t===Is&&(e.archived||e.phase==="archive"&&e.loop.next_action==="archive");return(e.language==="en"?{"host-attested":"Host independently verified","skill-coordinated":i?"Checks completed; result confirmed":"Checks completed, but your confirmation is required","semantic-verification-unavailable":"Full verification was unavailable; only automatic checks completed","user-confirmed-degraded":"You accepted the incomplete verification result"}:{"host-attested":"已完成独立验证","skill-coordinated":i?"已完成检查,验证结果已确认":"已完成检查,但需要你确认验证结果","semantic-verification-unavailable":"无法完成完整验证,只完成了自动检查","user-confirmed-degraded":"你已确认接受不完整验证结果"})[t]??t}function QD(e,t){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let i=e.language,r=d=>gd(i,d),n=(d,f)=>qt(i,d,f),a=e.acceptance.map(d=>`| ${Wi(d.id)} | ${Wi(d.result)} | ${Wi(d.source)} | ${Wi(d.text)} | ${Wi(Vr(d.reason))} |`).join(`
207
+ `),o=e.verification.checks.length===0?`_${n("No Runtime checks were recorded.","没有记录 Runtime 检查。")}_`:[`| ${n("Check","检查")} | ${n("Command","命令")} | ${n("Working directory","工作目录")} | ${n("Status","状态")} | ${n("Exit","退出码")} | ${n("Duration","耗时")} |`,"| --- | --- | --- | --- | ---: | ---: |",...e.verification.checks.map(d=>{let f=d.argv_display.map(Vr).join(" ");return`| ${Wi(Vr(d.name))} | ${Wi(f||"—")} | ${Wi(d.cwd_ref)} | ${d.status} | ${d.exit_code??"—"} | ${d.duration_ms} ms |`})].join(`
208
+ `),s=e.blockers.length===0?`_${n("None.","无。")}_`:e.blockers.map(d=>`- **${d.owner}**: ${Vr(d.reason)}${d.acceptance_ids.length>0?` (acceptance: ${d.acceptance_ids.join(", ")})`:""} — next: \`${d.resolution_action}\``).join(`
209
+ `),c=e.verification.risks.length===0?`_${n("None reported.","未报告风险。")}_`:e.verification.risks.map(d=>`- ${Vr(d)}`).join(`
210
+ `),l=e.history.length===0?`_${n("No previous iterations.","没有之前的迭代。")}_`:[`| ${n("Goal cycle","目标周期")} | ${n("Iteration","迭代")} | ${n("Attempt","尝试")} | ${n("Outcome","结果")} | ${n("Unresolved","未解决项")} | ${n("Summary","摘要")} | ${n("Completed","完成时间")} |`,"| ---: | ---: | ---: | --- | --- | --- | --- |",...e.history.map(d=>`| ${d.goal_cycle} | ${d.iteration} | ${d.attempt} | ${d.outcome} | ${d.unresolved_ids.join(", ")||"—"} | ${Wi(Vr(d.summary))} | ${d.completed_at} |`)].join(`
211
211
  `),u=t?.finalVerification.layers?`
212
212
  ## ${n("Supervisor evidence layers","Supervisor 分层证据")}
213
213
 
@@ -224,13 +224,13 @@ generated_from_state_version: ${e.state_version}
224
224
 
225
225
  ## ${r("currentResult")}
226
226
 
227
- - ${n("Result","结果")}: **${qD(e)}**
228
- - ${n("Verification status","验证情况")}: **${WD(e)}**
227
+ - ${n("Result","结果")}: **${YD(e)}**
228
+ - ${n("Verification status","验证情况")}: **${XD(e)}**
229
229
  - ${n("Goal cycle","目标周期")}: ${e.loop.goal_cycle}
230
230
  - ${n("Iteration","迭代")}: ${e.verification.iteration}
231
231
  - ${n("Verifier attempt","验证器尝试次数")}: ${e.verification.attempt}
232
232
  - ${n("Completed","完成时间")}: ${e.verification.completed_at}
233
- - ${n("Summary","摘要")}: ${Br(e.verification.summary)}
233
+ - ${n("Summary","摘要")}: ${Vr(e.verification.summary)}
234
234
 
235
235
  ## ${r("acceptance")}
236
236
 
@@ -260,27 +260,27 @@ ${e.history_overflow.dropped_entries>0?`${n("Earlier history entries folded into
260
260
 
261
261
  `:""}## ${r("conclusion")}
262
262
 
263
- ${Br(e.verification.summary)}
264
- `}function JD(e){let t=/^---\r?\ngenerated_from_state_version: ([1-9]\d*)\r?\n---(?:\r?\n|$)/u.exec(e);if(!t)return null;let i=Number(t[1]);return Number.isSafeInteger(i)?i:null}async function Hu(e){let t;try{t=await BD.readFile(e.file,"utf8")}catch(r){if(r.code==="ENOENT")return"missing";throw r}let i=JD(t);return i===null?"invalid":i===e.stateVersion?"aligned":"stale"}async function Du(e){await he(e.file,zD(e.state,e.supervisor))}var BS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,GD="comet-state.yaml",UD="state.json",EY=Us("en");function Lt(e,t){if(!BS.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=Vr.join(e.changesDir,t);if(!O(e.changesDir,i))throw new Error("Native change path escaped");return i}function Pt(e,t){return Vr.join(Lt(e,t),GD)}function Nn(e,t){return Vr.join(We(e,t),UD)}async function qr(e,t){try{let i=await _s.readFile(Pt(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}function KD(e){return fe(e).currentBranch}async function $a(e,t){return Ze(Pt(e,t))}async function YD(e){let t=await nn({file:Pt(e.paths,e.previous.name),expectedStateVersion:e.previous.state_version,next:e.next,containedRoot:e.paths.nativeRoot});if(t.verification===null&&t.verification_report===null){let i=Vr.join(Lt(e.paths,t.name),"verification.md");await T(e.paths.nativeRoot,i),await _s.rm(i,{force:!0})}return t}async function XD(e){let t=Lt(e.paths,e.state.name),i=Vr.join(t,"specs"),r=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await _s.readdir(i,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,c)=>s.name.localeCompare(c.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!BS.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(r.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,c=Vr.join(t,...s.split("/")),l=await _s.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=Vr.join(e.paths.specsDir,o.name,"spec.md"),d="create";try{let f=await _s.lstat(u);if(!f.isFile()||f.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);d="modify"}catch(f){if(f.code!=="ENOENT")throw f}a.push({capability:o.name,operation:d,source:s})}return a.push(...r.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function QD(e){let t=Lt(e.paths,e.state.name),i=await Z({root:t,ref:"brief.md",maxBytes:null,includeHash:!1}),r=[];for(let n of e.specChanges){if(n.source===null)continue;let a=await Z({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}return hl({briefMarkdown:i.text,specs:r})}async function VS(e){let t=await XD(e),i=e.ignoreSpecOperationFor??(e.state.children_contract_hash?new Set(e.state.spec_changes.map(({capability:c})=>c)):void 0);if(!(t.length===e.state.spec_changes.length&&t.every((c,l)=>{let u=e.state.spec_changes[l];return u!==void 0&&c.capability===u.capability&&c.source===u.source&&(c.operation===u.operation||i?.has(c.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n=await QD({...e,specChanges:t}),a=e.state.acceptance.map(({source:c,text:l})=>({source:c,text:l}));if(!Oy(a,n))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let o;try{o=await cm({changeDir:Lt(e.paths,e.state.name),acceptanceIds:n.map(({id:c})=>c),validation:sm({...e.state,acceptance:n})})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return(o?lm({acceptance:n,children:o.contract}):null)===(e.state.children_contract_hash??null)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native child declarations changed"}}async function qS(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let r={...Yn(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:hr(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"confirm-shape"}};delete r.children_contract_hash;let n=await YD({paths:e.paths,previous:t,next:r});return await Fr(Nn(e.paths,t.name),yn({portableState:n,projectRoot:e.paths.projectRoot,branch:KD(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function Lu(e){if(e.state.verification===null)return"not-applicable";let t=Vr.join(Lt(e.paths,e.state.name),"verification.md");return await Hu({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await Du({file:t,state:e.state}),"rebuilt")}async function WS(e){let t=await $a(e.paths,e.name),i=Nn(e.paths,e.name);try{let r=await Ou(i);return r===null?{state:t,local:null,localStatus:"missing"}:r.change!==t.name||r.basedOnStateVersion!==t.state_version?{state:t,local:null,localStatus:"stale"}:{state:t,local:r,localStatus:"available"}}catch(r){return r.code==="ENOENT"?{state:t,local:null,localStatus:"missing"}:{state:t,local:null,localStatus:"invalid"}}}var IY=16*1024;async function Mu(e){let t=await Zp(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(Ul(t.selection.change),t.selection)}function zS(e){return Pu(e.projectRoot)}async function Ts(e,t){return await Wn(e.projectRoot),vS(e.projectRoot,"native",t)}var s4=16*1024*1024,Fu=class extends Error{constructor(i,r,n,a){super(`Canonical spec conflict for ${i}: expected ${r??"(missing)"}, actual ${n??"(missing)"}`);this.capability=i;this.expectedHash=r;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},Is=class extends Error{constructor(i,r=i.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${i.findingCodes.join(", ")}`){super(r);this.preflight=i;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};function GS(e,t){let i=t.operations.find(r=>r.id==="archive-change");if(!i||i.type!=="move")throw new Error(`Archive transaction ${t.id} has no archive move`);return Oa.resolve(e.nativeRoot,...i.target.split("/"))}async function US(e,t,i){let r=await Nr(e,t.id);if(r.some(p=>p.type==="archive-finalized"))return;let n=r.some(p=>p.type==="archive-finalization-started");if(t.schema==="comet.native.transaction.v2"&&!n){let p=t.operations.find(g=>g.id==="archive-change");if(!p||p.type!=="move"||!p.expectedSourceHash)throw new Error(`Archive transaction ${t.id} has no content-bound archive move`);let b=await ni(GS(e,t));if(b?.kind!=="directory"||b.hash!==p.expectedSourceHash)throw new Error(`Native Archive content changed before finalization for transaction ${t.id}`)}let a=GS(e,t),o=Oa.join(a,Te),s=await db(o);if(!t.change||s.name!==t.change)throw new Error(`Archive transaction ${t.id} change mismatch`);let c=H(e,s.name),l=await $e(c);if(!l||l.runId!==s.run_id||l.currentStep!=="archive"&&!(l.currentStep===null&&l.status==="completed"))throw new Error(`Native archive Run state is missing or inconsistent for ${s.name}`);let u=l;if(l.currentStep==="archive"){let p=Um(Ni,l,new Set,xp,void 0);if(!p.action)throw new Error(p.reason??"Native archive produced no action");u=Km(Ni,p.state,{actionId:p.action.id,status:"succeeded",summary:`Archived Native change ${s.name}`},xp,void 0)}let d=L(`archive:${t.id}:${s.name}`),f=await it(c,u.trajectoryRef),h=f.filter(p=>p.data.transactionId===t.id);if(t.schema==="comet.native.transaction.v2"&&(h.length>1||h.some(p=>p.type!=="state_transitioned")))throw new Error(`Native Archive trajectory has a transaction id collision: ${t.id}`);let v=h.find(p=>p.type==="state_transitioned"),m={previousPhase:"archive",nextPhase:null,evidenceHash:d,summary:`Archived Native change ${s.name}`,transactionId:t.id};if(v&&t.schema==="comet.native.transaction.v2"&&(!ZD(v.data,m)||v.runId!==u.runId||v.timestamp!==t.createdAt||v!==f.at(-1)))throw new Error(`Native Archive trajectory event changed for transaction ${t.id}`);if(!n&&(s.archived||l.currentStep===null||h.length>0))throw new Error(`Native Archive finalization state changed before its irreversible marker: ${t.id}`);if(n||(t.schema==="comet.native.transaction.v2"?(await Eu(e,t,"archive-finalization-started"),await i?.afterFinalizationStarted?.(t)):await ta(e,t,"archive-finalization-started")),!s.archived){let p={...s,archived:!0};await ub(o,p)}v||(v=await Tr({changeDir:c,run:u,type:"state_transitioned",data:m,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}})),await vn({changeDir:c,run:u,trajectoryOffset:v.sequence,evidenceHash:d,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}}),await un(c,u),await Ts(e,s.name),t.schema==="comet.native.transaction.v2"?await Eu(e,t,"archive-finalized"):await ta(e,t,"archive-finalized")}async function pm(e,t){let i=We(e,t);try{let r=await JS.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`Native Runtime cleanup target is not a real directory: ${i}`);return await T(e.runtimeDir,i),await JS.rm(i,{recursive:!0,force:!0}),null}catch(r){return r.code==="ENOENT"?null:`Archived change ${t}, but local Runtime cleanup failed: ${r.message}`}}async function eL(e,t,i){if(t.schema==="comet.native.transaction.v2"){if(!(await Nr(e,t.id)).some(c=>c.type==="operation-started")){let c=await Nu({paths:e,name:t.change,now:new Date(t.createdAt)});if(!c.ready||c.preflightHash!==t.preflightHash)throw new Is(c,"Native Archive facts changed before the first transaction operation")}let o=await fS(e,t,{...i,beforeArchiveChangeMove:async c=>{await i?.beforeArchiveChangeMove?.(c);let l=await He(e,t.change),u=await yu({paths:e,state:l,now:new Date(t.createdAt)});if(l.phase!=="archive"||l.archived||l.verification_result!=="pass"||!["complete","partial"].includes(u.freshness)||u.findingCodes.length>0)throw new Error(`Native Archive verification freshness changed before moving ${t.change}: ${u.findingCodes.join(", ")||u.freshness}`)}});await US(e,o,i);let s=await Eu(e,o,"commit");return{journal:s,runtimeCleanupWarning:await pm(e,s.change)}}let r=await oN(e,t);await US(e,r,i);let n=await ta(e,r,"commit");return{journal:n,runtimeCleanupWarning:n.change?await pm(e,n.change):null}}function tL(e,t){if(t.kind!=="archive")throw new Error(`Transaction ${t.id} is not an archive`);if(t.schema==="comet.native.transaction.v2"){if(!t.change)throw new Error(`Archive transaction ${t.id} has no change`);return}if(Oa.resolve(t.projectRoot)!==Oa.resolve(e.projectRoot)||Oa.resolve(t.nativeRoot)!==Oa.resolve(e.nativeRoot))throw new Error(`Transaction ${t.id} belongs to a different Native root`)}async function KS(e){return se(e.paths,`recover archive ${e.transactionId}`,async()=>{let t=await dr(e.paths,"archive",`recover archive ${e.transactionId}`);try{let i=await yt(e.paths,e.transactionId),r=i.schema==="comet.native.transaction.v2"?await Xp(e.paths,e.transactionId):i;return tL(e.paths,r),r.status==="committed"?(r.change&&await pm(e.paths,r.change),r):r.status==="rolled-back"?r:e.strategy==="continue"?(await eL(e.paths,r)).journal:r.schema==="comet.native.transaction.v2"?hS(e.paths,r):_l(e.paths,r)}finally{await fr(t)}},{allowedTransactionId:e.transactionId})}import{promises as vL}from"fs";async function YS(e,t){let i=[],r=H(e,t.name),n=lr(r,Nt.stateRef),a;try{a=await $e(r)}catch(u){return[{code:"run-state-invalid",message:`Native Run state is invalid: ${u.message}`,path:n}]}if(!a)return(t.run_id!==null||t.phase!=="shape")&&i.push({code:"run-state-missing",message:"Native change references a missing Run state",path:n}),i;if(t.run_id===null)return[{code:"run-state-unexpected",message:"Native change has a Run state but no run_id",path:n}];a.runId!==t.run_id&&i.push({code:"run-id-mismatch",message:`Native Run id ${a.runId} does not match change run_id ${t.run_id}`,path:n}),(a.pending||a.status==="waiting")&&i.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:n}),a.currentStep!==t.phase&&i.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:n});let o=lr(r,a.trajectoryRef),s=await la(e,t.name);if(s.status==="repairable")return i.push({code:"trajectory-tail-incomplete",message:`Native trajectory final line is incomplete at line ${s.line}; doctor repair can discard ${s.discardedBytes} incomplete byte(s)`,path:o}),i;if(s.status==="invalid")return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),i;let c;try{if(c=await it(r,a.trajectoryRef),c.length===0||c.some((u,d)=>!u||typeof u!="object"||u.sequence!==d+1||u.runId!==a.runId||typeof u.type!="string"||!u.data||typeof u.data!="object"||Array.isArray(u.data)))throw new Error("trajectory events are missing or inconsistent")}catch(u){return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),i}let l=lr(r,a.checkpointRef);try{let u=await ca(r,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&i.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):i.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){i.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return i}var iL=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function rL(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function nL(e){return e?e.map(rL).join(" "):null}function aL(e){if(e===null)return null;let t=e.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/gu);return!t||t[0]!=="comet"?null:t.map(i=>{if(i.startsWith('"')&&i.endsWith('"'))try{return JSON.parse(i)}catch{return i.slice(1,-1)}return i.startsWith("'")&&i.endsWith("'")?i.slice(1,-1):i})}function Mt(e,t,i,r={}){return{input:e,flags:t,required:r.required??!0,placeholder:i,...r.choices?{choices:r.choices}:{},...r.repeatable?{repeatable:!0}:{},...r.alternativeGroup?{alternativeGroup:r.alternativeGroup}:{}}}function oL(e){return e.map(t=>Mt(t,[],null))}function sL(e){let t=["comet","native","next",e.name,"--summary","<summary>"],i=[Mt("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),i.push(Mt("shared-understanding-confirmation",["--confirmed"],null)),{commandArgs:t,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:i};if(e.phase==="build"){t.push("--artifact","<project-relative-path>"),i.push(Mt("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),Mt("artifact-or-no-code-reason",["--no-code-reason"],"<reason>",{alternativeGroup:"build-evidence"}));let r=["summary","artifact-or-no-code-reason"];return e.approval!=="confirmed"&&(t.push("--confirmed"),r.push("shared-understanding-confirmation"),i.push(Mt("shared-understanding-confirmation",["--confirmed"],null))),{commandArgs:t,requiredInputs:r,inputOptions:i}}return e.phase==="verify"?(t.push("--result","<pass|fail>","--report","<change-relative-path>"),i.push(Mt("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),Mt("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:i}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function Ke(e,t){let i=t.commandArgs===void 0?aL(t.command??null):t.commandArgs;return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.name,phase:e.phase,revision:e.revision,disposition:t.disposition,action:t.action,command:t.command===void 0?nL(i??null):t.command,commandArgs:i??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??oL(t.requiredInputs??[])}}function Bu(e){let i=(e.findings??[]).filter(d=>!ua(d.code)),r=i.find(d=>d.requiresUserDecision),n=i.find(d=>d.repairCommand!==null||iL.test(d.code)),a=i.find(d=>d.code==="repair-iteration-limit"||d.code==="repair-override-exhausted"),o=i.find(d=>d.code==="repair-stagnation-stop"),s=i.find(d=>d.requiredAction==="return-to-bound-working-directory"||d.requiredAction==="repair-workspace-binding"),c=i.find(d=>d.code==="runtime-missing"),l=[...new Set(i.map(d=>d.requiredAction))].sort();if(e.done)return Ke(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return Ke(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[Mt("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(r)return Ke(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return Ke(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return Ke(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return Ke(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[Mt("summary",["--summary"],"<summary>")]});if(n)return Ke(e.state,{disposition:"blocked",action:"repair",command:n.repairCommand,requiredInputs:l});if(e.evidenceRetreat){let d=["comet","native","next",e.state.name,"--summary","<summary>"];return Ke(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[Mt("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return Ke(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(i.length>0)return e.state.phase==="archive"?Ke(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?Ke(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):Ke(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:l});if(e.state.phase==="archive"){if(e.archiveReady&&e.archivePreflightHash){if(!/^[a-f0-9]{64}$/u.test(e.archivePreflightHash))throw new Error("Native Archive continuation preflight must be a SHA-256 hash");let d=["comet","native","archive",e.state.name,"--expect-preflight",e.archivePreflightHash];return e.archiveConfirmation==="required"?(d.push("--confirmed"),Ke(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[Mt("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):Ke(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return Ke(e.state,{disposition:e.archiveReady?"continue":"blocked",action:e.archiveReady?"archive":"none",commandArgs:e.archiveReady?["comet","native","archive",e.state.name,"--dry-run"]:null,requiredInputs:e.archiveReady?[]:["archive-readiness"]})}let u=sL(e.state);return Ke(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import js from"path";var XS=8,cL={"runtime-missing":{severity:"warning",requiredAction:"rebuild-native-runtime",retry:"next",repair:"none"},"runtime-layout-legacy":{severity:"warning",requiredAction:"migrate-native-runtime-layout",retry:"status",repair:"doctor"},"runtime-storage-invalid":{severity:"error",requiredAction:"repair-native-runtime-storage",retry:"status",repair:"doctor"},"brief-blocking-question":{severity:"error",requiredAction:"answer-blocking-question",retry:"next",repair:"none"},"shape-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"approval-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"transition-incomplete":{severity:"error",requiredAction:"recover-transition",retry:"status",repair:"doctor"},"trajectory-tail-incomplete":{severity:"error",requiredAction:"repair-trajectory-tail",retry:"status",repair:"doctor"},"checkpoint-progress-invalid":{severity:"error",requiredAction:"manually-isolate-invalid-checkpoint",retry:"none",repair:"none"},"checkpoint-progress-incomplete":{severity:"error",requiredAction:"recover-progress-checkpoint",retry:"status",repair:"doctor"},"checkpoint-manifest-invalid":{severity:"error",requiredAction:"record-checkpoint-again",retry:"status",repair:"none"},"verification-scope-partial":{severity:"error",requiredAction:"confirm-partial-verification-scope",retry:"next",repair:"none"},"verification-implementation-stale":{severity:"error",requiredAction:"return-to-build-and-refresh-implementation-scope",retry:"next",repair:"none"},"verification-receipt-binding-mismatch":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-stale":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-invalid":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"native-change-conflict":{severity:"error",requiredAction:"resolve-native-change-conflict",retry:"status",repair:"none"},"native-change-overlap":{severity:"error",requiredAction:"inspect-native-change-overlap",retry:"status",repair:"none"},"contract-changed-after-approval":{severity:"error",requiredAction:"re-confirm-contract",retry:"next",repair:"none"},"baseline-snapshot-incomplete":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"baseline-snapshot-missing":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"workspace-inspection-unavailable":{severity:"info",requiredAction:"migrate-workspace-identity",retry:"status",repair:"doctor"},"workspace-binding-root-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-binding-invalid":{severity:"error",requiredAction:"repair-workspace-binding",retry:"status",repair:"none"},"workspace-branch-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-kind-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-vcs-unavailable":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"repair-stagnation-warning":{severity:"warning",requiredAction:"change-repair-approach",retry:"next",repair:"none"},"repair-stagnation-stop":{severity:"error",requiredAction:"try-new-repair-hypothesis-with-status-override",retry:"none",repair:"none"},"repair-iteration-limit":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"},"repair-override-exhausted":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"}};function lL(e){let t=cL[e];return t||(/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid)|transition-invalid)/u.test(e)?{severity:"error",requiredAction:"isolate-or-restore-native-runtime-from-a-trusted-copy",retry:"none",repair:"none"}:e.startsWith("brief-")?{severity:"error",requiredAction:"complete-brief",retry:"next",repair:"none"}:e.startsWith("spec-")?{severity:"error",requiredAction:"resolve-spec-state",retry:"next",repair:"none"}:e.startsWith("verification-")?{severity:"error",requiredAction:"complete-verification-evidence",retry:"next",repair:"none"}:e.startsWith("build-")?{severity:"error",requiredAction:"record-build-evidence",retry:"next",repair:"none"}:ua(e)?{severity:e==="workspace-inspection-unavailable"?"info":"warning",requiredAction:"inspect-workspace-advisory",retry:"status",repair:"none"}:{severity:"error",requiredAction:"resolve-finding",retry:"status",repair:"none"})}function uL(e,t,i){if(!i.path)return null;let r;if(js.isAbsolute(i.path)?r=js.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?r=js.resolve(ne(e,t.name),...i.path.split(/[\\/]/u)):r=js.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!O(e.projectRoot,r))return null;let n=js.relative(e.projectRoot,r).replaceAll("\\","/");return n===""?".":n}function dL(e,t,i){return e==="next"?`comet native next ${t.name} --summary "<summary>"${i==="contract-changed-after-approval"||i==="shape-confirmation-required"||i==="approval-confirmation-required"?" --confirmed":""}`:e==="status"?`comet native status ${t.name} --details`:null}function mm(e){return e.findings.map(t=>{let i=lL(t.code);return{code:t.code,message:t.message,severity:i.severity,path:uL(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:dL(i.retry,e.state,t.code),repairCommand:i.repair==="doctor"?`comet native doctor ${e.state.name} --repair${t.code.startsWith("transition-")?" --strategy continue":""}`:null,requiresUserDecision:t.code==="brief-blocking-question"||t.code==="shape-confirmation-required"||t.code==="approval-confirmation-required"||t.code==="contract-changed-after-approval"||t.code==="verification-scope-partial"||t.code==="repair-iteration-limit"||t.code==="repair-override-exhausted"}}).sort((t,i)=>{let r={error:0,warning:1,info:2};return r[t.severity]-r[i.severity]||t.code.localeCompare(i.code)||(t.path??"").localeCompare(i.path??"")||t.message.localeCompare(i.message)})}function vm(e){let t=[...new Set(e.map(i=>i.code))];return{total:e.length,errors:e.filter(i=>i.severity==="error").length,warnings:e.filter(i=>i.severity==="warning").length,info:e.filter(i=>i.severity==="info").length,requiresUserDecision:e.some(i=>i.requiresUserDecision),codes:t.slice(0,XS),truncated:t.length>XS}}var QS=240,ZS=8,Vu=50;function eE(e){let t=Array.from(e);return t.length<=QS?e:`${t.slice(0,QS-1).join("")}…`}function fL(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function hL(e){let t=[...new Set(e.map(fL))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,ZS),reasonCount:e.length,codesTruncated:t.length>ZS};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,Vu),reasonsTruncated:e.length>Vu}}}async function tE(e){let t=null;try{let s=await Or(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:$r(e.paths,e.state.name)})}catch(s){t={code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint journal aside before retrying`,path:$r(e.paths,e.state.name)}}let i=await qk({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),r=t?[t.code,...i.reasons]:i.reasons,n=hL(r);if(!i.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:jr.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:eE(i.checkpoint.summary),nextAction:eE(i.checkpoint.nextAction),artifactCount:i.checkpoint.artifactCount},o=i.manifest?{...a,summary:i.checkpoint.summary,nextAction:i.checkpoint.nextAction,manifestHash:i.checkpoint.manifestHash,manifestRef:i.checkpoint.manifestRef,artifacts:i.manifest.artifacts,totalBytes:i.manifest.totalBytes}:null;return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:jr.maxArtifacts}}async function pL(e,t){let i=H(e,t.name),r=await $e(i);if(!r||!t.run_id||r.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let n=await ca(i,r.checkpointRef);if(!n||n.runId!==r.runId||n.stateVersion!==r.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await it(i,r.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:r.runId}}async function mL(e,t){let i=await pL(e,t);return{committed:i,latest:yk(i),history:wk(i)}}async function iE(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let r=await mL(e,t),n=r.latest;if(!n)return null;let a=r.history.filter(c=>c.kind==="failure"),o=a.length>=i,s=n.disposition==="hard-stop"&&!o?"continue":n.disposition;return{disposition:o?"hard-stop":s,signatureHash:n.signatureHash,overrideRecorded:r.history.some(c=>c.kind==="override"&&c.signatureHash===n.signatureHash),failedAcceptanceIds:[...n.failedAcceptanceIds],failedCheckIds:[...n.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:i,remainingVerifyFailures:Math.max(0,i-a.length)}}var gL=/^native-status-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u,Ha=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function gm(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function wL(e){return(await Mu(e))?.change??null}function yL(e,t,i=!1,r){return Bu({state:e,archiveReady:t,evidenceRetreat:i}).command}async function NL(e,t){let i=ne(e,t.name),r=[...(await tp(i,t.brief)).findings,...(await vb(e,t)).findings,...await YS(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await sa(e,t.name);if(n===null)r.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await Dl(e,n);a.complete||r.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${a.omittedCount} omitted entries); resolve the omissions before advancing`})}}catch(n){r.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${n.message}`})}if(t.phase==="build")try{let n=await Ca({changeDir:i,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==n.contract.contractHash&&r.push({code:"contract-changed-after-approval",message:t.approval===null||t.approved_contract_hash===null||t.approved_contract_hash===void 0?"Native approval is not bound to a contract hash; re-confirm the current contract":"Native contract changed after approval; re-confirm the current contract"})}catch(n){r.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${n.message}`})}try{await Mi(e,t.name)&&r.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(n){r.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${n.message}`})}return t.verification_report?r.push(...(await ip(i,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&r.push({code:"verification-report-missing",message:"Native change has no verification report"}),r}async function wm(e,t,i){let r=await wL(e)===t,n=await jo(e,t),a=await QN(e,t),o;try{let w=await vi(e,t);if(w.status==="migration-required"&&w.state)return{name:t,phase:w.state.phase,revision:"revision"in w.state?w.state.revision:null,approval:w.state.approval,verificationResult:w.state.verification_result,specChanges:w.state.spec_changes.length,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["migration-required"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:w.schema,migrationRequired:!0,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message};if(w.status!=="current"||!w.state)return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["runtime-incompatible"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:w.schema,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message??`Native change ${t} is incompatible`};o=w.state}catch(w){return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["change-invalid"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,error:w.message}}if(n.status!=="available"){let w={code:n.status==="missing"?"runtime-missing":"runtime-storage-invalid",message:n.status==="missing"?`Native Runtime is missing; continue ${o.name} to rebuild local execution state`:n.message??"Native Runtime storage is invalid",path:n.path},P=mm({paths:e,state:o,findings:[w]}),F=Bu({state:o,findings:P});return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:F.command,archiveReady:!1,inspection:{freshness:"stale",codes:[w.code],reasonCount:1,codesTruncated:!1},findingSummary:vm(P),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:F,workspace:a,runtime:n,...i?.details?{findings:P}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:w.message}:{}}}let s=await tE({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await iE(e,o,i?.maxVerifyFailures??5),c&&(c.disposition==="manual-stop"||c.disposition==="hard-stop")){let w=c.disposition==="hard-stop"?"repair-iteration-limit":c.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";l.push({code:w,message:`Native repair is stopped at failure signature: ${c.signatureHash}`})}}catch{l.push({code:"trajectory-invalid",message:"Native repair history could not be reconstructed safely"})}let u;if(i?.details&&(o.phase==="build"||o.phase==="verify"||o.phase==="archive"))try{let w=await Ca({changeDir:ne(e,o.name),briefRef:o.brief,specChanges:o.spec_changes}),P=new Map;if(o.phase==="build"&&o.verification_result==="fail"&&o.verification_evidence){let Fe=await Pa(e,o.name,o.verification_evidence);for(let ue of Fe.acceptanceTrace.entries)P.set(ue.acceptanceId,ue.status==="failed"?"failed":ue.status==="missing"?"missing":"satisfied")}let F=xy({criteria:w.contract.acceptance,acceptanceHash:w.contract.acceptanceHash,verificationStatuses:P,failedCheckIds:c?.failedCheckIds??[],...i.acceptanceCursor?{cursor:i.acceptanceCursor}:{}}),$=F.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",F.nextCursor,"--project-root",e.projectRoot]:null;u={...F,...$?{nextPageCommand:gm($),nextPageArgs:$}:{}}}catch(w){if(i.acceptanceCursor)throw w;u=void 0}let d=[];if(i?.includeConflictFindings!==!1)try{let w=await cu(e,o.name,{tolerateInvalidSiblings:!0});d.push(...w.findingCodes.map(P=>({code:P,message:`Native change overlap is visible in the current root: ${P}`})))}catch{d.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let f=[];try{let w=await kt(e,o.name);if(w)if(w.schema==="comet.native.workspace.v3"){let P=await fa({paths:e,identity:w});P.state==="drifted"&&P.code&&f.push({code:P.code,message:P.message??"Native workspace binding is no longer valid"})}else{let P=await Qo({paths:e,identity:w});f.push(...P.findingCodes.map(F=>({code:F,message:`Native workspace advisory changed: ${F} (${P.driftComponents.join(", ")||"no-component"})`})))}}catch{f.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let h=[],v=!1;if(o.phase==="verify"){let w=await Qk({paths:e,state:o});v=w.freshness!=="fresh",h.push(...w.findingCodes.map(P=>({code:P,message:`Native Verify implementation scope is not current: ${P}`})))}let m=null,p=[];if(o.phase==="archive")try{m=await Nu({paths:e,name:o.name}),p.push(...m.findingCodes.map(w=>({code:w,message:`Native Archive is blocked: ${w}`})))}catch{p.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let b=[...await NL(e,o),...s.findings,...d,...f,...h,...l,...p].filter((w,P,F)=>F.findIndex($=>$.code===w.code&&$.path===w.path)===P),g=mm({paths:e,state:o,findings:b}),y=g.filter(w=>!ua(w.code)),E=o.phase==="archive"&&m?.ready===!0&&y.length===0,k=v||o.phase==="archive"&&(m?.findingCodes??[]).some(w=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(w)),S=g.some(w=>w.code==="trajectory-tail-incomplete"||w.code==="trajectory-invalid"||w.requiredAction==="return-to-bound-working-directory"||w.requiredAction==="repair-workspace-binding"),R=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",N=g.find(w=>w.severity==="error");return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:S||R?null:yL(o,E,k,i?.clarificationMode),archiveReady:E,inspection:s.inspection,findingSummary:vm(g),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:Bu({state:o,findings:g,archiveReady:E,evidenceRetreat:k,clarificationMode:i?.clarificationMode}),workspace:a,runtime:n,repair:c,...i?.details?{...u?{acceptancePage:u}:{},findings:g.slice(0,50),inspectionDetails:s.inspectionDetails,checkpointDetails:s.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:Vu,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:g.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...N?{error:N.message}:{}}}async function bL(e){let t;try{t=await Qt({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[],r=await vL.opendir(e.changesDir);try{for await(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink())&&(i.push(n.name),i.length>Ha.maxChanges))throw new Error(`Native status exceeds ${Ha.maxChanges} visible changes`)}finally{await r.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),i.sort()}function qu(e,t){let i=t.toString(36),r=D("comet.native.status-cursor.v1",{namesHash:e,offset:t});return`native-status-v1.${e}.${i}.${r}`}function kL(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=gL.exec(e.cursor);if(!t)throw new Error("Native status cursor is invalid");if(t[1]!==e.namesHash)throw new Error("Native status cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native status cursor offset is invalid");let r=D("comet.native.status-cursor.v1",{namesHash:e.namesHash,offset:i});if(t[3]!==r)throw new Error("Native status cursor integrity check failed");return i}async function SL(e,t){let i=await bL(e),r=D("comet.native.status-names.v1",i),n=kL({namesHash:r,total:i.length,cursor:t?.cursor}),a=await Promise.all(i.slice(n,n+Ha.maxItems).map(u=>wm(e,u,{includeConflictFindings:!1,clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures}))),o=[];for(let u of a){let d=[...o,u],f=n+d.length,h={schema:"comet.native.status-page.v1",total:i.length,offset:n,items:d,nextCursor:f<i.length?qu(r,f):null,nextPageCommand:f<i.length?gm(["comet","native","status","--cursor",qu(r,f)]):null,nextPageArgs:f<i.length?["comet","native","status","--cursor",qu(r,f)]:null,limits:{...Ha}};if(Buffer.byteLength(JSON.stringify(h),"utf8")>Ha.maxSerializedBytes){if(o.length===0)throw new Error("Native status item exceeds its page serialization budget");break}o.push(u)}let s=n+o.length,c=s<i.length?qu(r,s):null,l=c?["comet","native","status","--cursor",c]:null;return{schema:"comet.native.status-page.v1",total:i.length,offset:n,items:o,nextCursor:c,nextPageCommand:l?gm(l):null,nextPageArgs:l,limits:{...Ha}}}async function ym(e,t){return(await SL(e,{clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures})).items}import{createHash as VL,randomUUID as qL}from"node:crypto";import{constants as Em,promises as Q}from"node:fs";import le from"node:path";var Ju=Rn(Qr(),1);import{randomUUID as EL}from"crypto";import{promises as sE}from"fs";import bm from"path";import{isDeepStrictEqual as km}from"util";var bn=/^[a-f0-9]{64}$/u,PL=new Set(["schema","id","change","fromSchema","toSchema","sourceHash","targetHash","createdAt","nextState","transition","transitionSupersede","runRetreat"]),RL=new Set(["sourceHash","targetHash","nextJournal"]),CL=new Set(["sourceHash","transitionId","previousRun","nextRun","evidenceHash","eventData"]),rE=new Set(["fromSchema","toSchema","previousPhase","nextPhase","reason","supersededTransitionId"]),xL=new Set(["previousRun","nextRun","evidenceHash","eventData"]);function Wu(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function nE(e){return JSON.stringify(e,null,2)+`
265
- `}function Sm(e){return e.schema===be?Kl(e):dn(e)}function Nm(e,t){return{...e,schema:be,minimum_runtime_version:2,revision:t}}function AL(e){return{...e,schema:Ti,minimum_runtime_version:2,revision:1,previousState:Nm(e.previousState,1),nextState:Nm(e.nextState,2)}}function zu(e,t){let i=t?.retreatEvidencePhase===!0&&(e.phase==="verify"||e.phase==="archive");return{...e,schema:Ne,minimum_runtime_version:3,verification_protocol:"legacy-v1",revision:e.revision+(i&&t?.incrementRetreatRevision?1:0),phase:i?"build":e.phase,verification_result:i?"pending":e.verification_result,verification_report:i?null:e.verification_report,approved_contract_hash:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:i?!1:e.archived}}function _L(e){if(e.nextState.phase==="archive")throw new Error("Native v2 Archive transition must be superseded by schema migration");let t=e.previousState.phase!=="shape"&&e.nextState.phase==="build"&&e.eventData.verificationResult===null,i=t?L(JSON.stringify({operation:"spec-rebase",change:e.change,summary:e.eventData.summary,specChanges:e.nextState.spec_changes})):e.evidenceHash;return{...e,schema:pr,minimum_runtime_version:3,revision:1,operation:t?"spec-rebase":"advance",evidenceHash:i,previousState:zu(e.previousState),nextState:{...zu(e.nextState),...t?{implementation_scope:null,verification_evidence:null,partial_allowance:null}:{}},eventData:{...e.eventData,evidenceHash:i},nextRun:e.previousRun===null?{...e.nextRun,skillVersion:Ni.definition.metadata.version,skillHash:gs}:e.nextRun}}function aE(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Da(e,t){return JSON.stringify(Kl(e))===JSON.stringify(Kl(t))}function oE(e,t){return JSON.stringify(dn(e))===JSON.stringify(dn(t))}function Vi(e,t){return km(e,t)}function TL(e,t,i,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Schema migration transition supersede plan is invalid");let n=e;if(Wu(n,CL,"Schema migration transition supersede plan"),typeof n.sourceHash!="string"||!bn.test(n.sourceHash))throw new Error("Schema migration transition supersede source hash is invalid");if(typeof n.transitionId!="string"||n.transitionId.length===0)throw new Error("Schema migration superseded transition id is invalid");if(typeof n.evidenceHash!="string"||!bn.test(n.evidenceHash))throw new Error("Schema migration transition supersede evidence hash is invalid");let a=Er(n.previousRun),o=Er(n.nextRun);if(a.runId!==o.runId||i.run_id!==o.runId||i.phase!=="build"&&i.phase!=="verify"||o.currentStep!==i.phase||o.pending!==null||o.status!=="running"||i.verification_result!=="pending"||i.verification_report!==null||i.implementation_scope!==null||i.verification_evidence!==null||i.partial_allowance!==null)throw new Error("Schema migration transition supersede Run does not match target state");let s=a.currentStep==="verify"&&i.phase==="build"||a.currentStep==="archive"&&i.phase==="build",c=a.currentStep===i.phase?a:s?{...a,currentStep:i.phase,iteration:a.iteration+1,pending:null,status:"running"}:null;if(!c||!Vi(c,o))throw new Error("Schema migration transition supersede Run retreat is invalid");if(!n.eventData||typeof n.eventData!="object"||Array.isArray(n.eventData))throw new Error("Schema migration transition supersede event is invalid");let l=n.eventData,u=Object.keys(l);if(u.length!==rE.size||u.some(f=>!rE.has(f))||l.fromSchema!==be||l.toSchema!==Ne||!["build","verify","archive"].includes(l.previousPhase)||l.nextPhase!==i.phase||l.reason!==(i.phase==="build"?"implementation-scope-required":"verification-evidence-required")||l.supersededTransitionId!==n.transitionId)throw new Error("Schema migration transition supersede event semantics are invalid");if(i.name!==t)throw new Error("Schema migration transition supersede change mismatch");let d=L(JSON.stringify({operation:"supersede-v2-evidence-transition",change:t,transitionId:n.transitionId,migrationId:r,previousPhase:l.previousPhase,nextPhase:l.nextPhase,reason:l.reason,previousIteration:a.iteration,nextRevision:i.revision}));if(n.evidenceHash!==d)throw new Error("Schema migration transition supersede evidence hash mismatch");return{sourceHash:n.sourceHash,transitionId:n.transitionId,previousRun:a,nextRun:o,evidenceHash:n.evidenceHash,eventData:l}}function $s(e,t){return bm.join(H(e,t),"schema-migration.json")}function IL(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native schema migration journal must be an object");Wu(e,PL,"Native schema migration journal");let i=e;if(i.schema!=="comet.native.schema-migration.v1")throw new Error("Unsupported Native schema migration journal");if(i.change!==t)throw new Error("Schema migration change mismatch");let r=i.fromSchema===et&&i.toSchema===be,n=i.fromSchema===be&&i.toSchema===Ne;if(!r&&!n)throw new Error("Schema migration route is unsupported");if(typeof i.id!="string"||i.id.length===0)throw new Error("Schema migration id is invalid");if(typeof i.sourceHash!="string"||!bn.test(i.sourceHash)||typeof i.targetHash!="string"||!bn.test(i.targetHash))throw new Error("Schema migration hash is invalid");if(typeof i.createdAt!="string"||Number.isNaN(Date.parse(i.createdAt)))throw new Error("Schema migration timestamp is invalid");let a=r?di(i.nextState):lt(i.nextState);if(a.name!==t)throw new Error("Schema migration target state change mismatch");if(L((0,Ju.stringify)(Sm(a)))!==i.targetHash)throw new Error("Schema migration state target hash does not match its document");let o;if(i.transition!==void 0){if(!i.transition||typeof i.transition!="object")throw new Error("Schema migration transition target is invalid");Wu(i.transition,RL,"Schema migration transition target");let l=i.transition;if(typeof l.sourceHash!="string"||!bn.test(l.sourceHash)||typeof l.targetHash!="string"||!bn.test(l.targetHash))throw new Error("Schema migration transition hash is invalid");let u=r?Hp(l.nextJournal,t):Op(l.nextJournal,t);if(L(JSON.stringify(l.nextJournal,null,2)+`
266
- `)!==l.targetHash)throw new Error("Schema migration transition target hash does not match its journal");if(!(r&&a.schema===be?Da(a,u.previousState)||Da(a,u.nextState):a.schema===Ne&&(oE(a,u.previousState)||oE(a,u.nextState))))throw new Error("Schema migration state/transition target mismatch");o={sourceHash:l.sourceHash,targetHash:l.targetHash,nextJournal:l.nextJournal}}if(r&&(!o&&a.revision!==1||o&&a.revision!==1&&a.revision!==2))throw new Error("Schema migration v1 target revision is invalid");let s;if(i.transitionSupersede!==void 0){if(!n||o)throw new Error("Schema migration transition supersede plan is not valid for this route");if(a.schema!==Ne)throw new Error("Schema migration transition supersede target schema is invalid");s=TL(i.transitionSupersede,t,a,i.id)}let c;if(i.runRetreat!==void 0){if(!n||o||s)throw new Error("Schema migration Run retreat is not valid for this route");if(!i.runRetreat||typeof i.runRetreat!="object")throw new Error("Schema migration Run retreat is invalid");Wu(i.runRetreat,xL,"Schema migration Run retreat");let l=i.runRetreat,u,d;try{u=Er(l.previousRun),d=Er(l.nextRun)}catch(f){throw new Error("Schema migration Run retreat is invalid",{cause:f})}if(typeof l.evidenceHash!="string"||!bn.test(l.evidenceHash)||!l.eventData||typeof l.eventData!="object"||Array.isArray(l.eventData))throw new Error("Schema migration Run retreat is invalid");if(a.schema!==Ne||a.phase!=="build"||a.run_id!==d.runId||u.runId!==d.runId||u.currentStep!=="verify"&&u.currentStep!=="archive"||d.currentStep!=="build"||d.iteration!==u.iteration+1)throw new Error("Schema migration Run retreat does not match target state");c={previousRun:u,nextRun:d,evidenceHash:l.evidenceHash,eventData:l.eventData}}if(o&&c||s&&c)throw new Error("Schema migration has conflicting recovery plans");return{schema:"comet.native.schema-migration.v1",id:i.id,change:t,fromSchema:i.fromSchema,toSchema:i.toSchema,sourceHash:i.sourceHash,targetHash:i.targetHash,createdAt:i.createdAt,nextState:a,...o?{transition:o}:{},...s?{transitionSupersede:s}:{},...c?{runRetreat:c}:{}}}async function Os(e,t){let i=$s(e,t),r=j(e,i);await T(r,i);try{let n=await Sl({root:r,file:i,maxBytes:524288,label:"Native schema migration journal"});return IL(JSON.parse(n.text),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function jL(e,t,i){let r=await sa(e,t),n=r?await Dl(e,r):await Ll(e,{now:new Date(i),origin:"legacy-migration"});if(!n.complete){let a=Bh(n),o=n.omitted.reduce((c,l)=>(c[l.reason]=(c[l.reason]??0)+1,c),{}),s=n.omissionOverflow?.count??0;throw s>0&&(o.overflow=s),new ha(t,n.omittedCount,o,a.samplePaths,a.sampleTruncated)}r===null&&await Wh(e,t,n)}async function cE(e){try{return await Zt(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}function $L(e,t){let i=e.transitionSupersede;return{sequence:t,timestamp:e.createdAt,type:"state_migrated",runId:i.nextRun.runId,data:{...i.eventData,migrationId:e.id,evidenceHash:i.evidenceHash}}}async function lE(e,t){let i=t.transitionSupersede,r=H(e,t.change),n=await it(r,i.nextRun.trajectoryRef),a=n.map((s,c)=>({event:s,index:c})).filter(({event:s})=>s.data.migrationId===t.id);if(a.length>1)throw new Error(`Native schema migration event ${t.id} is duplicated`);let o=a[0];if(o&&!km(o.event,$L(t,o.index+1)))throw new Error(`Native schema migration event ${t.id} changed`);return{trajectoryLength:n.length,sequence:o?.event.sequence??null}}async function OL(e,t,i){if(!t.transitionSupersede)return;let r=Ue(e,t.change),n=await cE(r);if(n===t.transitionSupersede.sourceHash)return;if(n!==null)throw new Error(`Native superseded transition source changed for ${t.change}: expected ${t.transitionSupersede.sourceHash}, actual ${n}`);let a=H(e,t.change),o=await $e(a),s=await lE(e,t),c=await ca(a,t.transitionSupersede.nextRun.checkpointRef);if(!i||!o||!Vi(o,t.transitionSupersede.nextRun)||s.sequence===null||!c||c.runId!==t.transitionSupersede.nextRun.runId||c.stateVersion!==t.transitionSupersede.nextRun.iteration||c.trajectoryOffset!==s.sequence||c.contextHash!==null||c.artifactsHash!==L(t.transitionSupersede.evidenceHash)||c.createdAt!==t.createdAt)throw new Error(`Native superseded transition disappeared before migration ${t.id} was durable`)}async function HL(e,t,i){let r=t.transitionSupersede;if(!r)return;let n=H(e,t.change),a=await $e(n);if(!a)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!Vi(a,r.nextRun)){if(!Vi(a,r.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await un(n,r.nextRun),await i?.afterRunStateWritten?.(t)}if(!Vi(await $e(n),r.nextRun))throw new Error(`Native schema migration Run write diverged for ${t.change}`);let o=await lE(e,t);if(o.sequence===null){let l=await Tr({changeDir:n,run:r.nextRun,type:"state_migrated",data:{...r.eventData,migrationId:t.id,evidenceHash:r.evidenceHash},now:new Date(t.createdAt)});o={trajectoryLength:l.sequence,sequence:l.sequence}}await i?.afterTrajectoryWritten?.(t),await vn({changeDir:n,run:r.nextRun,trajectoryOffset:o.sequence,evidenceHash:r.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t);let s=Ue(e,t.change),c=await cE(s);if(c!==null){if(c!==r.sourceHash)throw new Error(`Native superseded transition changed before removal for ${t.change}`);await sE.rm(s),await i?.afterTransitionSuperseded?.(t)}}async function DL(e,t,i){if(!t.runRetreat)return;let r=H(e,t.change),n=await $e(r);if(!n)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!Vi(n,t.runRetreat.nextRun)){if(!Vi(n,t.runRetreat.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await un(r,t.runRetreat.nextRun),await i?.afterRunStateWritten?.(t)}let a=await it(r,t.runRetreat.nextRun.trajectoryRef),o=a.find(s=>s.type==="state_migrated"&&s.data.migrationId===t.id);o||(o=await Tr({changeDir:r,run:t.runRetreat.nextRun,type:"state_migrated",data:{...t.runRetreat.eventData,migrationId:t.id,evidenceHash:t.runRetreat.evidenceHash},now:new Date(t.createdAt)}),a=[...a,o]),await i?.afterTrajectoryWritten?.(t),await vn({changeDir:r,run:t.runRetreat.nextRun,trajectoryOffset:a.length,evidenceHash:t.runRetreat.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t)}async function LL(e,t,i){let r=await Os(e,t);if(!r)return null;if(await ma(e,t))throw new Error(`Native change ${t} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let n=bm.join(ne(e,t),Te),a=await Zt(n);if(await OL(e,r,a===r.targetHash),await jL(e,t,r.createdAt),a!==r.targetHash){if(a!==r.sourceHash)throw new Error(`Native schema migration source changed for ${t}: expected ${r.sourceHash}, actual ${a}`);await he(n,(0,Ju.stringify)(Sm(r.nextState))),await i?.afterStateWritten?.(r)}if(r.transition){let o=Ue(e,t),s=await Zt(o);if(s!==r.transition.targetHash){if(s!==r.transition.sourceHash)throw new Error(`Native transition migration source changed for ${t}: expected ${r.transition.sourceHash}, actual ${s}`);await ee(o,r.transition.nextJournal),await i?.afterTransitionWritten?.(r)}}return await HL(e,r,i),await DL(e,r,i),await sE.rm($s(e,t),{force:!0}),r.nextState}async function ML(e){let t=H(e.paths,e.state.name),i=await $e(t);if(!i||i.runId!==e.state.run_id||i.currentStep!==e.state.phase||i.currentStep!=="verify"&&i.currentStep!=="archive"||i.pending!==null)throw new Error(`Native v2 ${e.state.phase} change ${e.state.name} has no consistent Run state for safe Build retreat`);let r={...i,currentStep:"build",iteration:i.iteration+1,pending:null,status:"running"},n=L(`schema-v3-evidence-retreat:${e.state.name}:${e.state.revision}:${e.migrationId}`);return{previousRun:i,nextRun:r,evidenceHash:n,eventData:{fromSchema:be,toSchema:Ne,previousPhase:e.state.phase,nextPhase:"build",reason:"implementation-scope-required"}}}async function FL(e){let{journal:t,state:i}=e;if(!(t.previousState.phase==="build"&&t.nextState.phase==="verify"||t.previousState.phase==="verify"&&(t.nextState.phase==="build"||t.nextState.phase==="archive")))throw new Error("Only a pending v2 evidence-bearing transition can be superseded");let n=Da(i,t.previousState),a=Da(i,t.nextState);if(!n&&!a)throw new Error(`Native change ${i.name} does not match its v2 evidence transition`);let o=H(e.paths,i.name),s=await $e(o);if(!s)throw new Error(`Native v2 transition Run is missing for ${i.name}`);let c=t.previousRun!==null&&Vi(s,t.previousRun),l=Vi(s,t.nextRun);if(!c&&!l||a&&!l)throw new Error(`Native v2 transition Run does not match its durable state for ${i.name}`);let d=(await it(o,t.nextRun.trajectoryRef)).map((b,g)=>({event:b,index:g})).filter(({event:b})=>b.data.transitionId===t.id);if(d.length>1)throw new Error(`Native v2 evidence transition ${t.id} has duplicate trajectory events`);let f=d[0];if(f){let b={sequence:f.index+1,timestamp:t.createdAt,type:"state_transitioned",runId:t.nextRun.runId,data:{...t.eventData,transitionId:t.id}};if(!km(f.event,b)||!a||!l)throw new Error(`Native v2 evidence transition ${t.id} trajectory event does not match its journal`)}let h={...zu(i),revision:i.revision+(i.phase==="build"?0:1),phase:"build",verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:!1},v=s,m=s.currentStep!=="build"?{...s,currentStep:"build",iteration:s.iteration+1,pending:null,status:"running"}:s,p=L(JSON.stringify({operation:"supersede-v2-evidence-transition",change:i.name,transitionId:t.id,migrationId:e.migrationId,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",previousIteration:s.iteration,nextRevision:h.revision}));return{nextState:h,plan:{sourceHash:await Zt(Ue(e.paths,i.name)),transitionId:t.id,previousRun:v,nextRun:m,evidenceHash:p,eventData:{fromSchema:be,toSchema:Ne,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",supersededTransitionId:t.id}}}}async function BL(e){let t,i,r,n;if(e.state.schema===et){if(t=Nm(e.state,1),e.pendingTransition){if(e.pendingTransition.journal.schema!==an)throw new Error("Native v1 change has a transition from another schema generation");let s=AL(e.pendingTransition.journal);if(aE(e.state,e.pendingTransition.journal.previousState))t=s.previousState;else if(aE(e.state,e.pendingTransition.journal.nextState))t=s.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v1 transition journal`);let c=Ue(e.paths,e.name);i={sourceHash:await Zt(c),targetHash:L(nE(s)),nextJournal:s}}}else if(e.pendingTransition){if(e.pendingTransition.journal.schema!==Ti)throw new Error("Native v2 change has a transition from another schema generation");let s=e.pendingTransition.journal;if(s.previousState.phase==="build"&&s.nextState.phase==="verify"||s.previousState.phase==="verify"&&(s.nextState.phase==="build"||s.nextState.phase==="archive")){let l=await FL({paths:e.paths,state:e.state,journal:s,migrationId:e.id});t=l.nextState,r=l.plan}else{let l=_L(s);if(Da(e.state,e.pendingTransition.journal.previousState))t=l.previousState;else if(Da(e.state,e.pendingTransition.journal.nextState))t=l.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v2 transition journal`);let u=Ue(e.paths,e.name);i={sourceHash:await Zt(u),targetHash:L(nE(l)),nextJournal:l}}}else t=zu(e.state,{retreatEvidencePhase:!0,incrementRetreatRevision:!0}),(e.state.phase==="verify"||e.state.phase==="archive")&&(n=await ML({paths:e.paths,state:e.state,migrationId:e.id}));let a=bm.join(ne(e.paths,e.name),Te),o=(0,Ju.stringify)(Sm(t));return{schema:"comet.native.schema-migration.v1",id:e.id,change:e.name,fromSchema:e.state.schema,toSchema:e.state.schema===et?be:Ne,sourceHash:await Zt(a),targetHash:L(o),createdAt:e.now.toISOString(),nextState:t,...i?{transition:i}:{},...r?{transitionSupersede:r}:{},...n?{runRetreat:n}:{}}}async function uE(e){return se(e.paths,`migrate schema for ${e.name}`,()=>gn(e.paths,e.name,`migrate schema for ${e.name}`,async()=>{for(let t=0;t<3;t+=1){let i=await LL(e.paths,e.name,e.hooks);if(i?.schema===Ne)return i;let r=await vi(e.paths,e.name);if(r.status==="current"&&r.state)return r.state;if(r.status!=="migration-required"||!r.state)throw new Error(r.message??`Native change ${e.name} cannot be migrated`);if(await ma(e.paths,e.name))throw new Error(`Native change ${e.name} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let n=r.state;if(n.schema!==et&&n.schema!==be)throw new Error(`Native change ${e.name} has no supported migration route`);let a=await Dp(e.paths,e.name);if(a?.status==="current")throw new Error(`Native change ${e.name} has a current-schema pending transition; recover it before schema migration`);let o=await BL({paths:e.paths,name:e.name,state:n,pendingTransition:a,now:e.now??new Date,id:e.id?.()??EL()}),s=$s(e.paths,e.name),c=j(e.paths,s);await T(c,s),await ee(s,o,{containedRoot:c}),await e.hooks?.afterPrepared?.(o)}throw new Error(`Native change ${e.name} exceeded the supported schema migration path`)}))}var qi=Object.freeze({minimumAgeMs:720*60*60*1e3,keepLatestUnreferencedPerKind:32,maxDocuments:4096,maxScannedBytes:256*1024*1024,maxReportedRefs:8,maxReportMessageBytes:4096}),WL=512*1024,kn=/^([a-f0-9]{64})\.json$/u,zL=/^\.([a-f0-9]{64}\.json)\.([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})\.gc$/u,JL=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts|check-receipts)\/[a-f0-9]{64}\.json$/u,Gu=["snapshots","scopes","allowances","verifications","reports","receipts","check-receipts"];function Rm(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Pi(e,t){return Rm(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function mE(e,t){return Rm(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function La(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function nt(e,t){return e<t?-1:e>t?1:0}function GL(e,t){let i=le.relative(e.projectRoot,t);if(i.length===0||le.isAbsolute(i)||i===".."||i.startsWith(`..${le.sep}`))throw new Error("Native evidence retention finding path is outside the project");return i.split(le.sep).join("/")}function vE(e,t){return le.join(H(e,t),"evidence")}function Uu(e,t){return GL(e,vE(e,t))}async function Ku(e,t){let i=le.resolve(e),r=le.resolve(t);if(!O(i,r))throw new Error("Native evidence retention path escapes its managed change");let n=le.relative(i,r).split(le.sep).filter(Boolean),a=[],o=i;for(let s of["",...n]){s&&(o=le.join(o,s));let c=await Q.lstat(o);if(!c.isDirectory()||c.isSymbolicLink())throw new Error(`Native evidence retention parent must be a real directory: ${o}`);let l=await Q.realpath(o);if(a.length>0&&!O(a[0].realPath,l))throw new Error(`Native evidence retention parent resolves outside its change: ${o}`);a.push({path:o,realPath:l,...La(c)})}return a}async function Ft(e){for(let t of e){let i=await Q.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!Rm(t,i)||await Q.realpath(t.path)!==t.realPath)throw new Error(`Native evidence retention parent changed: ${t.path}`)}}function gE(e,t){return e==="check-receipts"?`runtime/evidence/check-receipts/${t}.json`:Ea(e,t)}function dE(e){return e!==null&&JL.test(e)?[e]:[]}function UL(e,t,i,r){if(e==="snapshots")return{canonical:wa(i,t),dependencies:[]};if(e==="scopes"){let a=ya(i);if(a.scopeHash!==t)throw new Error("Native scope filename does not match its hash");return{canonical:a,dependencies:[a.baselineProjectionRef,a.currentProjectionRef]}}if(e==="allowances"){let a=ru(i);if(a.change!==r||a.allowanceHash!==t)throw new Error("Native allowance filename/change does not match its content");return{canonical:a,dependencies:[Ea("scopes",a.scopeHash)]}}if(e==="verifications"){let a=fs(i);if(a.change!==r||a.envelopeHash!==t)throw new Error("Native verification filename/change does not match its content");let o=a.acceptanceTrace.entries.flatMap(s=>s.evidenceRefs.flatMap(dE));return{canonical:a,dependencies:[a.implementationScopeRef,ck(a.reportHash),...dE(a.partialAllowanceRef),...a.requiredReceiptRefs,...a.receiptRefs,...o]}}if(e==="reports"){if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Native report evidence must be an object");let a=i;if(Object.keys(a).sort().join(",")!=="content,reportHash,schema"||a.schema!=="comet.native.verification-report.v1"||a.reportHash!==t||typeof a.content!="string"||VL("sha256").update(Buffer.from(a.content,"utf8")).digest("hex")!==t)throw new Error("Native report evidence filename/hash does not match its content");return{canonical:a,dependencies:[]}}if(e==="receipts"){let a=au(i);if(a.bindings.change!==r||a.receiptHash!==t)throw new Error("Native verification receipt filename/change does not match its content");return{canonical:a,dependencies:a.kind==="static-inspection"?[a.evidence.checkReceiptRef]:[]}}let n=nu(i);if(n.change!==r||n.receiptHash!==t)throw new Error("Native check receipt filename/change does not match its content");return{canonical:n,dependencies:[]}}async function Wr(e){let t=await Q.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`Native evidence entry is not a regular file: ${e.ref}`);let i=e.kind==="check-receipts"?WL:_r;if(t.size>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);let r=await Q.realpath(e.file);if(!O(e.directoryChain[0].realPath,r))throw new Error(`Native evidence entry resolves outside its change: ${e.ref}`);let n=process.platform==="win32"?"r":Em.O_RDONLY|Em.O_NOFOLLOW|Em.O_NONBLOCK,a=await Q.open(e.file,n).catch(o=>{throw o.code==="ELOOP"||o.code==="ENXIO"?new Error(`Native evidence entry became unsafe while opening: ${e.ref}`):o});try{let[o,s,c]=await Promise.all([a.stat(),Q.lstat(e.file),Q.realpath(e.file)]);if(await Ft(e.directoryChain),!o.isFile()||!s.isFile()||s.isSymbolicLink()||c!==r||!Pi(La(t),o)||!Pi(La(o),s))throw new Error(`Native evidence entry changed while opening: ${e.ref}`);let l=[],u=Buffer.allocUnsafe(64*1024),d=0;for(;;){let g=i+1-d,y=await a.read(u,0,Math.min(u.length,g),null);if(y.bytesRead===0)break;if(d+=y.bytesRead,d>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);l.push(Buffer.from(u.subarray(0,y.bytesRead)))}let[f,h,v]=await Promise.all([a.stat(),Q.lstat(e.file),Q.realpath(e.file)]);if(await Ft(e.directoryChain),!h.isFile()||h.isSymbolicLink()||v!==r||!Pi(La(o),f)||!Pi(La(o),h))throw new Error(`Native evidence entry changed while reading: ${e.ref}`);let m=Buffer.concat(l,d).toString("utf8"),p;try{p=JSON.parse(m)}catch(g){throw new Error(`Native evidence entry is not valid JSON: ${e.ref}`,{cause:g})}let b=UL(e.kind,e.hash,p,e.name);if(m!==JSON.stringify(b.canonical,null,2)+`
267
- `)throw new Error(`Native evidence entry is not canonically serialized: ${e.ref}`);return{ref:e.ref,kind:e.kind,change:e.name,changeRoot:e.changeRoot,file:e.file,size:d,mtimeMs:f.mtimeMs,identity:La(f),directoryChain:e.directoryChain,dependencies:[...new Set(b.dependencies)].sort(nt)}}finally{await a.close()}}async function fE(e){try{return await Q.lstat(e),!1}catch(t){if(t.code==="ENOENT")return!0;throw t}}async function KL(e){let t=H(e.paths,e.name),i=t,r=vE(e.paths,e.name);await T(j(e.paths,r),r);let n;try{let s=await Ku(t,r);n=await Q.readdir(r,{withFileTypes:!0}),await Ft(s)}catch(s){if(s.code==="ENOENT")return{findings:[],pending:!1};throw s}let a=[];for(let s of Gu){if(!n.some(f=>f.name===s))continue;let c=le.join(r,s),l=await Ku(t,c),u=(await Q.readdir(c,{withFileTypes:!0})).sort((f,h)=>nt(f.name,h.name)),d=new Map;for(let f of u){let h=zL.exec(f.name);if(!h)continue;let v=d.get(h[1])??[];v.push(f),d.set(h[1],v)}for(let[f,h]of[...d.entries()].sort(([v],[m])=>nt(v,m))){if(h.length!==1)throw new Error(`Native evidence cleanup has multiple quarantines for ${s}/${f}`);let v=h[0];if(!v.isFile()||v.isSymbolicLink())throw new Error(`Native evidence cleanup quarantine is not a regular file: ${s}/${v.name}`);let m=le.join(c,f),p=kn.exec(f)?.[1];if(!p)throw new Error(`Native evidence cleanup quarantine name is invalid: ${v.name}`);let b=gE(s,p),g=le.join(c,v.name),y=await Wr({changeRoot:i,file:g,ref:b,kind:s,hash:p,name:e.name,directoryChain:l}),E=await fE(m),k=E?null:await Wr({changeRoot:i,file:m,ref:b,kind:s,hash:p,name:e.name,directoryChain:l});a.push({ref:b,original:m,quarantine:g,document:y,action:E?"restore-original":"finish-linked-recovery",originalDocument:k})}}if(a.length===0)return{findings:[],pending:!1};let o=a.map(s=>s.ref).sort(nt);if(!e.repair)return{pending:!0,findings:[{severity:"warning",code:"evidence-retention-recovery-required",message:Ma(`Native evidence cleanup has ${o.length} safely recoverable quarantined document(s) for ${e.name}: ${Yu(o)}`),path:Uu(e.paths,e.name)}]};for(let s of a.sort((c,l)=>nt(c.ref,l.ref))){if(await Ft(s.document.directoryChain),s.action==="finish-linked-recovery"){let d=await Wr({changeRoot:i,file:s.original,ref:s.ref,kind:s.document.kind,hash:kn.exec(le.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),f=await Wr({changeRoot:i,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:kn.exec(le.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!s.originalDocument||!Pi(s.originalDocument.identity,d.identity)||!Pi(s.document.identity,f.identity))throw new Error(`Native evidence cleanup original or quarantine changed during recovery: ${s.ref}`);await Q.rm(s.quarantine),await Ft(s.document.directoryChain);continue}if(!await fE(s.original))throw new Error(`Native evidence cleanup original appeared during recovery: ${s.ref}`);let c=await Q.lstat(s.quarantine);if(!c.isFile()||c.isSymbolicLink()||!Pi(s.document.identity,c))throw new Error(`Native evidence cleanup quarantine changed during recovery: ${s.ref}`);await Q.link(s.quarantine,s.original),await e.hooks.afterRecoveryLink?.({ref:s.ref,original:s.original,quarantine:s.quarantine});let l=await Wr({changeRoot:i,file:s.original,ref:s.ref,kind:s.document.kind,hash:kn.exec(le.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),u=await Wr({changeRoot:i,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:kn.exec(le.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!mE(s.document.identity,l.identity)||!Pi(l.identity,u.identity))throw new Error(`Native evidence cleanup recovery identity changed: ${s.ref}`);await Q.rm(s.quarantine),await Ft(s.document.directoryChain)}return{pending:!1,findings:[{severity:"info",code:"evidence-retention-cleanup-recovered",message:Ma(`Recovered ${o.length} interrupted Native evidence cleanup document(s) for ${e.name}: ${Yu(o)}`),path:Uu(e.paths,e.name)}]}}async function YL(e,t){let i=H(e,t),r=i,n=le.join(i,"evidence");await T(j(e,n),n);let a;try{let l=await Ku(i,n);a=await Q.readdir(n,{withFileTypes:!0}),await Ft(l)}catch(l){if(l.code==="ENOENT")return[];throw l}let o=a.filter(l=>!Gu.includes(l.name)||!l.isDirectory()||l.isSymbolicLink()).map(l=>l.name).sort(nt);if(o.length>0)throw new Error(`Native evidence root has unknown or special entries: ${Yu(o)}`);let s=[],c=0;for(let l of Gu){if(!a.some(h=>h.name===l))continue;let u=le.join(n,l),d=await Ku(r,u),f=(await Q.readdir(u,{withFileTypes:!0})).sort((h,v)=>nt(h.name,v.name));await Ft(d);for(let h of f){if(s.length>=qi.maxDocuments)throw new Error(`Native evidence store exceeds ${qi.maxDocuments} documents`);let v=kn.exec(h.name);if(!v||!h.isFile()||h.isSymbolicLink())throw new Error(`Native evidence kind ${l} has an unknown or special entry: ${h.name}`);let m=gE(l,v[1]),p=le.join(u,h.name);await T(j(e,p),p);let b=await Wr({changeRoot:r,file:p,ref:m,kind:l,hash:v[1],name:t,directoryChain:d});if(c+=b.size,c>qi.maxScannedBytes)throw new Error(`Native evidence store exceeds ${qi.maxScannedBytes} scanned bytes`);s.push(b)}await Ft(d)}return s}function hE(e,t){let i=new Set,r=[...e].sort(nt).reverse();for(;r.length>0;){let n=r.pop();if(i.has(n))continue;let a=t.get(n);if(!a)throw new Error(`Native evidence dependency is missing: ${n}`);i.add(n);for(let o of[...a.dependencies].sort(nt).reverse())i.has(o)||r.push(o)}return i}function XL(e){let t=new Map(e.map(a=>[a.ref,a])),i=new Map(e.map(a=>[a.ref,0]));for(let a of e)for(let o of a.dependencies)t.has(o)&&i.set(o,(i.get(o)??0)+1);let r=[...i].filter(([,a])=>a===0).map(([a])=>a).sort(nt),n=[];for(;r.length>0;){let a=r.shift(),o=t.get(a);n.push(o);for(let s of o.dependencies){let c=i.get(s);if(c===void 0)continue;let l=c-1;i.set(s,l),l===0&&(r.push(s),r.sort(nt))}}if(n.length!==e.length)throw new Error("Native evidence candidate dependency graph contains a cycle");return n}function QL(e,t,i){let r=new Map(e.map(c=>[c.ref,c]));if(r.size!==e.length)throw new Error("Native evidence store has duplicate refs");for(let c of e)for(let l of c.dependencies)if(!r.has(l))throw new Error(`Native evidence dependency is missing: ${l}`);let n=hE(t,r),a=new Set(n);for(let c of e)i-c.mtimeMs<qi.minimumAgeMs&&a.add(c.ref);for(let c of Gu){let l=e.filter(u=>u.kind===c&&!n.has(u.ref)).sort((u,d)=>d.mtimeMs-u.mtimeMs||nt(u.ref,d.ref)).slice(0,qi.keepLatestUnreferencedPerKind);for(let u of l)a.add(u.ref)}let o=hE(a,r),s=e.filter(c=>!o.has(c.ref)&&i-c.mtimeMs>=qi.minimumAgeMs).sort((c,l)=>nt(c.ref,l.ref));return{candidates:XL(s),candidateBytes:s.reduce((c,l)=>c+l.size,0)}}function Yu(e){let t=e.slice(0,qi.maxReportedRefs),i=e.length-t.length;return`${t.join(", ")}${i>0?`, ... (${i} more)`:""}`}function Ma(e){let t=qi.maxReportMessageBytes;if(Buffer.byteLength(e,"utf8")<=t)return e;let i=e;for(;i.length>0&&Buffer.byteLength(`${i}...`,"utf8")>t;)i=i.slice(0,-1);return`${i}...`}function Pm(e,t,i,r){let n=t.candidates.map(a=>a.ref).sort(nt);return{severity:"info",code:i?"evidence-retention-cleaned":"evidence-retention-candidates",message:Ma(`${i?"Removed":"Found"} ${t.candidates.length} old unreferenced Native evidence document(s) (${t.candidateBytes} bytes) for ${e}: ${Yu(n)}`),path:r}}async function pE(e,t){try{await Q.lstat(t);return}catch(i){if(i.code!=="ENOENT")return}try{await Q.rename(e,t)}catch{}}async function ZL(e,t){await t.beforeDelete?.({ref:e.ref,file:e.file}),await Ft(e.directoryChain);let i=await Wr({changeRoot:e.changeRoot,file:e.file,ref:e.ref,kind:e.kind,hash:kn.exec(le.basename(e.file))[1],name:e.change,directoryChain:e.directoryChain}),r=await Q.lstat(e.file),n=await Q.realpath(e.file);if(!r.isFile()||r.isSymbolicLink()||!Pi(e.identity,r)||!Pi(e.identity,i.identity)||!O(e.directoryChain[0].realPath,n))throw new Error(`Native evidence candidate changed before cleanup: ${e.ref}`);let a=le.join(le.dirname(e.file),`.${le.basename(e.file)}.${qL()}.gc`);await Q.rename(e.file,a);try{let[o,s]=await Promise.all([Q.lstat(a),Q.realpath(a)]);if(await Ft(e.directoryChain),!o.isFile()||o.isSymbolicLink()||!mE(e.identity,o)||!O(e.directoryChain[0].realPath,s))throw await pE(a,e.file),new Error(`Native evidence candidate changed during cleanup: ${e.ref}`);await Q.rm(a),await Ft(e.directoryChain)}catch(o){throw await pE(a,e.file),o}}async function eM(e){if((await ye(e.projectRoot))?.native.pending_root_move)return!0;let i;try{i=await Q.readdir(e.transactionsDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return!1;throw r}for(let r of i){if(!r.isDirectory()||r.isSymbolicLink())return!0;try{let n=await yt(e,r.name);if(n.status!=="committed"&&n.status!=="rolled-back")return!0}catch{return!0}}return!1}async function tM(e,t){if(t)return[t];let i;try{i=await Q.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}return i.filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort(nt)}async function iM(e,t){let i=await vi(e,t);if(i.status!=="current"||!i.state||i.state.archived)return!0;let[r,n,a]=await Promise.all([Mi(e,t),Os(e,t),Or(e,t)]);return r!==null||n!==null||a!==null}async function rM(e){if(await iM(e.paths,e.name))return[];let t=await vi(e.paths,e.name);if(t.status!=="current"||!t.state)return[];if(!("implementation_scope"in t.state))return[];let i=await KL({paths:e.paths,name:e.name,repair:e.repair,hooks:e.hooks});if(i.pending)return i.findings;let r=[];for(let c of[t.state.implementation_scope,t.state.partial_allowance,t.state.verification_evidence])c!==null&&r.push(c);let n=await YL(e.paths,e.name),a=QL(n,r,e.nowMs);if(a.candidates.length===0)return i.findings;let o=Uu(e.paths,e.name);if(!e.repair)return[...i.findings,Pm(e.name,a,!1,o)];let s=[];for(let c of a.candidates)try{await ZL(c,e.hooks),s.push(c)}catch(l){let u=s.reduce((d,f)=>d+f.size,0);return[...i.findings,...s.length>0?[Pm(e.name,{candidates:s,candidateBytes:u},!0,o)]:[],{severity:"error",code:"evidence-retention-cleanup-failed",message:Ma(`Native evidence cleanup stopped safely for ${e.name}: ${l.message}`),path:o}]}return[...i.findings,Pm(e.name,a,!0,o)]}async function wE(e){if(e.deferAll||await eM(e.paths))return[];let t=e.now??new Date;if(Number.isNaN(t.getTime()))throw new Error("Native evidence retention time is invalid");let i=async n=>{let a=[];for(let o of await tM(e.paths,e.name))try{a.push(...await rM({paths:e.paths,name:o,repair:n,nowMs:t.getTime(),hooks:e.hooks??{}}))}catch(s){a.push({severity:"error",code:"evidence-retention-unsafe",message:Ma(`Native evidence retention refused to clean ${o}: ${s.message}`),path:Uu(e.paths,o)})}return a};if(!(e.repair??!1))return i(!1);let r=await i(!1);if(r.some(n=>n.severity==="error")||!r.some(n=>n.code==="evidence-retention-candidates"||n.code==="evidence-retention-recovery-required"))return r;try{return await se(e.paths,"prune Native evidence",()=>i(!0))}catch(n){return[{severity:"info",code:"evidence-retention-cleanup-deferred",message:Ma(`Native evidence cleanup was deferred until the project mutation lock is available: ${n.message}`)}]}}import{createHash as nM,randomUUID as F6}from"crypto";import{promises as Ls}from"fs";import ae from"path";var xm=64*1024*1024,aM=256*1024,kE=16*1024*1024;async function at(e){try{return await Ls.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function oM(e){let t;try{t=await Ls.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of t.sort((r,n)=>r.name.localeCompare(n.name))){if(!i.isDirectory()||i.isSymbolicLink())continue;let r=await kt(e,i.name);if(r){await Jl({paths:e,name:i.name,revision:r.capturedRevision,...r.schema==="comet.native.workspace.v3"?{binding:{isolation:r.isolation,changeBranch:r.changeBranch,targetBranch:r.targetBranch},...r.finish?{finish:r.finish}:{}}:{}});continue}}}async function Ds(e,t){let i=[];async function r(n){let a=await wt({root:e,directory:n,label:"Native root tree"}),o=a.entries;o.sort((s,c)=>s.name.localeCompare(c.name));for(let s of o){await a.verify();let c=ae.join(n,s.name);if(t.excludedFiles?.has(ae.resolve(c))){await a.verify();continue}let l=await Ls.lstat(c);if(s.isSymbolicLink()||l.isSymbolicLink()){if(t.rejectSymlinks)throw new Error(`Native root contains a symlink: ${c}`);await a.verify();continue}if(s.isDirectory()&&l.isDirectory())i.push({ref:ae.relative(e,c).split(ae.sep).join("/"),type:"directory"}),await r(c);else if(s.isFile()&&l.isFile()){let u=await re({root:e,file:c,maxBytes:xm,label:`Native root file ${ae.relative(e,c)}`});i.push({ref:ae.relative(e,c).split(ae.sep).join("/"),type:"file",size:u.size,hash:u.hash})}else throw new Error(`Native root contains an unsupported file type: ${c}`);await a.verify()}}return await r(e),i.sort((n,a)=>n.ref.localeCompare(a.ref))}async function sM(e,t,i,r){await fi({root:r,directory:t,label:"Native root move staging directory"});async function n(a,o){let s=await wt({root:e,directory:a,label:"Native root move source directory"}),c=s.entries;for(let l of c){await s.verify();let u=ae.join(a,l.name);if(ae.resolve(u)===ae.resolve(i)){await s.verify();continue}let d=await Ls.lstat(u);if(l.isSymbolicLink()||d.isSymbolicLink())throw new Error(`Native root contains a symlink: ${u}`);let f=ae.join(o,l.name);if(l.isDirectory()&&d.isDirectory())await fi({root:r,directory:f,label:"Native root move staging directory"}),await n(u,f);else if(l.isFile()&&d.isFile())await wr({sourceRoot:e,source:u,targetRoot:r,target:f,maxBytes:xm,label:`Native root move file ${ae.relative(e,u)}`,exclusive:!0,expectedTargetHash:null});else throw new Error(`Native root contains an unsupported file type: ${u}`);await s.verify()}}await n(e,t)}async function Fa(e,t,i,r){let n=await Ds(e,{rejectSymlinks:!0,excludedFiles:i?new Set([ae.resolve(i)]):void 0}),a=await Ds(t,{rejectSymlinks:!0,excludedFiles:r?new Set([ae.resolve(r)]):void 0});if(JSON.stringify(n)!==JSON.stringify(a))throw new Error(`Native root copies differ; preserve both trees for manual recovery: ${e} and ${t}`)}function cM(e,t){return ae.join(e.artifactRoot,`.comet-native-move-${t}`)}function lM(e,t){return ae.join(e.artifactRoot,`.comet-native-source-${t}.removing`)}function uM(e){return`${e}.removing`}function yE(e,t){return ae.join(ae.dirname(e),`.${ae.basename(e)}.${t}.rollback-removing`)}function SE(e,t,i){return ae.join(Al(e,t).directory,`root-move-cleanup-${i}.json`)}function dM(e){return JSON.stringify(e,null,2)+`
268
- `}function fM(e){return nM("sha256").update(e).digest("hex")}function hM(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Native root-move cleanup manifest entry ${t} must be an object`);let i=e,r=Object.keys(i).sort(),n=i.type==="file"?["hash","ref","size","type"]:["ref","type"];if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Native root-move cleanup manifest entry ${t} has invalid fields`);if(typeof i.ref!="string"||i.ref.length===0||i.ref.includes("\\")||ae.posix.normalize(i.ref)!==i.ref||i.ref.startsWith("/")||i.ref.split("/").includes("..")||Buffer.byteLength(i.ref,"utf8")>4096)throw new Error(`Native root-move cleanup manifest entry ${t} has an invalid ref`);if(i.type==="directory")return{ref:i.ref,type:"directory"};if(i.type!=="file"||typeof i.size!="number"||!Number.isSafeInteger(i.size)||i.size<0||typeof i.hash!="string"||!/^[a-f0-9]{64}$/u.test(i.hash))throw new Error(`Native root-move cleanup manifest entry ${t} is invalid`);return{ref:i.ref,type:"file",size:i.size,hash:i.hash}}function pM(e,t,i){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native root-move cleanup manifest must be an object");let r=e;if(JSON.stringify(Object.keys(r).sort())!==JSON.stringify(["entries","kind","schema","transactionId"])||r.schema!=="comet.native.root-move-cleanup.v1"||r.transactionId!==t||r.kind!==i||!Array.isArray(r.entries))throw new Error("Native root-move cleanup manifest binding is invalid");let n=r.entries.map(hM);for(let a=0;a<n.length;a+=1){if(a>0&&n[a-1].ref.localeCompare(n[a].ref)>=0)throw new Error("Native root-move cleanup manifest refs must be unique and sorted");let o=ae.posix.dirname(n[a].ref);if(o!=="."&&!n.some(s=>s.ref===o&&s.type==="directory"))throw new Error(`Native root-move cleanup manifest parent is missing: ${o}`)}return{schema:"comet.native.root-move-cleanup.v1",transactionId:t,kind:i,entries:n}}async function mM(e){let t={schema:"comet.native.root-move-cleanup.v1",transactionId:e.id,kind:e.kind,entries:e.entries},i=dM(t);if(Buffer.byteLength(i,"utf8")>kE)throw new Error("Native root-move cleanup manifest exceeds its byte budget");return await he(SE(e.paths,e.id,e.kind),i,{containedRoot:e.paths.runtimeDir}),fM(i)}async function vM(e){let t=await re({root:e.paths.runtimeDir,file:SE(e.paths,e.id,e.cleanup.kind),maxBytes:kE,label:`Native root-move cleanup manifest ${e.cleanup.kind}`});if(t.hash!==e.cleanup.manifestHash)throw new Error("Native root-move cleanup manifest hash changed");return pM(JSON.parse(t.bytes.toString("utf8")),e.id,e.cleanup.kind)}async function Cm(e){let t=await Ds(e.quarantine,{rejectSymlinks:!0}),i=new Map(e.manifest.entries.map(r=>[r.ref,r]));for(let r of t){let n=i.get(r.ref);if(!n||JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Native root-move cleanup quarantine differs from its bound manifest: ${r.ref}`)}if(e.exact&&t.length!==e.manifest.entries.length)throw new Error("Native root-move cleanup quarantine is incomplete before deletion");return t}function NE(e){return e.ref.split("/").length}async function gM(e){let i=[...await Cm({quarantine:e.quarantine,manifest:e.manifest,exact:!1})].sort((n,a)=>NE(a)-NE(n)||(n.type===a.type?a.ref.localeCompare(n.ref):n.type==="file"?-1:1)),r=0;for(let n of i){let a=ae.join(e.quarantine,...n.ref.split("/"));n.type==="file"?await El({root:e.projectRoot,file:a,maxBytes:xm,expectedHash:n.hash,expectedSize:n.size,label:`Native root-move cleanup file ${n.ref}`}):await Ph({root:e.projectRoot,directory:a,label:`Native root-move cleanup directory ${n.ref}`}),r+=1,await e.hooks?.afterRootMoveCleanupEntryRemoved?.(e.manifest.kind,n.ref,r)}await Cm({quarantine:e.quarantine,manifest:e.manifest,exact:!1}),await Ph({root:e.projectRoot,directory:e.quarantine,label:`Native root-move cleanup quarantine ${e.manifest.kind}`})}function EE(e,t,i=e.native.artifact_root){return{...e,native:{...e.native,artifact_root:i,pending_root_move:t}}}function wM(e){return{schema:"comet.native.transaction.v1",id:e.id,kind:"root-move",status:"prepared",projectRoot:e.paths.projectRoot,nativeRoot:e.paths.nativeRoot,createdAt:e.now.toISOString(),operations:[]}}async function yM(e,t,i,r){for(let a of[e,t])try{let o=await yt(a,r);if(o.kind!=="root-move")throw new Error(`Transaction ${r} is not a root move`);return{journal:o,paths:a}}catch(o){if(o.code!=="ENOENT")throw o}let n=ae.join(i,"runtime","transactions",r,"transaction.json");try{let a=await re({root:i,file:n,maxBytes:aM,label:`Staged Native root-move journal ${r}`}),o=JSON.parse(a.bytes.toString("utf8"));if(o.schema!=="comet.native.transaction.v1"||o.kind!=="root-move")throw new Error(`Invalid staged root-move journal: ${r}`);return{journal:o,paths:t}}catch(a){throw a.code!=="ENOENT"?a:new Error(`Native root-move journal is missing: ${r}`,{cause:a})}}async function bE(e){let t=EE(e.config,{...e.pending,stage:e.stage},e.activeArtifactRoot);return await ur(e.projectRoot,t),t}async function Hs(e){let t=e.config.native.pending_root_move;if(!t||t.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let i=EE(e.config,{id:t.id,fromArtifactRoot:t.fromArtifactRoot,toArtifactRoot:t.toArtifactRoot,stage:t.stage,...e.cleanup?{cleanup:e.cleanup}:{}},e.config.native.artifact_root);return await ur(e.projectRoot,i),i}async function Xu(e){let t=e.config,i=t.native.pending_root_move;if(!i||i.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let r=i.cleanup;if(r&&r.kind!==e.kind)throw new Error(`Native root move has unfinished ${r.kind} cleanup; cannot start ${e.kind}`);let n=await at(e.target),a=await at(e.quarantine);if(n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(!r){if(!n&&!a)return t;if(!n&&a)throw new Error(`Native root-move cleanup quarantine is not transaction-bound: ${e.kind}`);let s=await mM({paths:e.stablePaths,id:e.id,kind:e.kind,entries:await Ds(e.target,{rejectSymlinks:!0})});r={kind:e.kind,state:"prepared",manifestHash:s},t=await Hs({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})}let o=await vM({paths:e.stablePaths,id:e.id,cleanup:r});if(n=await at(e.target),a=await at(e.quarantine),n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(n){if(r.state!=="prepared")throw new Error(`Native root-move cleanup target reappeared after quarantine: ${e.kind}`);await Uy({root:e.projectRoot,directory:e.target,quarantine:e.quarantine,label:e.label,beforeQuarantine:e.beforeQuarantine,afterQuarantine:e.afterQuarantine}),a=!0}if(!a){if(r.state!=="deleting")throw new Error(`Native root-move cleanup quarantine disappeared: ${e.kind}`);return Hs({projectRoot:e.projectRoot,config:t,id:e.id})}return await Cm({quarantine:e.quarantine,manifest:o,exact:r.state!=="deleting"}),r.state==="prepared"&&(r={...r,state:"quarantined"},t=await Hs({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})),r.state==="quarantined"&&(r={...r,state:"deleting"},t=await Hs({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})),await gM({projectRoot:e.projectRoot,quarantine:e.quarantine,manifest:o,hooks:e.hooks}),Hs({projectRoot:e.projectRoot,config:t,id:e.id})}async function NM(e){let t=e.config,i=t.native.pending_root_move.stage;if(i==="copying"){if(!await at(e.sourcePaths.nativeRoot))throw new Error(`Native source root is missing: ${e.sourcePaths.nativeRoot}`);let s=uM(e.staging);t=await Xu({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"restart-staging",stablePaths:e.sourcePaths,target:e.staging,quarantine:s,label:"Native root move stale staging removal",hooks:e.hooks}),await Ds(e.sourcePaths.nativeRoot,{rejectSymlinks:!0,excludedFiles:new Set([ae.resolve(e.lockFile)])}),await sM(e.sourcePaths.nativeRoot,e.staging,e.lockFile,e.destinationPaths.projectRoot),await Fa(e.sourcePaths.nativeRoot,e.staging,e.lockFile),t=await bE({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"ready"}),i="ready",await e.hooks?.afterRootMoveStage?.("ready",e.journal)}if(i==="ready"){if(await at(e.destinationPaths.nativeRoot)){if(await at(e.staging))throw new Error(`Native destination is occupied: ${e.destinationPaths.nativeRoot}`);await Fa(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile)}else{if(!await at(e.staging))throw new Error("Native move staging tree is missing");await Fa(e.sourcePaths.nativeRoot,e.staging,e.lockFile),await Ls.rename(e.staging,e.destinationPaths.nativeRoot)}t=await bE({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"switched",activeArtifactRoot:e.pending.toArtifactRoot}),i="switched",await e.hooks?.afterRootMoveStage?.("switched",e.journal)}if(i!=="switched")throw new Error(`Unsupported Native root-move stage: ${i}`);if(!await at(e.destinationPaths.nativeRoot))throw new Error(`Native destination root is missing: ${e.destinationPaths.nativeRoot}`);let r=lM(e.sourcePaths,e.pending.id);!t.native.pending_root_move?.cleanup&&await at(e.sourcePaths.nativeRoot)&&await Fa(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile),t=await Xu({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"forward-source",stablePaths:e.destinationPaths,target:e.sourcePaths.nativeRoot,quarantine:r,label:"Native root move source removal",beforeQuarantine:()=>e.hooks?.beforeRootMoveSourceRemove?.(e.sourcePaths.nativeRoot),afterQuarantine:s=>e.hooks?.afterRootMoveSourceQuarantined?.(s),hooks:e.hooks}),await oM(e.destinationPaths);let n=await yt(e.destinationPaths,e.pending.id);await ta(e.destinationPaths,n,"commit");let a={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},o={...t,native:{...a,artifact_root:e.pending.toArtifactRoot}};return await ur(e.projectRoot,o),o}async function PE(e){let t=await ye(e.projectRoot),i=t?.native.pending_root_move;if(!t||!i)throw new Error("No pending Native root move was found");let r=await qe(e.projectRoot,i.fromArtifactRoot),n=await qe(e.projectRoot,i.toArtifactRoot),a=cM(n,i.id),o=await at(r.nativeRoot)?r:n,s=await dr(o,"root-move",`recover root ${i.id}`);try{let c;try{c=await yM(r,n,a,i.id)}catch(v){if(i.stage!=="copying"||!await at(r.nativeRoot))throw v;let m=wM({id:i.id,paths:r,now:new Date});await nN(r,m),c={journal:m,paths:r}}if(e.strategy==="continue"){let v=await NM({projectRoot:e.projectRoot,config:t,pending:i,sourcePaths:r,destinationPaths:n,staging:a,journal:c.journal,lockFile:s.file,hooks:e.hooks});return{activeNativeRoot:n.nativeRoot,config:v}}if(!await at(r.nativeRoot))throw new Error("Cannot roll back after the old Native root was removed; continue recovery");let l=yE(n.nativeRoot,i.id);!t.native.pending_root_move?.cleanup&&await at(n.nativeRoot)&&await Fa(r.nativeRoot,n.nativeRoot,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-destination")&&(t=await Xu({projectRoot:e.projectRoot,config:t,id:i.id,kind:"rollback-destination",stablePaths:r,target:n.nativeRoot,quarantine:l,label:"Native root move rollback destination removal",hooks:e.hooks}));let u=yE(a,i.id);!t.native.pending_root_move?.cleanup&&await at(a)&&await Fa(r.nativeRoot,a,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-staging")&&(t=await Xu({projectRoot:e.projectRoot,config:t,id:i.id,kind:"rollback-staging",stablePaths:r,target:a,quarantine:u,label:"Native root move rollback staging removal",hooks:e.hooks}));let d=await yt(r,i.id);await _l(r,d);let f={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},h={...t,native:{...f,artifact_root:i.fromArtifactRoot}};return await ur(e.projectRoot,h),{activeNativeRoot:r.nativeRoot,config:h}}finally{await fr(s)}}var Ba=4096,bM=4096,kM=1024;async function zr(e,t,i){try{let r=await wt({root:j(e,t),directory:t,label:"Native doctor directory",maxEntries:i});return await r.verify(),r.entries}catch(r){if(r.code==="ENOENT")return[];throw r}}async function Zu(e,t){let i=new Map(e.map(r=>[Ie.resolve(r.file),{...r,file:Ie.resolve(r.file)}]));for(let{paths:r,file:n}of i.values()){let a;try{a=await $o(n)}catch(o){return t.push({severity:"error",code:"lock-invalid",message:`Native recovery lock is invalid: ${o.message}`,path:n}),!1}if(a.status!=="missing"){if(a.status==="stale"){let o=await hh(r,n,a);if(o.status==="removed"){t.push({severity:"info",code:"stale-recovery-lock-removed",message:"Removed stale lock before explicit transaction recovery",path:n});continue}if(o.status==="missing")continue;a=o.diagnosis}return a.status==="stale"?(t.push({severity:"error",code:"lock-takeover-raced",message:"Native recovery lock changed while doctor was preparing stale takeover",path:n}),!1):(t.push({severity:"error",code:a.status==="active"?"lock-active":"lock-owner-unknown",message:a.status==="active"?"Native recovery lock is still owned by a live process":"Native recovery lock owner cannot be proven stale",path:n}),!1)}}return!0}async function SM(e,t){let i=zS(e),r;try{await T(e.projectRoot,i);let n=await Mu(e);if(!n)return[];r=n}catch(n){return n.code==="ENOENT"?[]:[{severity:"error",code:"selection-invalid",message:`Native selection is invalid: ${n.message}`,path:i}]}if(r.schema!=="comet.selection.v2"||r.workflow!=="native"||typeof r.change!="string")return[{severity:"error",code:"selection-invalid",message:"Native selection has an invalid schema or change name",path:i}];try{return await qr(e,r.change)?[]:(await He(e,r.change),[])}catch(n){if(n.code!=="ENOENT")return[{severity:"error",code:"selection-target-invalid",message:`Selected Native change is invalid: ${n.message}`,path:i}]}return t?(await Qu.rm(i,{force:!0}),[{severity:"info",code:"selection-cleared",message:`Cleared stale Native selection ${r.change}`,path:i}]):[{severity:"warning",code:"selection-stale",message:`Selected Native change does not exist: ${r.change}`,path:i}]}async function EM(e){let t=[];for(let i of[e.specsDir,e.changesDir,e.archiveDir,e.runtimeDir,e.locksDir,e.transactionsDir])try{await T(j(e,i),i)}catch(r){t.push({severity:"error",code:"native-path-unsafe",message:`Managed Native path is unsafe: ${r.message}`,path:i})}return t}async function PM(e,t){let i=[],r=[];for(let n of await zr(e,e.transactionsDir,bM)){if(!n.isDirectory()||n.isSymbolicLink())continue;let a;try{a=await yt(e,n.name)}catch(o){i.push({severity:"error",code:"transaction-invalid",message:`Native transaction ${n.name} is invalid: ${o.message}`,path:Ie.join(e.transactionsDir,n.name)});continue}if(!(a.status==="committed"||a.status==="rolled-back")&&!(t.name&&a.change&&a.change!==t.name)){if(a.kind!=="archive"){r.push(a),i.push({severity:"error",code:"root-move-transaction-orphaned",message:`Root-move transaction ${a.id} is incomplete but project config has no matching pending move`});continue}if(t.repair&&t.recoveryStrategy)try{if(!await zn([e],`doctor archive recovery ${a.id}`,async()=>await Zu([{paths:e,file:Ie.join(e.locksDir,"root-move.lock")},{paths:e,file:Ie.join(e.locksDir,"archive.lock")}],i)?(await KS({paths:e,transactionId:a.id,strategy:t.recoveryStrategy}),!0):!1)){r.push(a);continue}i.push({severity:"info",code:"archive-transaction-recovered",message:`${t.recoveryStrategy==="continue"?"Continued":"Rolled back"} archive transaction ${a.id}`})}catch(o){r.push(a),i.push({severity:"error",code:"archive-recovery-failed",message:`Archive recovery failed: ${o.message}`})}else r.push(a),i.push({severity:"error",code:"archive-transaction-incomplete",message:t.repair?`Archive transaction ${a.id} needs an explicit recovery strategy`:`Archive transaction ${a.id} is incomplete`,repair:t.recoveryStrategy??"continue"})}}return{findings:i,unfinished:r}}async function RM(e,t,i){let r=[];for(let n of await zr(e,e.locksDir,kM)){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".lock"))continue;let a=Ie.join(e.locksDir,n.name);try{let o=await $o(a);if(o.status==="active")r.push({severity:"warning",code:"lock-active",message:`Native lock is active for ${o.owner?.operation??"an operation"}`,path:a});else if(o.status==="unknown")r.push({severity:"warning",code:"lock-owner-unknown",message:"Native lock owner cannot be proven stale",path:a});else if(o.status==="stale")if(t&&i.length===0){let s=await hh(e,a,o);s.status==="removed"?r.push({severity:"info",code:"stale-lock-removed",message:"Removed a Native lock whose local owner process is absent",path:a}):s.status==="changed"&&r.push({severity:s.diagnosis.status==="active"?"warning":"error",code:"lock-takeover-raced",message:"Native lock changed while doctor was preparing stale takeover",path:a})}else r.push({severity:i.length>0?"error":"warning",code:"lock-stale",message:i.length>0?"Native lock is stale but an unfinished transaction still requires recovery":"Native lock owner process is absent",path:a})}catch(o){r.push({severity:"error",code:"lock-invalid",message:`Native lock metadata is invalid: ${o.message}`,path:a})}}return r}async function CM(e,t,i=5){let r=[],n=t?await ym(e,{maxVerifyFailures:i}).then(a=>a.filter(o=>o.name===t)):await ym(e,{maxVerifyFailures:i});if(t&&n.length===0)return[{severity:"error",code:"change-missing",message:`Native change does not exist: ${t}`}];for(let a of n){if(a.migrationRequired)continue;if(a.phase==="invalid"){r.push({severity:"error",code:"change-invalid",message:a.error??`Native change ${a.name} is invalid`,path:Ie.join(e.changesDir,a.name,Te)});continue}let o=await wm(e,a.name,{details:!0,maxVerifyFailures:i});for(let s of o.findings??[])s.code==="trajectory-tail-incomplete"||s.code==="checkpoint-progress-incomplete"||r.push({severity:s.severity,code:s.code,message:`${a.name}: ${s.message}`,...s.path?{path:Ie.join(e.projectRoot,s.path)}:{}})}return r}async function xM(e,t){let i=[],r=t.name?[t.name]:(await zr(e,e.changesDir,Ba)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r)try{let a=await la(e,n);if(a.status!=="repairable")continue;if(!t.repair){i.push({severity:"error",code:"trajectory-tail-incomplete",message:`Native trajectory for ${n} has an incomplete final line ${a.line}; ${a.discardedBytes} byte(s) are outside the last complete event`,path:a.file,repair:"truncate-tail"});continue}let o=await qN(e,n);o&&i.push({severity:"info",code:"trajectory-tail-repaired",message:`Removed the incomplete Native trajectory tail for ${n} and preserved all complete events`,path:o.file})}catch(a){i.push({severity:"error",code:"trajectory-tail-repair-failed",message:`Native trajectory tail repair failed for ${n}: ${a.message}`,path:Ie.join(H(e,n),"trajectory.jsonl")})}return i}async function AM(e,t){let i=[],r=t.name?[t.name]:(await zr(e,e.changesDir,Ba)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=await jo(e,n);if(a.status==="missing"){i.push({severity:"warning",code:"runtime-missing",message:`Native Runtime for ${n} is missing; continue the change to rebuild it`,path:a.path});continue}if(a.status==="invalid"){i.push({severity:"error",code:"runtime-storage-invalid",message:a.message??`Native Runtime storage for ${n} is invalid`,path:a.path});continue}if(a.layout!=="legacy")continue;let o=tn(e,n),s=We(e,n);if(!t.repair){i.push({severity:"warning",code:"runtime-layout-legacy",message:`Native Runtime for ${n} still uses the legacy change-local layout`,path:o,repair:"migrate"});continue}try{await zn([e],`migrate Runtime layout for ${n}`,async()=>{let c=await Qt({root:e.nativeRoot,directory:o,label:`Legacy Native Runtime ${n}`});await T(e.runtimeDir,s),await Qu.mkdir(e.changesRuntimeDir,{recursive:!0});let l=await Qt({root:e.runtimeDir,directory:e.changesRuntimeDir,label:`Native Runtime migration target parent ${n}`});try{throw await Qu.lstat(s),new Error(`Target Native Runtime already exists: ${s}`)}catch(u){if(u.code!=="ENOENT")throw u}await c.verify(),await l.verify(),await Qu.rename(o,s)}),i.push({severity:"info",code:"runtime-layout-migrated",message:`Moved Native Runtime for ${n} to project-local .comet storage`,path:s})}catch(c){i.push({severity:"error",code:"runtime-layout-migration-failed",message:`Native Runtime layout migration failed for ${n}: ${c.message}`,path:o})}}return i}async function _M(e,t){let i=[],r=t.name?[t.name]:(await zr(e,e.changesDir,Ba)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r)try{if(!await Yh(e,n))continue;if(!t.repair){i.push({severity:"warning",code:"workspace-identity-migration-required",message:`Native workspace identity for ${n} uses legacy external-probe or hash-only metadata`,path:da(e,n),repair:"migrate"});continue}let a=await He(e,n);await eb({paths:e,name:n,revision:a.revision})&&i.push({severity:"info",code:"workspace-identity-migrated",message:`Replaced legacy workspace metadata for ${n} with process-free root identities`,path:da(e,n)})}catch(a){i.push({severity:"error",code:"workspace-identity-migration-failed",message:`Native workspace identity migration failed for ${n}: ${a.message}`,path:da(e,n)})}return i}async function TM(e,t){let i=[],r=t.name?[t.name]:(await zr(e,e.changesDir,Ba)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=$s(e,n);try{let o=await Os(e,n),s=await vi(e,n);if(!o&&s.status==="current")continue;if(s.status==="runtime-incompatible"){i.push({severity:"error",code:"change-runtime-incompatible",message:s.message??`Native change ${n} requires a newer runtime`,path:Ie.join(e.changesDir,n,Te)});continue}if(!t.repair){i.push({severity:"error",code:o?"schema-migration-incomplete":"schema-migration-required",message:o?`Native schema migration ${o.id} is incomplete for ${n}`:`Native change ${n} requires migration to the current schema`,path:o?a:Ie.join(e.changesDir,n,Te),repair:"migrate"});continue}await uE({paths:e,name:n}),i.push({severity:"info",code:o?"schema-migration-recovered":"schema-migrated",message:`Migrated Native change ${n} to the current schema`,path:Ie.join(e.changesDir,n,Te)})}catch(o){if(o.code==="ENOENT")continue;i.push({severity:"error",code:"schema-migration-failed",message:`Native schema migration failed for ${n}: ${o.message}`,path:a})}}return i}async function IM(e,t){let i=[],r=t.name?[t.name]:(await zr(e,e.changesDir,Ba)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a;try{a=await Mi(e,n)}catch(o){if(o instanceof ws)continue;i.push({severity:"error",code:"transition-invalid",message:`Native transition journal is invalid: ${o.message}`,path:Ue(e,n)});continue}if(a){if(t.repair&&t.recoveryStrategy==="continue"){try{if(!await zn([e],`doctor transition recovery ${n}`,async()=>await Zu([{paths:e,file:Ie.join(e.locksDir,"root-move.lock")},{paths:e,file:Ie.join(e.locksDir,`transition-${n}.lock`)}],i)?(await jk(e,n),!0):!1))continue;i.push({severity:"info",code:"transition-recovered",message:`Continued Native phase transition ${a.id} for ${n}`,path:Ue(e,n)})}catch(o){i.push({severity:"error",code:"transition-recovery-failed",message:`Native transition recovery failed: ${o.message}`,path:Ue(e,n)})}continue}i.push({severity:"error",code:"transition-incomplete",message:t.repair&&t.recoveryStrategy==="rollback"?`Native phase transition ${a.id} only supports deterministic continue recovery`:`Native phase transition ${a.id} is incomplete for ${n}`,path:Ue(e,n),repair:"continue"})}}return i}async function jM(e,t){let i=[],r=t.name?[t.name]:(await zr(e,e.changesDir,Ba)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=$r(e,n),o;try{o=await Or(e,n)}catch(s){if(s.code==="ENOENT")continue;i.push({severity:"error",code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}`,path:a});continue}if(o){if(!t.repair){i.push({severity:"error",code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${o.id} is incomplete for ${n}`,path:a});continue}try{if(!await zn([e],`doctor checkpoint recovery ${n}`,async()=>await Zu([{paths:e,file:Ie.join(e.locksDir,"root-move.lock")},{paths:e,file:Ie.join(e.locksDir,`transition-${n}.lock`)}],i)?(await zk(e,n),!0):!1))continue;i.push({severity:"info",code:"checkpoint-progress-recovered",message:`Continued Native progress checkpoint ${o.id} for ${n}`,path:a})}catch(s){i.push({severity:"error",code:"checkpoint-progress-recovery-failed",message:`Native progress checkpoint recovery failed: ${s.message}`,path:a})}}}return i}async function Ms(e){let t=e.repair??!1,i=[],r=e.paths,n;try{n=await ye(r.projectRoot)}catch(c){return{healthy:!1,findings:[{severity:"error",code:"config-invalid",message:`Comet project config is invalid: ${c.message}`,path:r.configFile}]}}let a=!!n?.native.pending_root_move;if(n?.native.pending_root_move){let c=n.native.pending_root_move,[l,u]=await Promise.all([qe(r.projectRoot,c.fromArtifactRoot),qe(r.projectRoot,c.toArtifactRoot)]);if(t&&e.recoveryStrategy)try{if(!await Zu([{paths:l,file:Ie.join(l.locksDir,"root-move.lock")},{paths:u,file:Ie.join(u.locksDir,"root-move.lock")}],i))return{healthy:!1,findings:i};let f=await PE({projectRoot:r.projectRoot,strategy:e.recoveryStrategy});r=await qe(r.projectRoot,f.config.native.artifact_root),a=!1,i.push({severity:"info",code:"root-move-recovered",message:`${e.recoveryStrategy==="continue"?"Continued":"Rolled back"} Native root move ${c.id}`})}catch(d){return i.push({severity:"error",code:"root-move-recovery-failed",message:`Native root recovery failed: ${d.message}`}),{healthy:!1,findings:i}}else i.push({severity:"error",code:"root-move-incomplete",message:`Native root move ${c.id} is ${c.stage}; inspect ${l.nativeRoot} and ${u.nativeRoot}`,repair:e.recoveryStrategy??"continue"})}let o=await EM(r);if(i.push(...o),o.length>0)return{healthy:!1,findings:i};let s=await PM(r,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy});return i.push(...s.findings),e.projectOnly||(i.push(...await AM(r,{name:e.name,repair:t})),i.push(...await TM(r,{name:e.name,repair:t})),i.push(...await _M(r,{name:e.name,repair:t})),i.push(...await xM(r,{name:e.name,repair:t})),i.push(...await IM(r,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy})),i.push(...await jM(r,{name:e.name,repair:t})),i.push(...await wE({paths:r,name:e.name,repair:t,now:e.now,deferAll:a||s.unfinished.length>0}))),i.push(...await RM(r,t,s.unfinished)),i.push(...await SM(r,t)),e.projectOnly||i.push(...await CM(r,e.name,n?.native.max_verify_failures??5)),{healthy:i.every(c=>c.severity==="info"),findings:i}}import{randomUUID as $M}from"node:crypto";import{promises as Me}from"node:fs";import ht from"node:path";var Am=class extends Error{peers;constructor(t){super(t.length===0?"Native Archive serial capability decision is stale":`Native Archive requires a serial capability decision: ${t.join(", ")}`),this.name="NativePortableArchiveOrderRequiredError",this.peers=[...t]}};function RE(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function CE(e,t){if(!/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error("Native portable Archive ref is invalid");let i=ht.join(e.archiveDir,t);if(!O(e.archiveDir,i))throw new Error("Native Archive path escaped");return i}async function ed(e){try{return await Me.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function xE(e,t){let i=ht.normalize(ht.resolve(e)),r=ht.normalize(ht.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}async function OM(e,t){let i;try{i=await Me.readdir(e.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return null;throw n}let r=[];for(let n of i){if(!n.isDirectory()||n.isSymbolicLink())continue;let a=ht.join(e.archiveDir,n.name);try{let o=await Ze(ht.join(a,"comet-state.yaml"));o.name===t&&r.push({dir:a,state:o})}catch{}}if(r.length>1)throw new Error(`Multiple Native portable archives exist for ${t}`);return r[0]??null}async function HM(e,t){let i=await bl(e,{kind:"archive",change:t});return i?.kind==="archive"?i.journal:null}async function Sn(e,t){await Me.mkdir(e.transactionsDir,{recursive:!0}),await ee(mr(e,{kind:"archive",change:t.change}),t,{containedRoot:e.runtimeDir})}async function DM(e){let t=new Set(e.state.spec_changes.map(({capability:a})=>a));if(t.size===0)return[];let i=Jt(e.paths.projectRoot);i.some(a=>xE(a,e.paths.projectRoot))||i.push(e.paths.projectRoot);let r=[];for(let a of i){let o=await ye(a);if(!o)continue;let s=await qe(a,o.native.artifact_root);r.some(c=>xE(c.changesDir,s.changesDir))||r.push(s)}r.length===0&&r.push(e.paths);let n=new Set;for(let a of r){let o;try{o=await Me.readdir(a.changesDir,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of o)if(!(!s.isDirectory()||s.isSymbolicLink()||s.name===e.state.name))try{let c=await Ze(ht.join(a.changesDir,s.name,"comet-state.yaml"));c.status!=="done"&&c.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.name)}catch{let c=await Xl(a,s.name).catch(()=>null);c?.state&&c.state.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.state.name)}}return[...n].sort((a,o)=>a.localeCompare(o,"en"))}function LM(e){if(e===void 0)return null;if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error("Native Archive serial capability decision is invalid");return e}async function MM(e){let t=ht.join(e.paths.specsDir,e.change.capability),i=ht.join(t,"spec.md");if(!O(e.paths.specsDir,i))throw new Error("Native canonical spec path escaped");if(e.change.operation==="remove"){let n;try{n=await Me.lstat(e.paths.specsDir)}catch(c){if(c.code==="ENOENT")return;throw c}if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native canonical specs root is unsafe");let a;try{a=await Me.lstat(t)}catch(c){if(c.code==="ENOENT")return;throw c}if(!a.isDirectory()||a.isSymbolicLink())throw new Error(`Canonical Native capability directory is unsafe: ${e.change.capability}`);let[o,s]=await Promise.all([Me.realpath(e.paths.specsDir),Me.realpath(t)]);if(!O(o,s))throw new Error("Native canonical capability path escaped");try{let c=await Me.lstat(i);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await Me.unlink(i)}catch(c){if(c.code!=="ENOENT")throw c}await Me.rmdir(t).catch(c=>{if(c.code!=="ENOENT"&&c.code!=="ENOTEMPTY")throw c});return}if(e.change.source===null||e.change.content===null)throw new Error(`Native ${e.change.operation} spec requires frozen source content`);let r=ht.join(Lt(e.paths,e.state.name),e.change.source);await he(r,e.change.content,{containedRoot:e.paths.nativeRoot}),await Me.mkdir(t,{recursive:!0}),await he(i,e.change.content,{containedRoot:e.paths.nativeRoot})}function AE(e){if(e.phase!=="archive"||e.status!=="active"||e.loop.stage!=="archive-ready"||e.verification_result!=="pass"||e.verification?.verdict!=="pass"||e.verification_report!=="verification.md")throw new Error(`Native change ${e.name} is not archive-ready`)}async function FM(e,t){let i=Lt(e,t.name),r=[];for(let n of t.spec_changes){if(n.source===null){r.push({...n,content:null});continue}let a=await Z({root:i,ref:n.source,maxBytes:null,includeHash:!1});r.push({...n,content:a.text})}return r}function BM(e,t){if(t.archived){if(t.status!=="done"||t.loop.stage!=="done"||t.state_version!==e.start_state_version+1)throw new Error("Native Archive transaction no longer matches the finalized portable state");return}if(t.state_version!==e.start_state_version)throw new Error("Native Archive transaction is stale for the current portable state");if(AE(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function _m(e){return se(e.paths,`archive portable change ${e.name}`,async()=>{let t=LM(e.serialFirstChange);if(t!==null&&t!==e.name)throw new Error("Native Archive --serial-first must name the change being archived");let i=await HM(e.paths,e.name),r=Lt(e.paths,e.name),n=await ed(r),a=n?null:await OM(e.paths,e.name),o;if(n)o=await $a(e.paths,e.name);else if(i)o=await Ze(ht.join(CE(e.paths,i.archive_ref),"comet-state.yaml"));else if(a)o=a.state;else throw new Error(`Native active change is missing: ${e.name}`);let s=await Mr(e.paths,e.name);if(n&&!o.archived&&i===null){let d=await VS({paths:e.paths,state:o});if(d.drifted){let f=d.reason??"Native confirmed requirements changed";throw await qS({paths:e.paths,state:o,reason:f}),new Error(`${f}; Native change returned to Shape and requires confirmation`)}}let c=CE(e.paths,i?.archive_ref??RE(o)),l=await ed(c);if(i&&BM(i,o),n&&l)throw new Error("Native active and archive directories both exist; doctor intervention is required");if(!n&&!i&&a){if(!o.archived||o.status!=="done"||o.loop.stage!=="done")throw new Error("Native archive exists without a completed portable state");return await Ts(e.paths,o.name),await Me.rm(We(e.paths,o.name),{recursive:!0,force:!0}),{change:o.name,archiveDir:a.dir,transactionId:`recovered-${o.state_version}`,state:o}}if(!i){if(!o.archived)AE(o);else if(o.status!=="done"||o.loop.stage!=="done")throw new Error("Native active archived state is inconsistent");let d=await DM({paths:e.paths,state:o});if(!o.archived&&d.length>0&&t!==o.name)throw new Am(d);i={schema:Nl,id:$M(),change:o.name,start_state_version:o.archived?o.state_version-1:o.state_version,archive_ref:RE(o),status:o.archived?"state-finalized":"prepared",next_spec_index:o.archived?o.spec_changes.length:0,spec_changes:await FM(e.paths,o),created_at:new Date().toISOString()},await Sn(e.paths,i)}if(!n&&l&&i.status==="report-aligned")i={...i,status:"moved"},await Sn(e.paths,i);else if(!n&&l&&i.status!=="moved")throw new Error(`Native Archive layout contradicts transaction state ${i.status}; doctor intervention is required`);let u=!1;if(i.status==="prepared"&&s&&!o.archived&&(s=(await Ps({paths:e.paths,state:s})).state,u=!0),i.status==="prepared"){for(let d=i.next_spec_index;d<i.spec_changes.length;d+=1)await MM({paths:e.paths,state:o,change:i.spec_changes[d]}),i={...i,next_spec_index:d+1},await Sn(e.paths,i),await e.hooks?.afterSpecApplied?.(d);i={...i,status:"specs-applied"},await Sn(e.paths,i)}if(i.status==="specs-applied"){if(s&&!o.archived&&!u&&(s=(await Ps({paths:e.paths,state:s})).state,u=!0),!o.archived){let d={...o,phase:"archive",status:"done",state_version:o.state_version+1,archived:!0,blockers:[],loop:{...o.loop,stage:"done",next_action:null}};o=await nn({file:Pt(e.paths,o.name),expectedStateVersion:o.state_version,next:d,containedRoot:e.paths.nativeRoot})}i={...i,status:"state-finalized"},await Sn(e.paths,i),await e.hooks?.afterFinalState?.()}if(i.status==="state-finalized"){let d=await ed(r)?r:c;if(await Du({file:ht.join(d,"verification.md"),state:o,...s?{supervisor:s}:{}}),await Hu({file:ht.join(d,"verification.md"),stateVersion:o.state_version})!=="aligned")throw new Error("Native final verification report is not aligned");i={...i,status:"report-aligned"},await Sn(e.paths,i),s&&!u&&(await Ps({paths:e.paths,state:s}),u=!0),await e.hooks?.afterReportAligned?.()}if(i.status==="report-aligned"){if(s&&!u&&await Ps({paths:e.paths,state:s}),await Me.mkdir(e.paths.archiveDir,{recursive:!0}),await ed(c))throw new Error(`Native Archive target already exists: ${c}`);await Me.rename(r,c),i={...i,status:"moved"},await Sn(e.paths,i),await e.hooks?.afterMove?.()}return i.status==="moved"&&(await Ts(e.paths,o.name),await Me.rm(We(e.paths,o.name),{recursive:!0,force:!0}),await e.hooks?.afterRuntimeCleanup?.(),await Me.rm(mr(e.paths,{kind:"archive",change:o.name}),{force:!0})),{change:o.name,archiveDir:c,transactionId:i.id,state:o}},{allowedPortableTransaction:{kind:"archive",change:e.name}})}function En(e,t,i){return e.language==="zh-CN"?i:t}function VM(e,t){let i=r=>({required:!1,message:null,suggestedReply:null,agentInstruction:r});if(t&&e.phase==="shape"&&e.status==="active")return{required:!0,message:En(e,"This Supervisor Change has multiple independent children. Choose one coordination mode before confirming Shape: A) Multi-session coordination (recommended), or B) Single-session progression.","当前 Supervisor Change 包含多个可独立执行的 Child。确认 Shape 前请选择推进方式:A)多会话协作(推荐),或 B)单会话推进。"),suggestedReply:En(e,"Reply A or B","回复 A 或 B"),agentInstruction:En(e,"Relay the two coordination choices and wait for the user decision. Do not treat a generic confirmation as a mode selection or run --confirmed without --coordination-mode.","转述这两个推进方式并等待用户选择。不要把普通“确认”视为已选择推进方式,也不要在没有 --coordination-mode 时运行 --confirmed。")};if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready")return i(En(e,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result")return i(En(e,"Wait only while the dispatched Verifier task is still active. If it did not start, ended without a response, or is no longer available, immediately submit the matching verifier-unavailable or verifier-execution-error input. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","仅在已派发的独立验收任务仍在运行时等待。如果任务未启动、结束后没有返回结果或已经丢失,立即提交匹配的 verifier-unavailable 或 verifier-execution-error 输入。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。"));if(e.status==="blocked"&&e.blockers.some(({resolution_action:r})=>r==="retry-verifier"))return e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable")return e.language==="zh-CN"?{required:!0,message:"由于独立验收服务暂时不可用,目前只能完成自动检查。你可以选择接受当前检查结果,或者等验收服务恢复后再重试。",suggestedReply:null,agentInstruction:"向用户转述 message,并请用户明确选择是否接受只有自动检查的结果。不要把“继续”当作默认接受。"}:{required:!0,message:"Because independent verification is temporarily unavailable, only the automatic checks could be completed. You can accept the current check results or wait and retry when verification is available.",suggestedReply:null,agentInstruction:"Relay message and ask the user to explicitly choose whether to accept automatic checks only. Do not treat “Continue” as implicit acceptance."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="resolve-verifier-blocker")return e.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="await-user"){let n=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",a=n?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。",o=n?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return e.language==="zh-CN"?{required:!0,message:a,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:o,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}return i(En(e,"Follow the continuation action. Unless required is true, continue without asking the user to handle internal workflow state, and do not present machine fields as a user-facing explanation.","按 continuation 执行下一步。除非 required 为 true,否则继续推进,不要让用户处理内部工作流状态,也不要把机器字段作为面向用户的说明。"))}function Im(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function td(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function _E(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function qM(e,t,i){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...i]}}function WM(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function zM(e){return["comet","native","next",e.change,"--summary","<summary>",...e.coordinationRequired?["--coordination-mode","<coordination-mode>"]:[],"--confirmed","--expected-state-version",String(e.stateVersion),"--expected-action","confirm-shape"]}function Fs(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:Im({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[td("summary","--summary"),_E(e.name,e.flag)]}}function Tm(e){return[Fs({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Fs({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function id(e,t){let i=WM(t)&&e.coordination_mode===void 0,r={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],userCommunication:VM(e,i)},n=a=>({kind:a,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...r,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:n("none")};if(e.status==="await-user")return e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...r,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[td("summary","--summary")],commandAlternatives:[Fs({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...Tm({change:e.name,stateVersion:e.state_version})],runnerAction:n("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...r,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:Im({change:e.name,stateVersion:e.state_version,action:"confirm-verifier-unavailable",flag:"--confirmed"}),requiredInputs:["summary","user-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:n("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...r,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[td("summary","--summary")],commandAlternatives:[Fs({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...Tm({change:e.name,stateVersion:e.state_version})],runnerAction:n("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...r,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[td("summary","--summary")],commandAlternatives:Tm({change:e.name,stateVersion:e.state_version}),runnerAction:n("none")}:{...r,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:n("none")};if(e.status==="blocked"){let a=e.blockers.some(({resolution_action:o})=>o==="retry-verifier");return{...r,disposition:"blocked",action:a?"retry-verifier":"none",commandArgs:a?Im({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:a?["summary"]:["repair-runtime"],inputOptions:a?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:n(a?"retry-verifier":"none")}}if(e.phase==="shape")return{...r,disposition:i?"await-user":"continue",action:"confirm-shape",commandArgs:zM({change:e.name,stateVersion:e.state_version,coordinationRequired:i}),requiredInputs:["summary",...i?["coordination-choice"]:[],"shared-understanding-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},...i?[qM("coordination-mode","--coordination-mode",Hy)]:[],_E("confirmed","--confirmed")],runnerAction:n("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...r,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:n("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...r,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:n("none")};if(t.allDone)return{...r,disposition:"continue",action:"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:n("builder-handoff")};let a=t.children.some(({status:s})=>s==="blocked"||s==="needs-reverify"),o=t.children.some(({status:s})=>s==="ready"||s==="active");return{...r,disposition:a&&!o?"blocked":"continue",action:"advance-children",commandArgs:null,requiredInputs:a&&!o?["resolve-child-blocker"]:["ready-children"],inputOptions:[],runnerAction:n("none")}}return{...r,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:n("builder-handoff")}}if(e.phase==="verify"){let a=e.loop.next_action==="await-verifier-result",o=!!e.children_contract_hash,s={id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0};return{...r,userCommunication:!a&&o?{...r.userCommunication,agentInstruction:`${r.userCommunication.agentInstruction} ${En(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:r.userCommunication,disposition:"continue",action:a?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[a?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:a?[{kind:"verifier-response",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[s]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:[{id:"<acceptance-id>",result:"<passed|failed|blocked>",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:o?[s]:[]}}],runnerAction:n(a?"await-verifier":"dispatch-verifier")}}return e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived?{...r,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],commandAlternatives:[Fs({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:n("none")}:{...r,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:n("none")}}import{randomUUID as JM}from"node:crypto";import{promises as Va}from"node:fs";import DE from"node:path";var jm=["evidence.md","repair.md","archive.md","checkpoint.md"],GM="verification.md";async function UM(e){try{return await Va.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function $m(e,t){let i=ne(e,t),r=[mr(e,{kind:"migration",change:t}),tn(e,t),...jm.map(n=>DE.join(i,n))];return(await Promise.all(r.map(UM))).some(Boolean)}async function KM(e,t){let i=await bl(e,{kind:"migration",change:t});return i?.kind==="migration"?i.journal:null}async function TE(e,t){await Va.mkdir(e.transactionsDir,{recursive:!0}),await ee(mr(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function IE(e,t,i={}){let r=i.removeVerificationReport===!1?jm:[...jm,GM];await Promise.all([Va.rm(We(e,t),{recursive:!0,force:!0}),Va.rm(tn(e,t),{recursive:!0,force:!0}),...r.map(n=>Va.rm(DE.join(ne(e,t),n),{force:!0}))])}async function jE(e,t){await Fr(Nn(e,t.name),yn({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function $E(e,t){try{let i=await kt(e,t);if(i?.schema==="comet.native.workspace.v3")return{isolation:i.isolation,change_branch:i.changeBranch,target_branch:i.targetBranch,finish:i.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function OE(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let i=fe(e.projectRoot);if(!i.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(i.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${i.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!i.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function YM(e){let t=ne(e.paths,e.state.name),i=await Z({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),r=[];for(let n of e.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await Z({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return hl({briefMarkdown:i.text,specs:r})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function HE(e,t){let i=await Xl(e,t);if(!i.state)throw new Error(`Native legacy change ${t} is unreadable`);return i.state}async function Bs(e){return se(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await KM(e.paths,e.name),i=await qr(e.paths,e.name)?await Ze(Pt(e.paths,e.name)):null;if(!t&&i)return await IE(e.paths,e.name,{removeVerificationReport:!1}),await jE(e.paths,i),i;let r=null,n=null;for(t||(r=await HE(e.paths,e.name),n=await $E(e.paths,e.name),OE(e.paths,n),t={schema:yl,id:JM(),change:r.name,fromSchema:r.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await TE(e.paths,t));;){let a=My(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?i||(r??=await HE(e.paths,e.name),n??=await $E(e.paths,e.name),OE(e.paths,n),i=Ly({state:r,acceptance:await YM({paths:e.paths,state:r}),workspace:n,migratedAt:e.now}),await wl(Pt(e.paths,e.name),i,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await IE(e.paths,e.name):a.action==="commit-transaction"&&(i??=await Ze(Pt(e.paths,e.name)),await jE(e.paths,i)),t={...t,status:a.nextStatus},await TE(e.paths,t)}return await Va.rm(mr(e.paths,{kind:"migration",change:e.name}),{force:!0}),i??Ze(Pt(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as LE}from"node:fs";import ME from"node:path";function XM(e,t){let i=fe(e.projectRoot);if(t.workspace.change_branch!==null){if(!i.isGitWorktree)return"The portable change requires a Git branch/worktree";if(i.currentBranch!==t.workspace.change_branch)return`Expected Native change branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}`}return t.workspace.isolation==="current"?null:i.isGitWorktree?t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree?"The portable change requires its linked worktree":null:"The portable change requires a Git branch/worktree"}function QM(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function ZM(e,t,i){let r=new Date().toISOString(),n=e.verification===null?e:Yn(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:hr(t),completed_at:r});return ct({...n,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:i?QM(e):e.acceptance,verification:null,verification_result:"pending",verification_report:null,blockers:[],loop:{...e.loop,stage:"verify-ready",next_action:"run-required-checks-and-dispatch-verifier"}})}async function eF(e){try{let t=await Ou(e);return t===null?{local:null,reason:"missing"}:{local:t,reason:"available"}}catch(t){if(t.code&&t.code!=="ENOENT")throw t;return{local:null,reason:"invalid"}}}async function FE(e){return se(e.paths,`recover portable change ${e.name}`,async()=>{let t=await $a(e.paths,e.name);if(t.status==="done")return await Lu({paths:e.paths,state:t}),{state:t,local:null,action:"done",reason:"done",message:"Archived Native changes do not require a local execution overlay."};let i=XM(e.paths,t);if(i)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:i};let r=Nn(e.paths,e.name),n=await eF(r),a=n.reason==="available"&&(n.local?.change!==t.name||n.local?.basedOnStateVersion!==t.state_version)?"stale":n.reason;if(a==="available"&&!e.preserveRunningExecution&&n.local?.execution!==null&&n.local?.execution?.status!=="completed"&&n.local&&(a="interrupted",n.local.execution?.status==="running"&&(n.local={...n.local,execution:{...n.local.execution,status:"interrupted"},checks:n.local.checks.map(f=>f.status==="planned"||f.status==="running"?{...f,status:"interrupted"}:f)},await Fr(r,n.local,{containedRoot:e.paths.runtimeDir}))),a==="available")return await Lu({paths:e.paths,state:t}),{state:t,local:n.local,action:"resume-stable-boundary",reason:a,message:"Native local execution overlay matches the portable state."};let s=a==="interrupted"?n.local?.checks.find(f=>f.status==="interrupted"&&!f.repeatable):void 0;if(s){let f=um({state:t,reason:`Check ${s.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await nn({file:Pt(e.paths,t.name),expectedStateVersion:t.state_version,next:f,containedRoot:e.paths.nativeRoot}),await LE.rm(ME.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let h=yn({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await Fr(r,h,{containedRoot:e.paths.runtimeDir}),{state:t,local:h,action:"resume-stable-boundary",reason:a,message:`Native check ${s.id} was not repeatable; the change returned to Build for a new candidate.`}}let c=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",l=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",u=c||l;if(u){let f=ZM(t,l?"Local Runtime was unavailable at Archive ready; the synchronized implementation must be verified again.":"The previous Verifier execution was unavailable; dispatch a new attempt from the stable Verify boundary.",l);t=await nn({file:Pt(e.paths,t.name),expectedStateVersion:t.state_version,next:f,containedRoot:e.paths.nativeRoot})}let d=yn({portableState:t,projectRoot:e.paths.projectRoot,branch:fe(e.paths.projectRoot).currentBranch});return await LE.mkdir(ME.dirname(Nn(e.paths,t.name)),{recursive:!0}),await Fr(r,d,{containedRoot:e.paths.runtimeDir}),await Lu({paths:e.paths,state:t}),{state:t,local:d,action:u?"reverify":"resume-stable-boundary",reason:a,message:u?"Rebuilt local execution from the portable boundary; previous pass/execution was not reused.":`Rebuilt local execution from the portable ${t.phase}/${t.loop.stage} boundary.`}})}import{promises as VE}from"node:fs";import iF from"node:path";function tF(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function BE(e){let t=e.acceptance.reduce((i,r)=>({...i,[r.result]:i[r.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0});return{schema:"comet.native.state-summary.v1",name:e.name,phase:e.phase,status:e.status,state_version:e.state_version,...e.coordination_mode===void 0?{}:{coordination_mode:e.coordination_mode},loop:e.loop,acceptance:t,unresolved_acceptance_ids:e.acceptance.filter(({result:i})=>i==="failed"||i==="blocked").map(({id:i})=>i),verification_result:e.verification_result,blockers:e.blockers.slice(0,8).map(i=>({owner:i.owner,reason:tF(i.reason.text),acceptance_ids:i.acceptance_ids,resolution_action:i.resolution_action})),workspace:{isolation:e.workspace.isolation,change_branch:e.workspace.change_branch,target_branch:e.workspace.target_branch,finish:e.workspace.finish},archived:e.archived}}function rF(e,t,i){return`native-details-v2.${e}.${t}.${i.toString(36)}`}function nF(e,t,i){if(!e)return 0;let r=/^native-details-v2\.(\d+)\.(\d+)\.([0-9a-z]+)$/u.exec(e);if(!r||Number(r[1])!==t||Number(r[2])!==i)throw new Error("Native details cursor is stale or invalid");let n=Number.parseInt(r[3],36);if(!Number.isSafeInteger(n)||n<0)throw new Error("Native details cursor offset is invalid");return n}function aF(e,t,i){return[...e.acceptance.map(r=>({kind:"acceptance",value:r})),...e.spec_changes.map(r=>({kind:"spec-change",value:r})),...e.builder_handoff?[{kind:"builder-handoff",value:e.builder_handoff}]:[],...e.verification?[{kind:"verification",value:e.verification}]:[],...e.history.map(r=>({kind:"history",value:r})),{kind:"history-overflow",value:e.history_overflow},{kind:"workspace",value:e.workspace},...e.verification_report?[{kind:"verification-report",value:e.verification_report}]:[],...t?[{kind:"supervisor-integration",value:{...t.integration,worktree:"<worktree>",targetCommit:"<redacted>",headCommit:"<redacted>"}},{kind:"supervisor-final-verification",value:t.finalVerification},...t.children.map(r=>({kind:"supervisor-child",value:cF(r,i)})),...t.history.map(r=>({kind:"supervisor-history",value:lF(r,i)}))]:[]]}function oF(e){return e.acceptance.reduce((t,i)=>({...t,[i.result]:t[i.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0})}function qE(e,t){let i=fe(e.projectRoot),r=null;return t.workspace.change_branch!==null&&(i.isGitWorktree?i.currentBranch!==t.workspace.change_branch&&(r=`Expected branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}.`):r="The Native change requires a registered Git worktree."),r===null&&t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree&&(r="The Native change requires its linked worktree."),{projectRoot:iF.resolve(e.projectRoot),isolation:t.workspace.isolation,bindingState:r===null?"aligned":"mismatch",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:r}}function sF(e,t){return[e.projectRoot,t.integration.worktree,...t.children.flatMap(i=>[i.projectRoot,i.task?.projectRoot])].filter(i=>!!i).map(i=>i.replaceAll("/","\\")).sort((i,r)=>r.length-i.length)}function rd(e,t){return e===null?null:t.reduce((i,r)=>i.replaceAll(r,"<worktree>").replaceAll(r.replaceAll("\\","/"),"<worktree>"),e)}function cF(e,t){return{...e,projectRoot:e.projectRoot?"<worktree>":null,baseCommit:e.baseCommit?"<redacted>":null,candidateCommit:e.candidateCommit?"<redacted>":null,verifiedCommit:e.verifiedCommit?"<redacted>":null,integrationCommit:e.integrationCommit?"<redacted>":null,blocker:rd(e.blocker,t),task:e.task?{...e.task,projectRoot:"<worktree>",baseCommit:"<redacted>",runId:"<redacted>"}:null}}function lF(e,t){return{...e,runId:e.runId?"<redacted>":null,summary:rd(e.summary,t)??""}}async function qa(e){let t=await WS(e),i=BE(t.state),r=t.state.status==="active"&&t.state.loop.stage!=="done",n=await Cs({paths:e.paths,state:t.state}),a=await Mr(e.paths,e.name),o=a?{...qE(e.paths,t.state),projectRoot:"."}:qE(e.paths,t.state),s=id(t.state,n),c=o.bindingState==="mismatch"?{...s,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["return-to-bound-workspace"],runnerAction:{...s.runnerAction,kind:"none"}}:s,l=a?sF(e.paths,a):[],u=a?(()=>{let h=a.children.filter(({status:y})=>y==="pending"||y==="ready").length,v=a.children.filter(({status:y})=>y==="active"||y==="verified").length,m=a.children.filter(({status:y})=>y==="integrated"||y==="archived").length,p=a.children.filter(({status:y})=>y==="blocked"||y==="needs-reverify").length,b=a.children.filter(({status:y})=>y==="active"||y==="blocked"||y==="needs-reverify").slice(0,16).map(y=>({name:y.name,summary:y.summary,projectRoot:y.task?.projectRoot??y.projectRoot?"<worktree>":null,reason:rd(y.blocker,l)})),g=a.children.flatMap(({blocker:y})=>{let E=rd(y,l);return E?[E]:[]}).slice(0,16);return{targetSpecs:t.state.spec_changes.length,implementationChildren:a.children.length,waiting:h,working:v,integrated:m,blocked:p,active:b,agents:{working:a.children.filter(({task:y})=>y!==null).length,completed:m},risks:g,nextAction:a.finalVerification.status==="passed"?"final-delivery":a.finalVerification.status==="pending"&&m===a.children.length?"parent-verification":h>0?"dispatch-ready-child":p>0?"resolve-blocker":"continue-supervisor"}})():null,d=e.details?(()=>{let h=a?.stateVersion??0,v=aF(t.state,a,l),m=nF(e.cursor,t.state.state_version,h),p=v.slice(m,m+32),b=m+p.length<v.length?rF(t.state.state_version,h,m+p.length):null;return{items:p,nextCursor:b,supervisorStateVersion:h}})():null,f=a?{schema:a.schema,parent:a.parent,integration:{branch:a.integration.branch,targetBranch:a.integration.targetBranch},finalVerification:{status:a.finalVerification.status,summary:a.finalVerification.summary},summary:u}:null;return{schema:"comet.native.status.v2",name:t.state.name,phase:t.state.phase,status:t.state.status,stateVersion:t.state.state_version,...t.state.coordination_mode===void 0?{}:{coordinationMode:t.state.coordination_mode},loop:t.state.loop,acceptance:oF(t.state),unresolvedAcceptanceIds:i.unresolved_acceptance_ids,verificationResult:t.state.verification_result,blockers:a?[]:i.blockers,workspace:o,localExecution:{status:r?t.localStatus:"not-expected",operation:t.localStatus==="available"?t.local?.execution??null:null},...n?{childSummary:n.children.reduce((h,v)=>({...h,[v.status]:(h[v.status]??0)+1}),{total:n.children.length}),readyChildren:n.readyChildren}:{},...f?{supervisor:f}:{},continuation:c,...e.details?{details:{stateVersion:t.state.state_version,...a?{supervisorStateVersion:d.supervisorStateVersion}:{},items:d.items,nextCursor:d.nextCursor,nextPageArgs:d.nextCursor?["comet","native","status",t.state.name,"--details","--cursor",d.nextCursor,"--json","--project-root",e.paths.projectRoot]:null}}:{}}}async function WE(e){let t;try{t=await VE.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}let i=[];for(let r of t)if(!(!r.isDirectory()||r.isSymbolicLink()))try{let n=await VE.readFile(`${Lt(e,r.name)}/comet-state.yaml`,"utf8");/^schema:\s*comet\.native\.v4\s*$/mu.test(n)&&i.push(r.name)}catch(n){if(n.code!=="ENOENT")throw n}return i.sort((r,n)=>r.localeCompare(n,"en"))}import Vs from"path";import{realpathSync as EF}from"fs";var Wi={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function zE(e){return e?e.command?`${Wi.next} ${e.command}`:e.ask_user?`${Wi.next} ${e.ask_user}`:null:null}function JE(e,t){let i=[e.summary],r=zE(e.next);return r&&i.push(r),e.user_message&&i.push("",Wi.relay,e.user_message),t!==void 0&&i.push("",Wi.details,JSON.stringify(t,null,2)),`${i.join(`
263
+ ${Vr(e.verification.summary)}
264
+ `}function ZD(e){let t=/^---\r?\ngenerated_from_state_version: ([1-9]\d*)\r?\n---(?:\r?\n|$)/u.exec(e);if(!t)return null;let i=Number(t[1]);return Number.isSafeInteger(i)?i:null}async function Vu(e){let t;try{t=await UD.readFile(e.file,"utf8")}catch(r){if(r.code==="ENOENT")return"missing";throw r}let i=ZD(t);return i===null?"invalid":i===e.stateVersion?"aligned":"stale"}async function qu(e){await he(e.file,QD(e.state,e.supervisor))}var VS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,eL="comet-state.yaml",tL="state.json",jY=Xs("en");function Lt(e,t){if(!VS.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=qr.join(e.changesDir,t);if(!O(e.changesDir,i))throw new Error("Native change path escaped");return i}function Pt(e,t){return qr.join(Lt(e,t),eL)}function Wr(e,t){return qr.join(We(e,t),tL)}async function zr(e,t){try{let i=await Sn.readFile(Pt(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}function qS(e){return fe(e).currentBranch}async function En(e,t){return Ze(Pt(e,t))}async function WS(e){let t=await sn({file:Pt(e.paths,e.previous.name),expectedStateVersion:e.previous.state_version,next:e.next,containedRoot:e.paths.nativeRoot});if(t.verification===null&&t.verification_report===null){let i=qr.join(Lt(e.paths,t.name),"verification.md");await T(e.paths.nativeRoot,i),await Sn.rm(i,{force:!0})}return t}async function iL(e){let t=Lt(e.paths,e.state.name),i=qr.join(t,"specs"),r=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await Sn.readdir(i,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,c)=>s.name.localeCompare(c.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!VS.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(r.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,c=qr.join(t,...s.split("/")),l=await Sn.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=qr.join(e.paths.specsDir,o.name,"spec.md"),d="create";try{let f=await Sn.lstat(u);if(!f.isFile()||f.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);d="modify"}catch(f){if(f.code!=="ENOENT")throw f}a.push({capability:o.name,operation:d,source:s})}return a.push(...r.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function rL(e){let t=Lt(e.paths,e.state.name),i=await Z({root:t,ref:"brief.md",maxBytes:null,includeHash:!1}),r=[];for(let n of e.specChanges){if(n.source===null)continue;let a=await Z({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}return yl({briefMarkdown:i.text,specs:r})}async function zS(e){let t=await iL(e),i=e.ignoreSpecOperationFor??(e.state.children_contract_hash?new Set(e.state.spec_changes.map(({capability:c})=>c)):void 0);if(!(t.length===e.state.spec_changes.length&&t.every((c,l)=>{let u=e.state.spec_changes[l];return u!==void 0&&c.capability===u.capability&&c.source===u.source&&(c.operation===u.operation||i?.has(c.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n=await rL({...e,specChanges:t}),a=e.state.acceptance.map(({source:c,text:l})=>({source:c,text:l}));if(!Hy(a,n))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let o;try{o=await um({changeDir:Lt(e.paths,e.state.name),acceptanceIds:n.map(({id:c})=>c),validation:lm({...e.state,acceptance:n})})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return(o?dm({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 JS(e){let t=await En(e.paths,e.name),i=await Ei(e.paths,e.name),r=await ia(e.paths,{kind:"archive",change:e.name}),n=r?.kind==="archive"?r:null;if(n&&i?.finalVerification.status==="pending"){if(n.journal.status!=="prepared"||n.journal.next_spec_index!==0)throw new Error("Native Supervisor final verification changed after Archive applied side effects; doctor intervention is required");if(t.phase==="verify"&&t.status==="active"&&t.verification===null&&t.verification_result==="pending"&&t.loop.stage==="verify-ready")return await Sn.rm(n.file,{force:!0}),{state:t,action:"rerun-final-verification"}}if(t.archived||t.verification===null||t.verification_result!=="pass"||i?.finalVerification.status!=="pending")return{state:t,action:"none"};let a=RS(i);if(n||a.stateVersion!==i.stateVersion){let o=await nL({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 Sn.rm(n.file,{force:!0}),{state:o,action:"rerun-final-verification"}}return await kn(e.paths,CS(i,t)),{state:t,action:"recorded-final-verification"}}async function GS(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let r={...on(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:Ii(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"confirm-shape"}};delete r.children_contract_hash;let n=await WS({paths:e.paths,previous:t,next:r});return await qi(Wr(e.paths,t.name),Br({portableState:n,projectRoot:e.paths.projectRoot,branch:qS(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function nL(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);if(t.verification===null||t.verification_result!=="pass")throw new Error("Native Supervisor recovery requires a persisted final verification pass");let r={...on(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:Ii(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 WS({paths:e.paths,previous:t,next:r});return await qi(Wr(e.paths,t.name),Br({portableState:n,projectRoot:e.paths.projectRoot,branch:qS(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function Wu(e){if(e.state.verification===null)return"not-applicable";let t=qr.join(Lt(e.paths,e.state.name),"verification.md");return await Vu({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await qu({file:t,state:e.state}),"rebuilt")}async function US(e){let t=await En(e.paths,e.name),i=Wr(e.paths,e.name);try{let r=await Bu(i);return r===null?{state:t,local:null,localStatus:"missing"}:r.change!==t.name||r.basedOnStateVersion!==t.state_version?{state:t,local:null,localStatus:"stale"}:{state:t,local:r,localStatus:"available"}}catch(r){return r.code==="ENOENT"?{state:t,local:null,localStatus:"missing"}:{state:t,local:null,localStatus:"invalid"}}}var BY=16*1024;async function zu(e){let t=await tm(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(Zl(t.selection.change),t.selection)}function KS(e){return _u(e.projectRoot)}async function $s(e,t){return await Yn(e.projectRoot),gS(e.projectRoot,"native",t)}var v4=16*1024*1024,Ju=class extends Error{constructor(i,r,n,a){super(`Canonical spec conflict for ${i}: expected ${r??"(missing)"}, actual ${n??"(missing)"}`);this.capability=i;this.expectedHash=r;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},Os=class extends Error{constructor(i,r=i.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${i.findingCodes.join(", ")}`){super(r);this.preflight=i;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};function XS(e,t){let i=t.operations.find(r=>r.id==="archive-change");if(!i||i.type!=="move")throw new Error(`Archive transaction ${t.id} has no archive move`);return Fa.resolve(e.nativeRoot,...i.target.split("/"))}async function QS(e,t,i){let r=await kr(e,t.id);if(r.some(p=>p.type==="archive-finalized"))return;let n=r.some(p=>p.type==="archive-finalization-started");if(t.schema==="comet.native.transaction.v2"&&!n){let p=t.operations.find(g=>g.id==="archive-change");if(!p||p.type!=="move"||!p.expectedSourceHash)throw new Error(`Archive transaction ${t.id} has no content-bound archive move`);let b=await ai(XS(e,t));if(b?.kind!=="directory"||b.hash!==p.expectedSourceHash)throw new Error(`Native Archive content changed before finalization for transaction ${t.id}`)}let a=XS(e,t),o=Fa.join(a,Ie),s=await fb(o);if(!t.change||s.name!==t.change)throw new Error(`Archive transaction ${t.id} change mismatch`);let c=H(e,s.name),l=await Oe(c);if(!l||l.runId!==s.run_id||l.currentStep!=="archive"&&!(l.currentStep===null&&l.status==="completed"))throw new Error(`Native archive Run state is missing or inconsistent for ${s.name}`);let u=l;if(l.currentStep==="archive"){let p=Km(Ni,l,new Set,_p,void 0);if(!p.action)throw new Error(p.reason??"Native archive produced no action");u=Ym(Ni,p.state,{actionId:p.action.id,status:"succeeded",summary:`Archived Native change ${s.name}`},_p,void 0)}let d=L(`archive:${t.id}:${s.name}`),f=await it(c,u.trajectoryRef),h=f.filter(p=>p.data.transactionId===t.id);if(t.schema==="comet.native.transaction.v2"&&(h.length>1||h.some(p=>p.type!=="state_transitioned")))throw new Error(`Native Archive trajectory has a transaction id collision: ${t.id}`);let v=h.find(p=>p.type==="state_transitioned"),m={previousPhase:"archive",nextPhase:null,evidenceHash:d,summary:`Archived Native change ${s.name}`,transactionId:t.id};if(v&&t.schema==="comet.native.transaction.v2"&&(!aL(v.data,m)||v.runId!==u.runId||v.timestamp!==t.createdAt||v!==f.at(-1)))throw new Error(`Native Archive trajectory event changed for transaction ${t.id}`);if(!n&&(s.archived||l.currentStep===null||h.length>0))throw new Error(`Native Archive finalization state changed before its irreversible marker: ${t.id}`);if(n||(t.schema==="comet.native.transaction.v2"?(await Au(e,t,"archive-finalization-started"),await i?.afterFinalizationStarted?.(t)):await sa(e,t,"archive-finalization-started")),!s.archived){let p={...s,archived:!0};await db(o,p)}v||(v=await jr({changeDir:c,run:u,type:"state_transitioned",data:m,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}})),await yn({changeDir:c,run:u,trajectoryOffset:v.sequence,evidenceHash:d,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}}),await hn(c,u),await $s(e,s.name),t.schema==="comet.native.transaction.v2"?await Au(e,t,"archive-finalized"):await sa(e,t,"archive-finalized")}async function vm(e,t){let i=We(e,t);try{let r=await YS.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`Native Runtime cleanup target is not a real directory: ${i}`);return await T(e.runtimeDir,i),await YS.rm(i,{recursive:!0,force:!0}),null}catch(r){return r.code==="ENOENT"?null:`Archived change ${t}, but local Runtime cleanup failed: ${r.message}`}}async function oL(e,t,i){if(t.schema==="comet.native.transaction.v2"){if(!(await kr(e,t.id)).some(c=>c.type==="operation-started")){let c=await Pu({paths:e,name:t.change,now:new Date(t.createdAt)});if(!c.ready||c.preflightHash!==t.preflightHash)throw new Os(c,"Native Archive facts changed before the first transaction operation")}let o=await hS(e,t,{...i,beforeArchiveChangeMove:async c=>{await i?.beforeArchiveChangeMove?.(c);let l=await De(e,t.change),u=await Eu({paths:e,state:l,now:new Date(t.createdAt)});if(l.phase!=="archive"||l.archived||l.verification_result!=="pass"||!["complete","partial"].includes(u.freshness)||u.findingCodes.length>0)throw new Error(`Native Archive verification freshness changed before moving ${t.change}: ${u.findingCodes.join(", ")||u.freshness}`)}});await QS(e,o,i);let s=await Au(e,o,"commit");return{journal:s,runtimeCleanupWarning:await vm(e,s.change)}}let r=await sN(e,t);await QS(e,r,i);let n=await sa(e,r,"commit");return{journal:n,runtimeCleanupWarning:n.change?await vm(e,n.change):null}}function sL(e,t){if(t.kind!=="archive")throw new Error(`Transaction ${t.id} is not an archive`);if(t.schema==="comet.native.transaction.v2"){if(!t.change)throw new Error(`Archive transaction ${t.id} has no change`);return}if(Fa.resolve(t.projectRoot)!==Fa.resolve(e.projectRoot)||Fa.resolve(t.nativeRoot)!==Fa.resolve(e.nativeRoot))throw new Error(`Transaction ${t.id} belongs to a different Native root`)}async function ZS(e){return se(e.paths,`recover archive ${e.transactionId}`,async()=>{let t=await pr(e.paths,"archive",`recover archive ${e.transactionId}`);try{let i=await yt(e.paths,e.transactionId),r=i.schema==="comet.native.transaction.v2"?await Zp(e.paths,e.transactionId):i;return sL(e.paths,r),r.status==="committed"?(r.change&&await vm(e.paths,r.change),r):r.status==="rolled-back"?r:e.strategy==="continue"?(await oL(e.paths,r)).journal:r.schema==="comet.native.transaction.v2"?pS(e.paths,r):Ol(e.paths,r)}finally{await mr(t)}},{allowedTransactionId:e.transactionId})}import{promises as kL}from"fs";async function eE(e,t){let i=[],r=H(e,t.name),n=fr(r,Nt.stateRef),a;try{a=await Oe(r)}catch(u){return[{code:"run-state-invalid",message:`Native Run state is invalid: ${u.message}`,path:n}]}if(!a)return(t.run_id!==null||t.phase!=="shape")&&i.push({code:"run-state-missing",message:"Native change references a missing Run state",path:n}),i;if(t.run_id===null)return[{code:"run-state-unexpected",message:"Native change has a Run state but no run_id",path:n}];a.runId!==t.run_id&&i.push({code:"run-id-mismatch",message:`Native Run id ${a.runId} does not match change run_id ${t.run_id}`,path:n}),(a.pending||a.status==="waiting")&&i.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:n}),a.currentStep!==t.phase&&i.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:n});let o=fr(r,a.trajectoryRef),s=await ma(e,t.name);if(s.status==="repairable")return i.push({code:"trajectory-tail-incomplete",message:`Native trajectory final line is incomplete at line ${s.line}; doctor repair can discard ${s.discardedBytes} incomplete byte(s)`,path:o}),i;if(s.status==="invalid")return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),i;let c;try{if(c=await it(r,a.trajectoryRef),c.length===0||c.some((u,d)=>!u||typeof u!="object"||u.sequence!==d+1||u.runId!==a.runId||typeof u.type!="string"||!u.data||typeof u.data!="object"||Array.isArray(u.data)))throw new Error("trajectory events are missing or inconsistent")}catch(u){return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),i}let l=fr(r,a.checkpointRef);try{let u=await pa(r,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&i.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):i.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){i.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return i}var cL=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function lL(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function uL(e){return e?e.map(lL).join(" "):null}function dL(e){if(e===null)return null;let t=e.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/gu);return!t||t[0]!=="comet"?null:t.map(i=>{if(i.startsWith('"')&&i.endsWith('"'))try{return JSON.parse(i)}catch{return i.slice(1,-1)}return i.startsWith("'")&&i.endsWith("'")?i.slice(1,-1):i})}function Mt(e,t,i,r={}){return{input:e,flags:t,required:r.required??!0,placeholder:i,...r.choices?{choices:r.choices}:{},...r.repeatable?{repeatable:!0}:{},...r.alternativeGroup?{alternativeGroup:r.alternativeGroup}:{}}}function fL(e){return e.map(t=>Mt(t,[],null))}function hL(e){let t=["comet","native","next",e.name,"--summary","<summary>"],i=[Mt("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),i.push(Mt("shared-understanding-confirmation",["--confirmed"],null)),{commandArgs:t,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:i};if(e.phase==="build"){t.push("--artifact","<project-relative-path>"),i.push(Mt("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),Mt("artifact-or-no-code-reason",["--no-code-reason"],"<reason>",{alternativeGroup:"build-evidence"}));let r=["summary","artifact-or-no-code-reason"];return e.approval!=="confirmed"&&(t.push("--confirmed"),r.push("shared-understanding-confirmation"),i.push(Mt("shared-understanding-confirmation",["--confirmed"],null))),{commandArgs:t,requiredInputs:r,inputOptions:i}}return e.phase==="verify"?(t.push("--result","<pass|fail>","--report","<change-relative-path>"),i.push(Mt("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),Mt("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:i}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function Ke(e,t){let i=t.commandArgs===void 0?dL(t.command??null):t.commandArgs;return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.name,phase:e.phase,revision:e.revision,disposition:t.disposition,action:t.action,command:t.command===void 0?uL(i??null):t.command,commandArgs:i??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??fL(t.requiredInputs??[])}}function Gu(e){let i=(e.findings??[]).filter(d=>!va(d.code)),r=i.find(d=>d.requiresUserDecision),n=i.find(d=>d.repairCommand!==null||cL.test(d.code)),a=i.find(d=>d.code==="repair-iteration-limit"||d.code==="repair-override-exhausted"),o=i.find(d=>d.code==="repair-stagnation-stop"),s=i.find(d=>d.requiredAction==="return-to-bound-working-directory"||d.requiredAction==="repair-workspace-binding"),c=i.find(d=>d.code==="runtime-missing"),l=[...new Set(i.map(d=>d.requiredAction))].sort();if(e.done)return Ke(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return Ke(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[Mt("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(r)return Ke(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return Ke(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return Ke(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return Ke(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[Mt("summary",["--summary"],"<summary>")]});if(n)return Ke(e.state,{disposition:"blocked",action:"repair",command:n.repairCommand,requiredInputs:l});if(e.evidenceRetreat){let d=["comet","native","next",e.state.name,"--summary","<summary>"];return Ke(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[Mt("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return Ke(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(i.length>0)return e.state.phase==="archive"?Ke(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?Ke(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):Ke(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:l});if(e.state.phase==="archive"){if(e.archiveReady&&e.archivePreflightHash){if(!/^[a-f0-9]{64}$/u.test(e.archivePreflightHash))throw new Error("Native Archive continuation preflight must be a SHA-256 hash");let d=["comet","native","archive",e.state.name,"--expect-preflight",e.archivePreflightHash];return e.archiveConfirmation==="required"?(d.push("--confirmed"),Ke(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[Mt("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):Ke(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return Ke(e.state,{disposition:e.archiveReady?"continue":"blocked",action:e.archiveReady?"archive":"none",commandArgs:e.archiveReady?["comet","native","archive",e.state.name,"--dry-run"]:null,requiredInputs:e.archiveReady?[]:["archive-readiness"]})}let u=hL(e.state);return Ke(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import Hs from"path";var tE=8,pL={"runtime-missing":{severity:"warning",requiredAction:"rebuild-native-runtime",retry:"next",repair:"none"},"runtime-layout-legacy":{severity:"warning",requiredAction:"migrate-native-runtime-layout",retry:"status",repair:"doctor"},"runtime-storage-invalid":{severity:"error",requiredAction:"repair-native-runtime-storage",retry:"status",repair:"doctor"},"brief-blocking-question":{severity:"error",requiredAction:"answer-blocking-question",retry:"next",repair:"none"},"shape-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"approval-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"transition-incomplete":{severity:"error",requiredAction:"recover-transition",retry:"status",repair:"doctor"},"trajectory-tail-incomplete":{severity:"error",requiredAction:"repair-trajectory-tail",retry:"status",repair:"doctor"},"checkpoint-progress-invalid":{severity:"error",requiredAction:"manually-isolate-invalid-checkpoint",retry:"none",repair:"none"},"checkpoint-progress-incomplete":{severity:"error",requiredAction:"recover-progress-checkpoint",retry:"status",repair:"doctor"},"checkpoint-manifest-invalid":{severity:"error",requiredAction:"record-checkpoint-again",retry:"status",repair:"none"},"verification-scope-partial":{severity:"error",requiredAction:"confirm-partial-verification-scope",retry:"next",repair:"none"},"verification-implementation-stale":{severity:"error",requiredAction:"return-to-build-and-refresh-implementation-scope",retry:"next",repair:"none"},"verification-receipt-binding-mismatch":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-stale":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-invalid":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"native-change-conflict":{severity:"error",requiredAction:"resolve-native-change-conflict",retry:"status",repair:"none"},"native-change-overlap":{severity:"error",requiredAction:"inspect-native-change-overlap",retry:"status",repair:"none"},"contract-changed-after-approval":{severity:"error",requiredAction:"re-confirm-contract",retry:"next",repair:"none"},"baseline-snapshot-incomplete":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"baseline-snapshot-missing":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"workspace-inspection-unavailable":{severity:"info",requiredAction:"migrate-workspace-identity",retry:"status",repair:"doctor"},"workspace-binding-root-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-binding-invalid":{severity:"error",requiredAction:"repair-workspace-binding",retry:"status",repair:"none"},"workspace-branch-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-kind-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-vcs-unavailable":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"repair-stagnation-warning":{severity:"warning",requiredAction:"change-repair-approach",retry:"next",repair:"none"},"repair-stagnation-stop":{severity:"error",requiredAction:"try-new-repair-hypothesis-with-status-override",retry:"none",repair:"none"},"repair-iteration-limit":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"},"repair-override-exhausted":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"}};function mL(e){let t=pL[e];return t||(/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid)|transition-invalid)/u.test(e)?{severity:"error",requiredAction:"isolate-or-restore-native-runtime-from-a-trusted-copy",retry:"none",repair:"none"}:e.startsWith("brief-")?{severity:"error",requiredAction:"complete-brief",retry:"next",repair:"none"}:e.startsWith("spec-")?{severity:"error",requiredAction:"resolve-spec-state",retry:"next",repair:"none"}:e.startsWith("verification-")?{severity:"error",requiredAction:"complete-verification-evidence",retry:"next",repair:"none"}:e.startsWith("build-")?{severity:"error",requiredAction:"record-build-evidence",retry:"next",repair:"none"}:va(e)?{severity:e==="workspace-inspection-unavailable"?"info":"warning",requiredAction:"inspect-workspace-advisory",retry:"status",repair:"none"}:{severity:"error",requiredAction:"resolve-finding",retry:"status",repair:"none"})}function vL(e,t,i){if(!i.path)return null;let r;if(Hs.isAbsolute(i.path)?r=Hs.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?r=Hs.resolve(ne(e,t.name),...i.path.split(/[\\/]/u)):r=Hs.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!O(e.projectRoot,r))return null;let n=Hs.relative(e.projectRoot,r).replaceAll("\\","/");return n===""?".":n}function gL(e,t,i){return e==="next"?`comet native next ${t.name} --summary "<summary>"${i==="contract-changed-after-approval"||i==="shape-confirmation-required"||i==="approval-confirmation-required"?" --confirmed":""}`:e==="status"?`comet native status ${t.name} --details`:null}function gm(e){return e.findings.map(t=>{let i=mL(t.code);return{code:t.code,message:t.message,severity:i.severity,path:vL(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:gL(i.retry,e.state,t.code),repairCommand:i.repair==="doctor"?`comet native doctor ${e.state.name} --repair${t.code.startsWith("transition-")?" --strategy continue":""}`:null,requiresUserDecision:t.code==="brief-blocking-question"||t.code==="shape-confirmation-required"||t.code==="approval-confirmation-required"||t.code==="contract-changed-after-approval"||t.code==="verification-scope-partial"||t.code==="repair-iteration-limit"||t.code==="repair-override-exhausted"}}).sort((t,i)=>{let r={error:0,warning:1,info:2};return r[t.severity]-r[i.severity]||t.code.localeCompare(i.code)||(t.path??"").localeCompare(i.path??"")||t.message.localeCompare(i.message)})}function wm(e){let t=[...new Set(e.map(i=>i.code))];return{total:e.length,errors:e.filter(i=>i.severity==="error").length,warnings:e.filter(i=>i.severity==="warning").length,info:e.filter(i=>i.severity==="info").length,requiresUserDecision:e.some(i=>i.requiresUserDecision),codes:t.slice(0,tE),truncated:t.length>tE}}var iE=240,rE=8,Uu=50;function nE(e){let t=Array.from(e);return t.length<=iE?e:`${t.slice(0,iE-1).join("")}…`}function wL(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function yL(e){let t=[...new Set(e.map(wL))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,rE),reasonCount:e.length,codesTruncated:t.length>rE};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,Uu),reasonsTruncated:e.length>Uu}}}async function aE(e){let t=null;try{let s=await Dr(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:Hr(e.paths,e.state.name)})}catch(s){t={code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint journal aside before retrying`,path:Hr(e.paths,e.state.name)}}let i=await Wk({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),r=t?[t.code,...i.reasons]:i.reasons,n=yL(r);if(!i.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:Or.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:nE(i.checkpoint.summary),nextAction:nE(i.checkpoint.nextAction),artifactCount:i.checkpoint.artifactCount},o=i.manifest?{...a,summary:i.checkpoint.summary,nextAction:i.checkpoint.nextAction,manifestHash:i.checkpoint.manifestHash,manifestRef:i.checkpoint.manifestRef,artifacts:i.manifest.artifacts,totalBytes:i.manifest.totalBytes}:null;return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:Or.maxArtifacts}}async function NL(e,t){let i=H(e,t.name),r=await Oe(i);if(!r||!t.run_id||r.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let n=await pa(i,r.checkpointRef);if(!n||n.runId!==r.runId||n.stateVersion!==r.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await it(i,r.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:r.runId}}async function bL(e,t){let i=await NL(e,t);return{committed:i,latest:Nk(i),history:yk(i)}}async function oE(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let r=await bL(e,t),n=r.latest;if(!n)return null;let a=r.history.filter(c=>c.kind==="failure"),o=a.length>=i,s=n.disposition==="hard-stop"&&!o?"continue":n.disposition;return{disposition:o?"hard-stop":s,signatureHash:n.signatureHash,overrideRecorded:r.history.some(c=>c.kind==="override"&&c.signatureHash===n.signatureHash),failedAcceptanceIds:[...n.failedAcceptanceIds],failedCheckIds:[...n.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:i,remainingVerifyFailures:Math.max(0,i-a.length)}}var SL=/^native-status-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u,Ba=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function ym(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function EL(e){return(await zu(e))?.change??null}function PL(e,t,i=!1,r){return Gu({state:e,archiveReady:t,evidenceRetreat:i}).command}async function RL(e,t){let i=ne(e,t.name),r=[...(await rp(i,t.brief)).findings,...(await gb(e,t)).findings,...await eE(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await ha(e,t.name);if(n===null)r.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await Vl(e,n);a.complete||r.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${a.omittedCount} omitted entries); resolve the omissions before advancing`})}}catch(n){r.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${n.message}`})}if(t.phase==="build")try{let n=await ja({changeDir:i,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==n.contract.contractHash&&r.push({code:"contract-changed-after-approval",message:t.approval===null||t.approved_contract_hash===null||t.approved_contract_hash===void 0?"Native approval is not bound to a contract hash; re-confirm the current contract":"Native contract changed after approval; re-confirm the current contract"})}catch(n){r.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${n.message}`})}try{await Bi(e,t.name)&&r.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(n){r.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${n.message}`})}return t.verification_report?r.push(...(await np(i,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&r.push({code:"verification-report-missing",message:"Native change has no verification report"}),r}async function Nm(e,t,i){let r=await EL(e)===t,n=await Do(e,t),a=await ZN(e,t),o;try{let w=await vi(e,t);if(w.status==="migration-required"&&w.state)return{name:t,phase:w.state.phase,revision:"revision"in w.state?w.state.revision:null,approval:w.state.approval,verificationResult:w.state.verification_result,specChanges:w.state.spec_changes.length,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["migration-required"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:w.schema,migrationRequired:!0,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message};if(w.status!=="current"||!w.state)return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["runtime-incompatible"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:w.schema,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message??`Native change ${t} is incompatible`};o=w.state}catch(w){return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["change-invalid"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,error:w.message}}if(n.status!=="available"){let w={code:n.status==="missing"?"runtime-missing":"runtime-storage-invalid",message:n.status==="missing"?`Native Runtime is missing; continue ${o.name} to rebuild local execution state`:n.message??"Native Runtime storage is invalid",path:n.path},P=gm({paths:e,state:o,findings:[w]}),F=Gu({state:o,findings:P});return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:F.command,archiveReady:!1,inspection:{freshness:"stale",codes:[w.code],reasonCount:1,codesTruncated:!1},findingSummary:wm(P),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:F,workspace:a,runtime:n,...i?.details?{findings:P}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:w.message}:{}}}let s=await aE({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await oE(e,o,i?.maxVerifyFailures??5),c&&(c.disposition==="manual-stop"||c.disposition==="hard-stop")){let w=c.disposition==="hard-stop"?"repair-iteration-limit":c.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";l.push({code:w,message:`Native repair is stopped at failure signature: ${c.signatureHash}`})}}catch{l.push({code:"trajectory-invalid",message:"Native repair history could not be reconstructed safely"})}let u;if(i?.details&&(o.phase==="build"||o.phase==="verify"||o.phase==="archive"))try{let w=await ja({changeDir:ne(e,o.name),briefRef:o.brief,specChanges:o.spec_changes}),P=new Map;if(o.phase==="build"&&o.verification_result==="fail"&&o.verification_evidence){let Be=await Ta(e,o.name,o.verification_evidence);for(let ue of Be.acceptanceTrace.entries)P.set(ue.acceptanceId,ue.status==="failed"?"failed":ue.status==="missing"?"missing":"satisfied")}let F=Ay({criteria:w.contract.acceptance,acceptanceHash:w.contract.acceptanceHash,verificationStatuses:P,failedCheckIds:c?.failedCheckIds??[],...i.acceptanceCursor?{cursor:i.acceptanceCursor}:{}}),$=F.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",F.nextCursor,"--project-root",e.projectRoot]:null;u={...F,...$?{nextPageCommand:ym($),nextPageArgs:$}:{}}}catch(w){if(i.acceptanceCursor)throw w;u=void 0}let d=[];if(i?.includeConflictFindings!==!1)try{let w=await hu(e,o.name,{tolerateInvalidSiblings:!0});d.push(...w.findingCodes.map(P=>({code:P,message:`Native change overlap is visible in the current root: ${P}`})))}catch{d.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let f=[];try{let w=await kt(e,o.name);if(w)if(w.schema==="comet.native.workspace.v3"){let P=await wa({paths:e,identity:w});P.state==="drifted"&&P.code&&f.push({code:P.code,message:P.message??"Native workspace binding is no longer valid"})}else{let P=await is({paths:e,identity:w});f.push(...P.findingCodes.map(F=>({code:F,message:`Native workspace advisory changed: ${F} (${P.driftComponents.join(", ")||"no-component"})`})))}}catch{f.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let h=[],v=!1;if(o.phase==="verify"){let w=await Zk({paths:e,state:o});v=w.freshness!=="fresh",h.push(...w.findingCodes.map(P=>({code:P,message:`Native Verify implementation scope is not current: ${P}`})))}let m=null,p=[];if(o.phase==="archive")try{m=await Pu({paths:e,name:o.name}),p.push(...m.findingCodes.map(w=>({code:w,message:`Native Archive is blocked: ${w}`})))}catch{p.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let b=[...await RL(e,o),...s.findings,...d,...f,...h,...l,...p].filter((w,P,F)=>F.findIndex($=>$.code===w.code&&$.path===w.path)===P),g=gm({paths:e,state:o,findings:b}),y=g.filter(w=>!va(w.code)),E=o.phase==="archive"&&m?.ready===!0&&y.length===0,k=v||o.phase==="archive"&&(m?.findingCodes??[]).some(w=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(w)),S=g.some(w=>w.code==="trajectory-tail-incomplete"||w.code==="trajectory-invalid"||w.requiredAction==="return-to-bound-working-directory"||w.requiredAction==="repair-workspace-binding"),R=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",N=g.find(w=>w.severity==="error");return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:S||R?null:PL(o,E,k,i?.clarificationMode),archiveReady:E,inspection:s.inspection,findingSummary:wm(g),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:Gu({state:o,findings:g,archiveReady:E,evidenceRetreat:k,clarificationMode:i?.clarificationMode}),workspace:a,runtime:n,repair:c,...i?.details?{...u?{acceptancePage:u}:{},findings:g.slice(0,50),inspectionDetails:s.inspectionDetails,checkpointDetails:s.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:Uu,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:g.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...N?{error:N.message}:{}}}async function CL(e){let t;try{t=await Zt({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[],r=await kL.opendir(e.changesDir);try{for await(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink())&&(i.push(n.name),i.length>Ba.maxChanges))throw new Error(`Native status exceeds ${Ba.maxChanges} visible changes`)}finally{await r.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),i.sort()}function Ku(e,t){let i=t.toString(36),r=D("comet.native.status-cursor.v1",{namesHash:e,offset:t});return`native-status-v1.${e}.${i}.${r}`}function xL(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=SL.exec(e.cursor);if(!t)throw new Error("Native status cursor is invalid");if(t[1]!==e.namesHash)throw new Error("Native status cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native status cursor offset is invalid");let r=D("comet.native.status-cursor.v1",{namesHash:e.namesHash,offset:i});if(t[3]!==r)throw new Error("Native status cursor integrity check failed");return i}async function AL(e,t){let i=await CL(e),r=D("comet.native.status-names.v1",i),n=xL({namesHash:r,total:i.length,cursor:t?.cursor}),a=await Promise.all(i.slice(n,n+Ba.maxItems).map(u=>Nm(e,u,{includeConflictFindings:!1,clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures}))),o=[];for(let u of a){let d=[...o,u],f=n+d.length,h={schema:"comet.native.status-page.v1",total:i.length,offset:n,items:d,nextCursor:f<i.length?Ku(r,f):null,nextPageCommand:f<i.length?ym(["comet","native","status","--cursor",Ku(r,f)]):null,nextPageArgs:f<i.length?["comet","native","status","--cursor",Ku(r,f)]:null,limits:{...Ba}};if(Buffer.byteLength(JSON.stringify(h),"utf8")>Ba.maxSerializedBytes){if(o.length===0)throw new Error("Native status item exceeds its page serialization budget");break}o.push(u)}let s=n+o.length,c=s<i.length?Ku(r,s):null,l=c?["comet","native","status","--cursor",c]:null;return{schema:"comet.native.status-page.v1",total:i.length,offset:n,items:o,nextCursor:c,nextPageCommand:l?ym(l):null,nextPageArgs:l,limits:{...Ba}}}async function bm(e,t){return(await AL(e,{clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures})).items}import{createHash as UL,randomUUID as KL}from"node:crypto";import{constants as Rm,promises as Q}from"node:fs";import le from"node:path";var Qu=Tn(en(),1);import{randomUUID as _L}from"crypto";import{promises as dE}from"fs";import Sm from"path";import{isDeepStrictEqual as Em}from"util";var Pn=/^[a-f0-9]{64}$/u,TL=new Set(["schema","id","change","fromSchema","toSchema","sourceHash","targetHash","createdAt","nextState","transition","transitionSupersede","runRetreat"]),IL=new Set(["sourceHash","targetHash","nextJournal"]),jL=new Set(["sourceHash","transitionId","previousRun","nextRun","evidenceHash","eventData"]),sE=new Set(["fromSchema","toSchema","previousPhase","nextPhase","reason","supersededTransitionId"]),$L=new Set(["previousRun","nextRun","evidenceHash","eventData"]);function Yu(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function cE(e){return JSON.stringify(e,null,2)+`
265
+ `}function Pm(e){return e.schema===be?eu(e):pn(e)}function km(e,t){return{...e,schema:be,minimum_runtime_version:2,revision:t}}function OL(e){return{...e,schema:ji,minimum_runtime_version:2,revision:1,previousState:km(e.previousState,1),nextState:km(e.nextState,2)}}function Xu(e,t){let i=t?.retreatEvidencePhase===!0&&(e.phase==="verify"||e.phase==="archive");return{...e,schema:Ne,minimum_runtime_version:3,verification_protocol:"legacy-v1",revision:e.revision+(i&&t?.incrementRetreatRevision?1:0),phase:i?"build":e.phase,verification_result:i?"pending":e.verification_result,verification_report:i?null:e.verification_report,approved_contract_hash:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:i?!1:e.archived}}function HL(e){if(e.nextState.phase==="archive")throw new Error("Native v2 Archive transition must be superseded by schema migration");let t=e.previousState.phase!=="shape"&&e.nextState.phase==="build"&&e.eventData.verificationResult===null,i=t?L(JSON.stringify({operation:"spec-rebase",change:e.change,summary:e.eventData.summary,specChanges:e.nextState.spec_changes})):e.evidenceHash;return{...e,schema:vr,minimum_runtime_version:3,revision:1,operation:t?"spec-rebase":"advance",evidenceHash:i,previousState:Xu(e.previousState),nextState:{...Xu(e.nextState),...t?{implementation_scope:null,verification_evidence:null,partial_allowance:null}:{}},eventData:{...e.eventData,evidenceHash:i},nextRun:e.previousRun===null?{...e.nextRun,skillVersion:Ni.definition.metadata.version,skillHash:bs}:e.nextRun}}function lE(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Va(e,t){return JSON.stringify(eu(e))===JSON.stringify(eu(t))}function uE(e,t){return JSON.stringify(pn(e))===JSON.stringify(pn(t))}function zi(e,t){return Em(e,t)}function DL(e,t,i,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Schema migration transition supersede plan is invalid");let n=e;if(Yu(n,jL,"Schema migration transition supersede plan"),typeof n.sourceHash!="string"||!Pn.test(n.sourceHash))throw new Error("Schema migration transition supersede source hash is invalid");if(typeof n.transitionId!="string"||n.transitionId.length===0)throw new Error("Schema migration superseded transition id is invalid");if(typeof n.evidenceHash!="string"||!Pn.test(n.evidenceHash))throw new Error("Schema migration transition supersede evidence hash is invalid");let a=Rr(n.previousRun),o=Rr(n.nextRun);if(a.runId!==o.runId||i.run_id!==o.runId||i.phase!=="build"&&i.phase!=="verify"||o.currentStep!==i.phase||o.pending!==null||o.status!=="running"||i.verification_result!=="pending"||i.verification_report!==null||i.implementation_scope!==null||i.verification_evidence!==null||i.partial_allowance!==null)throw new Error("Schema migration transition supersede Run does not match target state");let s=a.currentStep==="verify"&&i.phase==="build"||a.currentStep==="archive"&&i.phase==="build",c=a.currentStep===i.phase?a:s?{...a,currentStep:i.phase,iteration:a.iteration+1,pending:null,status:"running"}:null;if(!c||!zi(c,o))throw new Error("Schema migration transition supersede Run retreat is invalid");if(!n.eventData||typeof n.eventData!="object"||Array.isArray(n.eventData))throw new Error("Schema migration transition supersede event is invalid");let l=n.eventData,u=Object.keys(l);if(u.length!==sE.size||u.some(f=>!sE.has(f))||l.fromSchema!==be||l.toSchema!==Ne||!["build","verify","archive"].includes(l.previousPhase)||l.nextPhase!==i.phase||l.reason!==(i.phase==="build"?"implementation-scope-required":"verification-evidence-required")||l.supersededTransitionId!==n.transitionId)throw new Error("Schema migration transition supersede event semantics are invalid");if(i.name!==t)throw new Error("Schema migration transition supersede change mismatch");let d=L(JSON.stringify({operation:"supersede-v2-evidence-transition",change:t,transitionId:n.transitionId,migrationId:r,previousPhase:l.previousPhase,nextPhase:l.nextPhase,reason:l.reason,previousIteration:a.iteration,nextRevision:i.revision}));if(n.evidenceHash!==d)throw new Error("Schema migration transition supersede evidence hash mismatch");return{sourceHash:n.sourceHash,transitionId:n.transitionId,previousRun:a,nextRun:o,evidenceHash:n.evidenceHash,eventData:l}}function Ds(e,t){return Sm.join(H(e,t),"schema-migration.json")}function LL(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native schema migration journal must be an object");Yu(e,TL,"Native schema migration journal");let i=e;if(i.schema!=="comet.native.schema-migration.v1")throw new Error("Unsupported Native schema migration journal");if(i.change!==t)throw new Error("Schema migration change mismatch");let r=i.fromSchema===et&&i.toSchema===be,n=i.fromSchema===be&&i.toSchema===Ne;if(!r&&!n)throw new Error("Schema migration route is unsupported");if(typeof i.id!="string"||i.id.length===0)throw new Error("Schema migration id is invalid");if(typeof i.sourceHash!="string"||!Pn.test(i.sourceHash)||typeof i.targetHash!="string"||!Pn.test(i.targetHash))throw new Error("Schema migration hash is invalid");if(typeof i.createdAt!="string"||Number.isNaN(Date.parse(i.createdAt)))throw new Error("Schema migration timestamp is invalid");let a=r?di(i.nextState):lt(i.nextState);if(a.name!==t)throw new Error("Schema migration target state change mismatch");if(L((0,Qu.stringify)(Pm(a)))!==i.targetHash)throw new Error("Schema migration state target hash does not match its document");let o;if(i.transition!==void 0){if(!i.transition||typeof i.transition!="object")throw new Error("Schema migration transition target is invalid");Yu(i.transition,IL,"Schema migration transition target");let l=i.transition;if(typeof l.sourceHash!="string"||!Pn.test(l.sourceHash)||typeof l.targetHash!="string"||!Pn.test(l.targetHash))throw new Error("Schema migration transition hash is invalid");let u=r?Lp(l.nextJournal,t):Dp(l.nextJournal,t);if(L(JSON.stringify(l.nextJournal,null,2)+`
266
+ `)!==l.targetHash)throw new Error("Schema migration transition target hash does not match its journal");if(!(r&&a.schema===be?Va(a,u.previousState)||Va(a,u.nextState):a.schema===Ne&&(uE(a,u.previousState)||uE(a,u.nextState))))throw new Error("Schema migration state/transition target mismatch");o={sourceHash:l.sourceHash,targetHash:l.targetHash,nextJournal:l.nextJournal}}if(r&&(!o&&a.revision!==1||o&&a.revision!==1&&a.revision!==2))throw new Error("Schema migration v1 target revision is invalid");let s;if(i.transitionSupersede!==void 0){if(!n||o)throw new Error("Schema migration transition supersede plan is not valid for this route");if(a.schema!==Ne)throw new Error("Schema migration transition supersede target schema is invalid");s=DL(i.transitionSupersede,t,a,i.id)}let c;if(i.runRetreat!==void 0){if(!n||o||s)throw new Error("Schema migration Run retreat is not valid for this route");if(!i.runRetreat||typeof i.runRetreat!="object")throw new Error("Schema migration Run retreat is invalid");Yu(i.runRetreat,$L,"Schema migration Run retreat");let l=i.runRetreat,u,d;try{u=Rr(l.previousRun),d=Rr(l.nextRun)}catch(f){throw new Error("Schema migration Run retreat is invalid",{cause:f})}if(typeof l.evidenceHash!="string"||!Pn.test(l.evidenceHash)||!l.eventData||typeof l.eventData!="object"||Array.isArray(l.eventData))throw new Error("Schema migration Run retreat is invalid");if(a.schema!==Ne||a.phase!=="build"||a.run_id!==d.runId||u.runId!==d.runId||u.currentStep!=="verify"&&u.currentStep!=="archive"||d.currentStep!=="build"||d.iteration!==u.iteration+1)throw new Error("Schema migration Run retreat does not match target state");c={previousRun:u,nextRun:d,evidenceHash:l.evidenceHash,eventData:l.eventData}}if(o&&c||s&&c)throw new Error("Schema migration has conflicting recovery plans");return{schema:"comet.native.schema-migration.v1",id:i.id,change:t,fromSchema:i.fromSchema,toSchema:i.toSchema,sourceHash:i.sourceHash,targetHash:i.targetHash,createdAt:i.createdAt,nextState:a,...o?{transition:o}:{},...s?{transitionSupersede:s}:{},...c?{runRetreat:c}:{}}}async function Ls(e,t){let i=Ds(e,t),r=j(e,i);await T(r,i);try{let n=await xl({root:r,file:i,maxBytes:524288,label:"Native schema migration journal"});return LL(JSON.parse(n.text),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function ML(e,t,i){let r=await ha(e,t),n=r?await Vl(e,r):await ql(e,{now:new Date(i),origin:"legacy-migration"});if(!n.complete){let a=qh(n),o=n.omitted.reduce((c,l)=>(c[l.reason]=(c[l.reason]??0)+1,c),{}),s=n.omissionOverflow?.count??0;throw s>0&&(o.overflow=s),new ya(t,n.omittedCount,o,a.samplePaths,a.sampleTruncated)}r===null&&await Jh(e,t,n)}async function fE(e){try{return await ei(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}function FL(e,t){let i=e.transitionSupersede;return{sequence:t,timestamp:e.createdAt,type:"state_migrated",runId:i.nextRun.runId,data:{...i.eventData,migrationId:e.id,evidenceHash:i.evidenceHash}}}async function hE(e,t){let i=t.transitionSupersede,r=H(e,t.change),n=await it(r,i.nextRun.trajectoryRef),a=n.map((s,c)=>({event:s,index:c})).filter(({event:s})=>s.data.migrationId===t.id);if(a.length>1)throw new Error(`Native schema migration event ${t.id} is duplicated`);let o=a[0];if(o&&!Em(o.event,FL(t,o.index+1)))throw new Error(`Native schema migration event ${t.id} changed`);return{trajectoryLength:n.length,sequence:o?.event.sequence??null}}async function BL(e,t,i){if(!t.transitionSupersede)return;let r=Ue(e,t.change),n=await fE(r);if(n===t.transitionSupersede.sourceHash)return;if(n!==null)throw new Error(`Native superseded transition source changed for ${t.change}: expected ${t.transitionSupersede.sourceHash}, actual ${n}`);let a=H(e,t.change),o=await Oe(a),s=await hE(e,t),c=await pa(a,t.transitionSupersede.nextRun.checkpointRef);if(!i||!o||!zi(o,t.transitionSupersede.nextRun)||s.sequence===null||!c||c.runId!==t.transitionSupersede.nextRun.runId||c.stateVersion!==t.transitionSupersede.nextRun.iteration||c.trajectoryOffset!==s.sequence||c.contextHash!==null||c.artifactsHash!==L(t.transitionSupersede.evidenceHash)||c.createdAt!==t.createdAt)throw new Error(`Native superseded transition disappeared before migration ${t.id} was durable`)}async function VL(e,t,i){let r=t.transitionSupersede;if(!r)return;let n=H(e,t.change),a=await Oe(n);if(!a)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!zi(a,r.nextRun)){if(!zi(a,r.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await hn(n,r.nextRun),await i?.afterRunStateWritten?.(t)}if(!zi(await Oe(n),r.nextRun))throw new Error(`Native schema migration Run write diverged for ${t.change}`);let o=await hE(e,t);if(o.sequence===null){let l=await jr({changeDir:n,run:r.nextRun,type:"state_migrated",data:{...r.eventData,migrationId:t.id,evidenceHash:r.evidenceHash},now:new Date(t.createdAt)});o={trajectoryLength:l.sequence,sequence:l.sequence}}await i?.afterTrajectoryWritten?.(t),await yn({changeDir:n,run:r.nextRun,trajectoryOffset:o.sequence,evidenceHash:r.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t);let s=Ue(e,t.change),c=await fE(s);if(c!==null){if(c!==r.sourceHash)throw new Error(`Native superseded transition changed before removal for ${t.change}`);await dE.rm(s),await i?.afterTransitionSuperseded?.(t)}}async function qL(e,t,i){if(!t.runRetreat)return;let r=H(e,t.change),n=await Oe(r);if(!n)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!zi(n,t.runRetreat.nextRun)){if(!zi(n,t.runRetreat.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await hn(r,t.runRetreat.nextRun),await i?.afterRunStateWritten?.(t)}let a=await it(r,t.runRetreat.nextRun.trajectoryRef),o=a.find(s=>s.type==="state_migrated"&&s.data.migrationId===t.id);o||(o=await jr({changeDir:r,run:t.runRetreat.nextRun,type:"state_migrated",data:{...t.runRetreat.eventData,migrationId:t.id,evidenceHash:t.runRetreat.evidenceHash},now:new Date(t.createdAt)}),a=[...a,o]),await i?.afterTrajectoryWritten?.(t),await yn({changeDir:r,run:t.runRetreat.nextRun,trajectoryOffset:a.length,evidenceHash:t.runRetreat.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t)}async function WL(e,t,i){let r=await Ls(e,t);if(!r)return null;if(await ba(e,t))throw new Error(`Native change ${t} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let n=Sm.join(ne(e,t),Ie),a=await ei(n);if(await BL(e,r,a===r.targetHash),await ML(e,t,r.createdAt),a!==r.targetHash){if(a!==r.sourceHash)throw new Error(`Native schema migration source changed for ${t}: expected ${r.sourceHash}, actual ${a}`);await he(n,(0,Qu.stringify)(Pm(r.nextState))),await i?.afterStateWritten?.(r)}if(r.transition){let o=Ue(e,t),s=await ei(o);if(s!==r.transition.targetHash){if(s!==r.transition.sourceHash)throw new Error(`Native transition migration source changed for ${t}: expected ${r.transition.sourceHash}, actual ${s}`);await ee(o,r.transition.nextJournal),await i?.afterTransitionWritten?.(r)}}return await VL(e,r,i),await qL(e,r,i),await dE.rm(Ds(e,t),{force:!0}),r.nextState}async function zL(e){let t=H(e.paths,e.state.name),i=await Oe(t);if(!i||i.runId!==e.state.run_id||i.currentStep!==e.state.phase||i.currentStep!=="verify"&&i.currentStep!=="archive"||i.pending!==null)throw new Error(`Native v2 ${e.state.phase} change ${e.state.name} has no consistent Run state for safe Build retreat`);let r={...i,currentStep:"build",iteration:i.iteration+1,pending:null,status:"running"},n=L(`schema-v3-evidence-retreat:${e.state.name}:${e.state.revision}:${e.migrationId}`);return{previousRun:i,nextRun:r,evidenceHash:n,eventData:{fromSchema:be,toSchema:Ne,previousPhase:e.state.phase,nextPhase:"build",reason:"implementation-scope-required"}}}async function JL(e){let{journal:t,state:i}=e;if(!(t.previousState.phase==="build"&&t.nextState.phase==="verify"||t.previousState.phase==="verify"&&(t.nextState.phase==="build"||t.nextState.phase==="archive")))throw new Error("Only a pending v2 evidence-bearing transition can be superseded");let n=Va(i,t.previousState),a=Va(i,t.nextState);if(!n&&!a)throw new Error(`Native change ${i.name} does not match its v2 evidence transition`);let o=H(e.paths,i.name),s=await Oe(o);if(!s)throw new Error(`Native v2 transition Run is missing for ${i.name}`);let c=t.previousRun!==null&&zi(s,t.previousRun),l=zi(s,t.nextRun);if(!c&&!l||a&&!l)throw new Error(`Native v2 transition Run does not match its durable state for ${i.name}`);let d=(await it(o,t.nextRun.trajectoryRef)).map((b,g)=>({event:b,index:g})).filter(({event:b})=>b.data.transitionId===t.id);if(d.length>1)throw new Error(`Native v2 evidence transition ${t.id} has duplicate trajectory events`);let f=d[0];if(f){let b={sequence:f.index+1,timestamp:t.createdAt,type:"state_transitioned",runId:t.nextRun.runId,data:{...t.eventData,transitionId:t.id}};if(!Em(f.event,b)||!a||!l)throw new Error(`Native v2 evidence transition ${t.id} trajectory event does not match its journal`)}let h={...Xu(i),revision:i.revision+(i.phase==="build"?0:1),phase:"build",verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:!1},v=s,m=s.currentStep!=="build"?{...s,currentStep:"build",iteration:s.iteration+1,pending:null,status:"running"}:s,p=L(JSON.stringify({operation:"supersede-v2-evidence-transition",change:i.name,transitionId:t.id,migrationId:e.migrationId,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",previousIteration:s.iteration,nextRevision:h.revision}));return{nextState:h,plan:{sourceHash:await ei(Ue(e.paths,i.name)),transitionId:t.id,previousRun:v,nextRun:m,evidenceHash:p,eventData:{fromSchema:be,toSchema:Ne,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",supersededTransitionId:t.id}}}}async function GL(e){let t,i,r,n;if(e.state.schema===et){if(t=km(e.state,1),e.pendingTransition){if(e.pendingTransition.journal.schema!==cn)throw new Error("Native v1 change has a transition from another schema generation");let s=OL(e.pendingTransition.journal);if(lE(e.state,e.pendingTransition.journal.previousState))t=s.previousState;else if(lE(e.state,e.pendingTransition.journal.nextState))t=s.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v1 transition journal`);let c=Ue(e.paths,e.name);i={sourceHash:await ei(c),targetHash:L(cE(s)),nextJournal:s}}}else if(e.pendingTransition){if(e.pendingTransition.journal.schema!==ji)throw new Error("Native v2 change has a transition from another schema generation");let s=e.pendingTransition.journal;if(s.previousState.phase==="build"&&s.nextState.phase==="verify"||s.previousState.phase==="verify"&&(s.nextState.phase==="build"||s.nextState.phase==="archive")){let l=await JL({paths:e.paths,state:e.state,journal:s,migrationId:e.id});t=l.nextState,r=l.plan}else{let l=HL(s);if(Va(e.state,e.pendingTransition.journal.previousState))t=l.previousState;else if(Va(e.state,e.pendingTransition.journal.nextState))t=l.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v2 transition journal`);let u=Ue(e.paths,e.name);i={sourceHash:await ei(u),targetHash:L(cE(l)),nextJournal:l}}}else t=Xu(e.state,{retreatEvidencePhase:!0,incrementRetreatRevision:!0}),(e.state.phase==="verify"||e.state.phase==="archive")&&(n=await zL({paths:e.paths,state:e.state,migrationId:e.id}));let a=Sm.join(ne(e.paths,e.name),Ie),o=(0,Qu.stringify)(Pm(t));return{schema:"comet.native.schema-migration.v1",id:e.id,change:e.name,fromSchema:e.state.schema,toSchema:e.state.schema===et?be:Ne,sourceHash:await ei(a),targetHash:L(o),createdAt:e.now.toISOString(),nextState:t,...i?{transition:i}:{},...r?{transitionSupersede:r}:{},...n?{runRetreat:n}:{}}}async function pE(e){return se(e.paths,`migrate schema for ${e.name}`,()=>Nn(e.paths,e.name,`migrate schema for ${e.name}`,async()=>{for(let t=0;t<3;t+=1){let i=await WL(e.paths,e.name,e.hooks);if(i?.schema===Ne)return i;let r=await vi(e.paths,e.name);if(r.status==="current"&&r.state)return r.state;if(r.status!=="migration-required"||!r.state)throw new Error(r.message??`Native change ${e.name} cannot be migrated`);if(await ba(e.paths,e.name))throw new Error(`Native change ${e.name} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let n=r.state;if(n.schema!==et&&n.schema!==be)throw new Error(`Native change ${e.name} has no supported migration route`);let a=await Mp(e.paths,e.name);if(a?.status==="current")throw new Error(`Native change ${e.name} has a current-schema pending transition; recover it before schema migration`);let o=await GL({paths:e.paths,name:e.name,state:n,pendingTransition:a,now:e.now??new Date,id:e.id?.()??_L()}),s=Ds(e.paths,e.name),c=j(e.paths,s);await T(c,s),await ee(s,o,{containedRoot:c}),await e.hooks?.afterPrepared?.(o)}throw new Error(`Native change ${e.name} exceeded the supported schema migration path`)}))}var Ji=Object.freeze({minimumAgeMs:720*60*60*1e3,keepLatestUnreferencedPerKind:32,maxDocuments:4096,maxScannedBytes:256*1024*1024,maxReportedRefs:8,maxReportMessageBytes:4096}),YL=512*1024,Rn=/^([a-f0-9]{64})\.json$/u,XL=/^\.([a-f0-9]{64}\.json)\.([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})\.gc$/u,QL=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts|check-receipts)\/[a-f0-9]{64}\.json$/u,Zu=["snapshots","scopes","allowances","verifications","reports","receipts","check-receipts"];function xm(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Ri(e,t){return xm(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function yE(e,t){return xm(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function qa(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function nt(e,t){return e<t?-1:e>t?1:0}function ZL(e,t){let i=le.relative(e.projectRoot,t);if(i.length===0||le.isAbsolute(i)||i===".."||i.startsWith(`..${le.sep}`))throw new Error("Native evidence retention finding path is outside the project");return i.split(le.sep).join("/")}function NE(e,t){return le.join(H(e,t),"evidence")}function ed(e,t){return ZL(e,NE(e,t))}async function td(e,t){let i=le.resolve(e),r=le.resolve(t);if(!O(i,r))throw new Error("Native evidence retention path escapes its managed change");let n=le.relative(i,r).split(le.sep).filter(Boolean),a=[],o=i;for(let s of["",...n]){s&&(o=le.join(o,s));let c=await Q.lstat(o);if(!c.isDirectory()||c.isSymbolicLink())throw new Error(`Native evidence retention parent must be a real directory: ${o}`);let l=await Q.realpath(o);if(a.length>0&&!O(a[0].realPath,l))throw new Error(`Native evidence retention parent resolves outside its change: ${o}`);a.push({path:o,realPath:l,...qa(c)})}return a}async function Ft(e){for(let t of e){let i=await Q.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!xm(t,i)||await Q.realpath(t.path)!==t.realPath)throw new Error(`Native evidence retention parent changed: ${t.path}`)}}function bE(e,t){return e==="check-receipts"?`runtime/evidence/check-receipts/${t}.json`:_a(e,t)}function mE(e){return e!==null&&QL.test(e)?[e]:[]}function eM(e,t,i,r){if(e==="snapshots")return{canonical:Ea(i,t),dependencies:[]};if(e==="scopes"){let a=Pa(i);if(a.scopeHash!==t)throw new Error("Native scope filename does not match its hash");return{canonical:a,dependencies:[a.baselineProjectionRef,a.currentProjectionRef]}}if(e==="allowances"){let a=cu(i);if(a.change!==r||a.allowanceHash!==t)throw new Error("Native allowance filename/change does not match its content");return{canonical:a,dependencies:[_a("scopes",a.scopeHash)]}}if(e==="verifications"){let a=vs(i);if(a.change!==r||a.envelopeHash!==t)throw new Error("Native verification filename/change does not match its content");let o=a.acceptanceTrace.entries.flatMap(s=>s.evidenceRefs.flatMap(mE));return{canonical:a,dependencies:[a.implementationScopeRef,lk(a.reportHash),...mE(a.partialAllowanceRef),...a.requiredReceiptRefs,...a.receiptRefs,...o]}}if(e==="reports"){if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Native report evidence must be an object");let a=i;if(Object.keys(a).sort().join(",")!=="content,reportHash,schema"||a.schema!=="comet.native.verification-report.v1"||a.reportHash!==t||typeof a.content!="string"||UL("sha256").update(Buffer.from(a.content,"utf8")).digest("hex")!==t)throw new Error("Native report evidence filename/hash does not match its content");return{canonical:a,dependencies:[]}}if(e==="receipts"){let a=uu(i);if(a.bindings.change!==r||a.receiptHash!==t)throw new Error("Native verification receipt filename/change does not match its content");return{canonical:a,dependencies:a.kind==="static-inspection"?[a.evidence.checkReceiptRef]:[]}}let n=lu(i);if(n.change!==r||n.receiptHash!==t)throw new Error("Native check receipt filename/change does not match its content");return{canonical:n,dependencies:[]}}async function Jr(e){let t=await Q.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`Native evidence entry is not a regular file: ${e.ref}`);let i=e.kind==="check-receipts"?YL:Ir;if(t.size>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);let r=await Q.realpath(e.file);if(!O(e.directoryChain[0].realPath,r))throw new Error(`Native evidence entry resolves outside its change: ${e.ref}`);let n=process.platform==="win32"?"r":Rm.O_RDONLY|Rm.O_NOFOLLOW|Rm.O_NONBLOCK,a=await Q.open(e.file,n).catch(o=>{throw o.code==="ELOOP"||o.code==="ENXIO"?new Error(`Native evidence entry became unsafe while opening: ${e.ref}`):o});try{let[o,s,c]=await Promise.all([a.stat(),Q.lstat(e.file),Q.realpath(e.file)]);if(await Ft(e.directoryChain),!o.isFile()||!s.isFile()||s.isSymbolicLink()||c!==r||!Ri(qa(t),o)||!Ri(qa(o),s))throw new Error(`Native evidence entry changed while opening: ${e.ref}`);let l=[],u=Buffer.allocUnsafe(64*1024),d=0;for(;;){let g=i+1-d,y=await a.read(u,0,Math.min(u.length,g),null);if(y.bytesRead===0)break;if(d+=y.bytesRead,d>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);l.push(Buffer.from(u.subarray(0,y.bytesRead)))}let[f,h,v]=await Promise.all([a.stat(),Q.lstat(e.file),Q.realpath(e.file)]);if(await Ft(e.directoryChain),!h.isFile()||h.isSymbolicLink()||v!==r||!Ri(qa(o),f)||!Ri(qa(o),h))throw new Error(`Native evidence entry changed while reading: ${e.ref}`);let m=Buffer.concat(l,d).toString("utf8"),p;try{p=JSON.parse(m)}catch(g){throw new Error(`Native evidence entry is not valid JSON: ${e.ref}`,{cause:g})}let b=eM(e.kind,e.hash,p,e.name);if(m!==JSON.stringify(b.canonical,null,2)+`
267
+ `)throw new Error(`Native evidence entry is not canonically serialized: ${e.ref}`);return{ref:e.ref,kind:e.kind,change:e.name,changeRoot:e.changeRoot,file:e.file,size:d,mtimeMs:f.mtimeMs,identity:qa(f),directoryChain:e.directoryChain,dependencies:[...new Set(b.dependencies)].sort(nt)}}finally{await a.close()}}async function vE(e){try{return await Q.lstat(e),!1}catch(t){if(t.code==="ENOENT")return!0;throw t}}async function tM(e){let t=H(e.paths,e.name),i=t,r=NE(e.paths,e.name);await T(j(e.paths,r),r);let n;try{let s=await td(t,r);n=await Q.readdir(r,{withFileTypes:!0}),await Ft(s)}catch(s){if(s.code==="ENOENT")return{findings:[],pending:!1};throw s}let a=[];for(let s of Zu){if(!n.some(f=>f.name===s))continue;let c=le.join(r,s),l=await td(t,c),u=(await Q.readdir(c,{withFileTypes:!0})).sort((f,h)=>nt(f.name,h.name)),d=new Map;for(let f of u){let h=XL.exec(f.name);if(!h)continue;let v=d.get(h[1])??[];v.push(f),d.set(h[1],v)}for(let[f,h]of[...d.entries()].sort(([v],[m])=>nt(v,m))){if(h.length!==1)throw new Error(`Native evidence cleanup has multiple quarantines for ${s}/${f}`);let v=h[0];if(!v.isFile()||v.isSymbolicLink())throw new Error(`Native evidence cleanup quarantine is not a regular file: ${s}/${v.name}`);let m=le.join(c,f),p=Rn.exec(f)?.[1];if(!p)throw new Error(`Native evidence cleanup quarantine name is invalid: ${v.name}`);let b=bE(s,p),g=le.join(c,v.name),y=await Jr({changeRoot:i,file:g,ref:b,kind:s,hash:p,name:e.name,directoryChain:l}),E=await vE(m),k=E?null:await Jr({changeRoot:i,file:m,ref:b,kind:s,hash:p,name:e.name,directoryChain:l});a.push({ref:b,original:m,quarantine:g,document:y,action:E?"restore-original":"finish-linked-recovery",originalDocument:k})}}if(a.length===0)return{findings:[],pending:!1};let o=a.map(s=>s.ref).sort(nt);if(!e.repair)return{pending:!0,findings:[{severity:"warning",code:"evidence-retention-recovery-required",message:Wa(`Native evidence cleanup has ${o.length} safely recoverable quarantined document(s) for ${e.name}: ${id(o)}`),path:ed(e.paths,e.name)}]};for(let s of a.sort((c,l)=>nt(c.ref,l.ref))){if(await Ft(s.document.directoryChain),s.action==="finish-linked-recovery"){let d=await Jr({changeRoot:i,file:s.original,ref:s.ref,kind:s.document.kind,hash:Rn.exec(le.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),f=await Jr({changeRoot:i,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:Rn.exec(le.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!s.originalDocument||!Ri(s.originalDocument.identity,d.identity)||!Ri(s.document.identity,f.identity))throw new Error(`Native evidence cleanup original or quarantine changed during recovery: ${s.ref}`);await Q.rm(s.quarantine),await Ft(s.document.directoryChain);continue}if(!await vE(s.original))throw new Error(`Native evidence cleanup original appeared during recovery: ${s.ref}`);let c=await Q.lstat(s.quarantine);if(!c.isFile()||c.isSymbolicLink()||!Ri(s.document.identity,c))throw new Error(`Native evidence cleanup quarantine changed during recovery: ${s.ref}`);await Q.link(s.quarantine,s.original),await e.hooks.afterRecoveryLink?.({ref:s.ref,original:s.original,quarantine:s.quarantine});let l=await Jr({changeRoot:i,file:s.original,ref:s.ref,kind:s.document.kind,hash:Rn.exec(le.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),u=await Jr({changeRoot:i,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:Rn.exec(le.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!yE(s.document.identity,l.identity)||!Ri(l.identity,u.identity))throw new Error(`Native evidence cleanup recovery identity changed: ${s.ref}`);await Q.rm(s.quarantine),await Ft(s.document.directoryChain)}return{pending:!1,findings:[{severity:"info",code:"evidence-retention-cleanup-recovered",message:Wa(`Recovered ${o.length} interrupted Native evidence cleanup document(s) for ${e.name}: ${id(o)}`),path:ed(e.paths,e.name)}]}}async function iM(e,t){let i=H(e,t),r=i,n=le.join(i,"evidence");await T(j(e,n),n);let a;try{let l=await td(i,n);a=await Q.readdir(n,{withFileTypes:!0}),await Ft(l)}catch(l){if(l.code==="ENOENT")return[];throw l}let o=a.filter(l=>!Zu.includes(l.name)||!l.isDirectory()||l.isSymbolicLink()).map(l=>l.name).sort(nt);if(o.length>0)throw new Error(`Native evidence root has unknown or special entries: ${id(o)}`);let s=[],c=0;for(let l of Zu){if(!a.some(h=>h.name===l))continue;let u=le.join(n,l),d=await td(r,u),f=(await Q.readdir(u,{withFileTypes:!0})).sort((h,v)=>nt(h.name,v.name));await Ft(d);for(let h of f){if(s.length>=Ji.maxDocuments)throw new Error(`Native evidence store exceeds ${Ji.maxDocuments} documents`);let v=Rn.exec(h.name);if(!v||!h.isFile()||h.isSymbolicLink())throw new Error(`Native evidence kind ${l} has an unknown or special entry: ${h.name}`);let m=bE(l,v[1]),p=le.join(u,h.name);await T(j(e,p),p);let b=await Jr({changeRoot:r,file:p,ref:m,kind:l,hash:v[1],name:t,directoryChain:d});if(c+=b.size,c>Ji.maxScannedBytes)throw new Error(`Native evidence store exceeds ${Ji.maxScannedBytes} scanned bytes`);s.push(b)}await Ft(d)}return s}function gE(e,t){let i=new Set,r=[...e].sort(nt).reverse();for(;r.length>0;){let n=r.pop();if(i.has(n))continue;let a=t.get(n);if(!a)throw new Error(`Native evidence dependency is missing: ${n}`);i.add(n);for(let o of[...a.dependencies].sort(nt).reverse())i.has(o)||r.push(o)}return i}function rM(e){let t=new Map(e.map(a=>[a.ref,a])),i=new Map(e.map(a=>[a.ref,0]));for(let a of e)for(let o of a.dependencies)t.has(o)&&i.set(o,(i.get(o)??0)+1);let r=[...i].filter(([,a])=>a===0).map(([a])=>a).sort(nt),n=[];for(;r.length>0;){let a=r.shift(),o=t.get(a);n.push(o);for(let s of o.dependencies){let c=i.get(s);if(c===void 0)continue;let l=c-1;i.set(s,l),l===0&&(r.push(s),r.sort(nt))}}if(n.length!==e.length)throw new Error("Native evidence candidate dependency graph contains a cycle");return n}function nM(e,t,i){let r=new Map(e.map(c=>[c.ref,c]));if(r.size!==e.length)throw new Error("Native evidence store has duplicate refs");for(let c of e)for(let l of c.dependencies)if(!r.has(l))throw new Error(`Native evidence dependency is missing: ${l}`);let n=gE(t,r),a=new Set(n);for(let c of e)i-c.mtimeMs<Ji.minimumAgeMs&&a.add(c.ref);for(let c of Zu){let l=e.filter(u=>u.kind===c&&!n.has(u.ref)).sort((u,d)=>d.mtimeMs-u.mtimeMs||nt(u.ref,d.ref)).slice(0,Ji.keepLatestUnreferencedPerKind);for(let u of l)a.add(u.ref)}let o=gE(a,r),s=e.filter(c=>!o.has(c.ref)&&i-c.mtimeMs>=Ji.minimumAgeMs).sort((c,l)=>nt(c.ref,l.ref));return{candidates:rM(s),candidateBytes:s.reduce((c,l)=>c+l.size,0)}}function id(e){let t=e.slice(0,Ji.maxReportedRefs),i=e.length-t.length;return`${t.join(", ")}${i>0?`, ... (${i} more)`:""}`}function Wa(e){let t=Ji.maxReportMessageBytes;if(Buffer.byteLength(e,"utf8")<=t)return e;let i=e;for(;i.length>0&&Buffer.byteLength(`${i}...`,"utf8")>t;)i=i.slice(0,-1);return`${i}...`}function Cm(e,t,i,r){let n=t.candidates.map(a=>a.ref).sort(nt);return{severity:"info",code:i?"evidence-retention-cleaned":"evidence-retention-candidates",message:Wa(`${i?"Removed":"Found"} ${t.candidates.length} old unreferenced Native evidence document(s) (${t.candidateBytes} bytes) for ${e}: ${id(n)}`),path:r}}async function wE(e,t){try{await Q.lstat(t);return}catch(i){if(i.code!=="ENOENT")return}try{await Q.rename(e,t)}catch{}}async function aM(e,t){await t.beforeDelete?.({ref:e.ref,file:e.file}),await Ft(e.directoryChain);let i=await Jr({changeRoot:e.changeRoot,file:e.file,ref:e.ref,kind:e.kind,hash:Rn.exec(le.basename(e.file))[1],name:e.change,directoryChain:e.directoryChain}),r=await Q.lstat(e.file),n=await Q.realpath(e.file);if(!r.isFile()||r.isSymbolicLink()||!Ri(e.identity,r)||!Ri(e.identity,i.identity)||!O(e.directoryChain[0].realPath,n))throw new Error(`Native evidence candidate changed before cleanup: ${e.ref}`);let a=le.join(le.dirname(e.file),`.${le.basename(e.file)}.${KL()}.gc`);await Q.rename(e.file,a);try{let[o,s]=await Promise.all([Q.lstat(a),Q.realpath(a)]);if(await Ft(e.directoryChain),!o.isFile()||o.isSymbolicLink()||!yE(e.identity,o)||!O(e.directoryChain[0].realPath,s))throw await wE(a,e.file),new Error(`Native evidence candidate changed during cleanup: ${e.ref}`);await Q.rm(a),await Ft(e.directoryChain)}catch(o){throw await wE(a,e.file),o}}async function oM(e){if((await ye(e.projectRoot))?.native.pending_root_move)return!0;let i;try{i=await Q.readdir(e.transactionsDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return!1;throw r}for(let r of i){if(!r.isDirectory()||r.isSymbolicLink())return!0;try{let n=await yt(e,r.name);if(n.status!=="committed"&&n.status!=="rolled-back")return!0}catch{return!0}}return!1}async function sM(e,t){if(t)return[t];let i;try{i=await Q.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}return i.filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort(nt)}async function cM(e,t){let i=await vi(e,t);if(i.status!=="current"||!i.state||i.state.archived)return!0;let[r,n,a]=await Promise.all([Bi(e,t),Ls(e,t),Dr(e,t)]);return r!==null||n!==null||a!==null}async function lM(e){if(await cM(e.paths,e.name))return[];let t=await vi(e.paths,e.name);if(t.status!=="current"||!t.state)return[];if(!("implementation_scope"in t.state))return[];let i=await tM({paths:e.paths,name:e.name,repair:e.repair,hooks:e.hooks});if(i.pending)return i.findings;let r=[];for(let c of[t.state.implementation_scope,t.state.partial_allowance,t.state.verification_evidence])c!==null&&r.push(c);let n=await iM(e.paths,e.name),a=nM(n,r,e.nowMs);if(a.candidates.length===0)return i.findings;let o=ed(e.paths,e.name);if(!e.repair)return[...i.findings,Cm(e.name,a,!1,o)];let s=[];for(let c of a.candidates)try{await aM(c,e.hooks),s.push(c)}catch(l){let u=s.reduce((d,f)=>d+f.size,0);return[...i.findings,...s.length>0?[Cm(e.name,{candidates:s,candidateBytes:u},!0,o)]:[],{severity:"error",code:"evidence-retention-cleanup-failed",message:Wa(`Native evidence cleanup stopped safely for ${e.name}: ${l.message}`),path:o}]}return[...i.findings,Cm(e.name,a,!0,o)]}async function kE(e){if(e.deferAll||await oM(e.paths))return[];let t=e.now??new Date;if(Number.isNaN(t.getTime()))throw new Error("Native evidence retention time is invalid");let i=async n=>{let a=[];for(let o of await sM(e.paths,e.name))try{a.push(...await lM({paths:e.paths,name:o,repair:n,nowMs:t.getTime(),hooks:e.hooks??{}}))}catch(s){a.push({severity:"error",code:"evidence-retention-unsafe",message:Wa(`Native evidence retention refused to clean ${o}: ${s.message}`),path:ed(e.paths,o)})}return a};if(!(e.repair??!1))return i(!1);let r=await i(!1);if(r.some(n=>n.severity==="error")||!r.some(n=>n.code==="evidence-retention-candidates"||n.code==="evidence-retention-recovery-required"))return r;try{return await se(e.paths,"prune Native evidence",()=>i(!0))}catch(n){return[{severity:"info",code:"evidence-retention-cleanup-deferred",message:Wa(`Native evidence cleanup was deferred until the project mutation lock is available: ${n.message}`)}]}}import{createHash as uM,randomUUID as K6}from"crypto";import{promises as Bs}from"fs";import ae from"path";var _m=64*1024*1024,dM=256*1024,RE=16*1024*1024;async function at(e){try{return await Bs.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function fM(e){let t;try{t=await Bs.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of t.sort((r,n)=>r.name.localeCompare(n.name))){if(!i.isDirectory()||i.isSymbolicLink())continue;let r=await kt(e,i.name);if(r){await Xl({paths:e,name:i.name,revision:r.capturedRevision,...r.schema==="comet.native.workspace.v3"?{binding:{isolation:r.isolation,changeBranch:r.changeBranch,targetBranch:r.targetBranch},...r.finish?{finish:r.finish}:{}}:{}});continue}}}async function Fs(e,t){let i=[];async function r(n){let a=await wt({root:e,directory:n,label:"Native root tree"}),o=a.entries;o.sort((s,c)=>s.name.localeCompare(c.name));for(let s of o){await a.verify();let c=ae.join(n,s.name);if(t.excludedFiles?.has(ae.resolve(c))){await a.verify();continue}let l=await Bs.lstat(c);if(s.isSymbolicLink()||l.isSymbolicLink()){if(t.rejectSymlinks)throw new Error(`Native root contains a symlink: ${c}`);await a.verify();continue}if(s.isDirectory()&&l.isDirectory())i.push({ref:ae.relative(e,c).split(ae.sep).join("/"),type:"directory"}),await r(c);else if(s.isFile()&&l.isFile()){let u=await re({root:e,file:c,maxBytes:_m,label:`Native root file ${ae.relative(e,c)}`});i.push({ref:ae.relative(e,c).split(ae.sep).join("/"),type:"file",size:u.size,hash:u.hash})}else throw new Error(`Native root contains an unsupported file type: ${c}`);await a.verify()}}return await r(e),i.sort((n,a)=>n.ref.localeCompare(a.ref))}async function hM(e,t,i,r){await fi({root:r,directory:t,label:"Native root move staging directory"});async function n(a,o){let s=await wt({root:e,directory:a,label:"Native root move source directory"}),c=s.entries;for(let l of c){await s.verify();let u=ae.join(a,l.name);if(ae.resolve(u)===ae.resolve(i)){await s.verify();continue}let d=await Bs.lstat(u);if(l.isSymbolicLink()||d.isSymbolicLink())throw new Error(`Native root contains a symlink: ${u}`);let f=ae.join(o,l.name);if(l.isDirectory()&&d.isDirectory())await fi({root:r,directory:f,label:"Native root move staging directory"}),await n(u,f);else if(l.isFile()&&d.isFile())await Nr({sourceRoot:e,source:u,targetRoot:r,target:f,maxBytes:_m,label:`Native root move file ${ae.relative(e,u)}`,exclusive:!0,expectedTargetHash:null});else throw new Error(`Native root contains an unsupported file type: ${u}`);await s.verify()}}await n(e,t)}async function za(e,t,i,r){let n=await Fs(e,{rejectSymlinks:!0,excludedFiles:i?new Set([ae.resolve(i)]):void 0}),a=await Fs(t,{rejectSymlinks:!0,excludedFiles:r?new Set([ae.resolve(r)]):void 0});if(JSON.stringify(n)!==JSON.stringify(a))throw new Error(`Native root copies differ; preserve both trees for manual recovery: ${e} and ${t}`)}function pM(e,t){return ae.join(e.artifactRoot,`.comet-native-move-${t}`)}function mM(e,t){return ae.join(e.artifactRoot,`.comet-native-source-${t}.removing`)}function vM(e){return`${e}.removing`}function SE(e,t){return ae.join(ae.dirname(e),`.${ae.basename(e)}.${t}.rollback-removing`)}function CE(e,t,i){return ae.join($l(e,t).directory,`root-move-cleanup-${i}.json`)}function gM(e){return JSON.stringify(e,null,2)+`
268
+ `}function wM(e){return uM("sha256").update(e).digest("hex")}function yM(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Native root-move cleanup manifest entry ${t} must be an object`);let i=e,r=Object.keys(i).sort(),n=i.type==="file"?["hash","ref","size","type"]:["ref","type"];if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Native root-move cleanup manifest entry ${t} has invalid fields`);if(typeof i.ref!="string"||i.ref.length===0||i.ref.includes("\\")||ae.posix.normalize(i.ref)!==i.ref||i.ref.startsWith("/")||i.ref.split("/").includes("..")||Buffer.byteLength(i.ref,"utf8")>4096)throw new Error(`Native root-move cleanup manifest entry ${t} has an invalid ref`);if(i.type==="directory")return{ref:i.ref,type:"directory"};if(i.type!=="file"||typeof i.size!="number"||!Number.isSafeInteger(i.size)||i.size<0||typeof i.hash!="string"||!/^[a-f0-9]{64}$/u.test(i.hash))throw new Error(`Native root-move cleanup manifest entry ${t} is invalid`);return{ref:i.ref,type:"file",size:i.size,hash:i.hash}}function NM(e,t,i){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native root-move cleanup manifest must be an object");let r=e;if(JSON.stringify(Object.keys(r).sort())!==JSON.stringify(["entries","kind","schema","transactionId"])||r.schema!=="comet.native.root-move-cleanup.v1"||r.transactionId!==t||r.kind!==i||!Array.isArray(r.entries))throw new Error("Native root-move cleanup manifest binding is invalid");let n=r.entries.map(yM);for(let a=0;a<n.length;a+=1){if(a>0&&n[a-1].ref.localeCompare(n[a].ref)>=0)throw new Error("Native root-move cleanup manifest refs must be unique and sorted");let o=ae.posix.dirname(n[a].ref);if(o!=="."&&!n.some(s=>s.ref===o&&s.type==="directory"))throw new Error(`Native root-move cleanup manifest parent is missing: ${o}`)}return{schema:"comet.native.root-move-cleanup.v1",transactionId:t,kind:i,entries:n}}async function bM(e){let t={schema:"comet.native.root-move-cleanup.v1",transactionId:e.id,kind:e.kind,entries:e.entries},i=gM(t);if(Buffer.byteLength(i,"utf8")>RE)throw new Error("Native root-move cleanup manifest exceeds its byte budget");return await he(CE(e.paths,e.id,e.kind),i,{containedRoot:e.paths.runtimeDir}),wM(i)}async function kM(e){let t=await re({root:e.paths.runtimeDir,file:CE(e.paths,e.id,e.cleanup.kind),maxBytes:RE,label:`Native root-move cleanup manifest ${e.cleanup.kind}`});if(t.hash!==e.cleanup.manifestHash)throw new Error("Native root-move cleanup manifest hash changed");return NM(JSON.parse(t.bytes.toString("utf8")),e.id,e.cleanup.kind)}async function Am(e){let t=await Fs(e.quarantine,{rejectSymlinks:!0}),i=new Map(e.manifest.entries.map(r=>[r.ref,r]));for(let r of t){let n=i.get(r.ref);if(!n||JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Native root-move cleanup quarantine differs from its bound manifest: ${r.ref}`)}if(e.exact&&t.length!==e.manifest.entries.length)throw new Error("Native root-move cleanup quarantine is incomplete before deletion");return t}function EE(e){return e.ref.split("/").length}async function SM(e){let i=[...await Am({quarantine:e.quarantine,manifest:e.manifest,exact:!1})].sort((n,a)=>EE(a)-EE(n)||(n.type===a.type?a.ref.localeCompare(n.ref):n.type==="file"?-1:1)),r=0;for(let n of i){let a=ae.join(e.quarantine,...n.ref.split("/"));n.type==="file"?await Al({root:e.projectRoot,file:a,maxBytes:_m,expectedHash:n.hash,expectedSize:n.size,label:`Native root-move cleanup file ${n.ref}`}):await Ch({root:e.projectRoot,directory:a,label:`Native root-move cleanup directory ${n.ref}`}),r+=1,await e.hooks?.afterRootMoveCleanupEntryRemoved?.(e.manifest.kind,n.ref,r)}await Am({quarantine:e.quarantine,manifest:e.manifest,exact:!1}),await Ch({root:e.projectRoot,directory:e.quarantine,label:`Native root-move cleanup quarantine ${e.manifest.kind}`})}function xE(e,t,i=e.native.artifact_root){return{...e,native:{...e.native,artifact_root:i,pending_root_move:t}}}function EM(e){return{schema:"comet.native.transaction.v1",id:e.id,kind:"root-move",status:"prepared",projectRoot:e.paths.projectRoot,nativeRoot:e.paths.nativeRoot,createdAt:e.now.toISOString(),operations:[]}}async function PM(e,t,i,r){for(let a of[e,t])try{let o=await yt(a,r);if(o.kind!=="root-move")throw new Error(`Transaction ${r} is not a root move`);return{journal:o,paths:a}}catch(o){if(o.code!=="ENOENT")throw o}let n=ae.join(i,"runtime","transactions",r,"transaction.json");try{let a=await re({root:i,file:n,maxBytes:dM,label:`Staged Native root-move journal ${r}`}),o=JSON.parse(a.bytes.toString("utf8"));if(o.schema!=="comet.native.transaction.v1"||o.kind!=="root-move")throw new Error(`Invalid staged root-move journal: ${r}`);return{journal:o,paths:t}}catch(a){throw a.code!=="ENOENT"?a:new Error(`Native root-move journal is missing: ${r}`,{cause:a})}}async function PE(e){let t=xE(e.config,{...e.pending,stage:e.stage},e.activeArtifactRoot);return await hr(e.projectRoot,t),t}async function Ms(e){let t=e.config.native.pending_root_move;if(!t||t.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let i=xE(e.config,{id:t.id,fromArtifactRoot:t.fromArtifactRoot,toArtifactRoot:t.toArtifactRoot,stage:t.stage,...e.cleanup?{cleanup:e.cleanup}:{}},e.config.native.artifact_root);return await hr(e.projectRoot,i),i}async function rd(e){let t=e.config,i=t.native.pending_root_move;if(!i||i.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let r=i.cleanup;if(r&&r.kind!==e.kind)throw new Error(`Native root move has unfinished ${r.kind} cleanup; cannot start ${e.kind}`);let n=await at(e.target),a=await at(e.quarantine);if(n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(!r){if(!n&&!a)return t;if(!n&&a)throw new Error(`Native root-move cleanup quarantine is not transaction-bound: ${e.kind}`);let s=await bM({paths:e.stablePaths,id:e.id,kind:e.kind,entries:await Fs(e.target,{rejectSymlinks:!0})});r={kind:e.kind,state:"prepared",manifestHash:s},t=await Ms({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})}let o=await kM({paths:e.stablePaths,id:e.id,cleanup:r});if(n=await at(e.target),a=await at(e.quarantine),n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(n){if(r.state!=="prepared")throw new Error(`Native root-move cleanup target reappeared after quarantine: ${e.kind}`);await Ky({root:e.projectRoot,directory:e.target,quarantine:e.quarantine,label:e.label,beforeQuarantine:e.beforeQuarantine,afterQuarantine:e.afterQuarantine}),a=!0}if(!a){if(r.state!=="deleting")throw new Error(`Native root-move cleanup quarantine disappeared: ${e.kind}`);return Ms({projectRoot:e.projectRoot,config:t,id:e.id})}return await Am({quarantine:e.quarantine,manifest:o,exact:r.state!=="deleting"}),r.state==="prepared"&&(r={...r,state:"quarantined"},t=await Ms({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})),r.state==="quarantined"&&(r={...r,state:"deleting"},t=await Ms({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})),await SM({projectRoot:e.projectRoot,quarantine:e.quarantine,manifest:o,hooks:e.hooks}),Ms({projectRoot:e.projectRoot,config:t,id:e.id})}async function RM(e){let t=e.config,i=t.native.pending_root_move.stage;if(i==="copying"){if(!await at(e.sourcePaths.nativeRoot))throw new Error(`Native source root is missing: ${e.sourcePaths.nativeRoot}`);let s=vM(e.staging);t=await rd({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"restart-staging",stablePaths:e.sourcePaths,target:e.staging,quarantine:s,label:"Native root move stale staging removal",hooks:e.hooks}),await Fs(e.sourcePaths.nativeRoot,{rejectSymlinks:!0,excludedFiles:new Set([ae.resolve(e.lockFile)])}),await hM(e.sourcePaths.nativeRoot,e.staging,e.lockFile,e.destinationPaths.projectRoot),await za(e.sourcePaths.nativeRoot,e.staging,e.lockFile),t=await PE({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"ready"}),i="ready",await e.hooks?.afterRootMoveStage?.("ready",e.journal)}if(i==="ready"){if(await at(e.destinationPaths.nativeRoot)){if(await at(e.staging))throw new Error(`Native destination is occupied: ${e.destinationPaths.nativeRoot}`);await za(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile)}else{if(!await at(e.staging))throw new Error("Native move staging tree is missing");await za(e.sourcePaths.nativeRoot,e.staging,e.lockFile),await Bs.rename(e.staging,e.destinationPaths.nativeRoot)}t=await PE({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"switched",activeArtifactRoot:e.pending.toArtifactRoot}),i="switched",await e.hooks?.afterRootMoveStage?.("switched",e.journal)}if(i!=="switched")throw new Error(`Unsupported Native root-move stage: ${i}`);if(!await at(e.destinationPaths.nativeRoot))throw new Error(`Native destination root is missing: ${e.destinationPaths.nativeRoot}`);let r=mM(e.sourcePaths,e.pending.id);!t.native.pending_root_move?.cleanup&&await at(e.sourcePaths.nativeRoot)&&await za(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile),t=await rd({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"forward-source",stablePaths:e.destinationPaths,target:e.sourcePaths.nativeRoot,quarantine:r,label:"Native root move source removal",beforeQuarantine:()=>e.hooks?.beforeRootMoveSourceRemove?.(e.sourcePaths.nativeRoot),afterQuarantine:s=>e.hooks?.afterRootMoveSourceQuarantined?.(s),hooks:e.hooks}),await fM(e.destinationPaths);let n=await yt(e.destinationPaths,e.pending.id);await sa(e.destinationPaths,n,"commit");let a={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},o={...t,native:{...a,artifact_root:e.pending.toArtifactRoot}};return await hr(e.projectRoot,o),o}async function AE(e){let t=await ye(e.projectRoot),i=t?.native.pending_root_move;if(!t||!i)throw new Error("No pending Native root move was found");let r=await qe(e.projectRoot,i.fromArtifactRoot),n=await qe(e.projectRoot,i.toArtifactRoot),a=pM(n,i.id),o=await at(r.nativeRoot)?r:n,s=await pr(o,"root-move",`recover root ${i.id}`);try{let c;try{c=await PM(r,n,a,i.id)}catch(v){if(i.stage!=="copying"||!await at(r.nativeRoot))throw v;let m=EM({id:i.id,paths:r,now:new Date});await aN(r,m),c={journal:m,paths:r}}if(e.strategy==="continue"){let v=await RM({projectRoot:e.projectRoot,config:t,pending:i,sourcePaths:r,destinationPaths:n,staging:a,journal:c.journal,lockFile:s.file,hooks:e.hooks});return{activeNativeRoot:n.nativeRoot,config:v}}if(!await at(r.nativeRoot))throw new Error("Cannot roll back after the old Native root was removed; continue recovery");let l=SE(n.nativeRoot,i.id);!t.native.pending_root_move?.cleanup&&await at(n.nativeRoot)&&await za(r.nativeRoot,n.nativeRoot,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-destination")&&(t=await rd({projectRoot:e.projectRoot,config:t,id:i.id,kind:"rollback-destination",stablePaths:r,target:n.nativeRoot,quarantine:l,label:"Native root move rollback destination removal",hooks:e.hooks}));let u=SE(a,i.id);!t.native.pending_root_move?.cleanup&&await at(a)&&await za(r.nativeRoot,a,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-staging")&&(t=await rd({projectRoot:e.projectRoot,config:t,id:i.id,kind:"rollback-staging",stablePaths:r,target:a,quarantine:u,label:"Native root move rollback staging removal",hooks:e.hooks}));let d=await yt(r,i.id);await Ol(r,d);let f={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},h={...t,native:{...f,artifact_root:i.fromArtifactRoot}};return await hr(e.projectRoot,h),{activeNativeRoot:r.nativeRoot,config:h}}finally{await mr(s)}}var Ja=4096,CM=4096,xM=1024;async function Gr(e,t,i){try{let r=await wt({root:j(e,t),directory:t,label:"Native doctor directory",maxEntries:i});return await r.verify(),r.entries}catch(r){if(r.code==="ENOENT")return[];throw r}}async function ad(e,t){let i=new Map(e.map(r=>[je.resolve(r.file),{...r,file:je.resolve(r.file)}]));for(let{paths:r,file:n}of i.values()){let a;try{a=await Lo(n)}catch(o){return t.push({severity:"error",code:"lock-invalid",message:`Native recovery lock is invalid: ${o.message}`,path:n}),!1}if(a.status!=="missing"){if(a.status==="stale"){let o=await mh(r,n,a);if(o.status==="removed"){t.push({severity:"info",code:"stale-recovery-lock-removed",message:"Removed stale lock before explicit transaction recovery",path:n});continue}if(o.status==="missing")continue;a=o.diagnosis}return a.status==="stale"?(t.push({severity:"error",code:"lock-takeover-raced",message:"Native recovery lock changed while doctor was preparing stale takeover",path:n}),!1):(t.push({severity:"error",code:a.status==="active"?"lock-active":"lock-owner-unknown",message:a.status==="active"?"Native recovery lock is still owned by a live process":"Native recovery lock owner cannot be proven stale",path:n}),!1)}}return!0}async function AM(e,t){let i=KS(e),r;try{await T(e.projectRoot,i);let n=await zu(e);if(!n)return[];r=n}catch(n){return n.code==="ENOENT"?[]:[{severity:"error",code:"selection-invalid",message:`Native selection is invalid: ${n.message}`,path:i}]}if(r.schema!=="comet.selection.v2"||r.workflow!=="native"||typeof r.change!="string")return[{severity:"error",code:"selection-invalid",message:"Native selection has an invalid schema or change name",path:i}];try{return await zr(e,r.change)?[]:(await De(e,r.change),[])}catch(n){if(n.code!=="ENOENT")return[{severity:"error",code:"selection-target-invalid",message:`Selected Native change is invalid: ${n.message}`,path:i}]}return t?(await nd.rm(i,{force:!0}),[{severity:"info",code:"selection-cleared",message:`Cleared stale Native selection ${r.change}`,path:i}]):[{severity:"warning",code:"selection-stale",message:`Selected Native change does not exist: ${r.change}`,path:i}]}async function _M(e){let t=[];for(let i of[e.specsDir,e.changesDir,e.archiveDir,e.runtimeDir,e.locksDir,e.transactionsDir])try{await T(j(e,i),i)}catch(r){t.push({severity:"error",code:"native-path-unsafe",message:`Managed Native path is unsafe: ${r.message}`,path:i})}return t}async function TM(e,t){let i=[],r=[];for(let n of await Gr(e,e.transactionsDir,CM)){if(!n.isDirectory()||n.isSymbolicLink())continue;let a;try{a=await yt(e,n.name)}catch(o){i.push({severity:"error",code:"transaction-invalid",message:`Native transaction ${n.name} is invalid: ${o.message}`,path:je.join(e.transactionsDir,n.name)});continue}if(!(a.status==="committed"||a.status==="rolled-back")&&!(t.name&&a.change&&a.change!==t.name)){if(a.kind!=="archive"){r.push(a),i.push({severity:"error",code:"root-move-transaction-orphaned",message:`Root-move transaction ${a.id} is incomplete but project config has no matching pending move`});continue}if(t.repair&&t.recoveryStrategy)try{if(!await Xn([e],`doctor archive recovery ${a.id}`,async()=>await ad([{paths:e,file:je.join(e.locksDir,"root-move.lock")},{paths:e,file:je.join(e.locksDir,"archive.lock")}],i)?(await ZS({paths:e,transactionId:a.id,strategy:t.recoveryStrategy}),!0):!1)){r.push(a);continue}i.push({severity:"info",code:"archive-transaction-recovered",message:`${t.recoveryStrategy==="continue"?"Continued":"Rolled back"} archive transaction ${a.id}`})}catch(o){r.push(a),i.push({severity:"error",code:"archive-recovery-failed",message:`Archive recovery failed: ${o.message}`})}else r.push(a),i.push({severity:"error",code:"archive-transaction-incomplete",message:t.repair?`Archive transaction ${a.id} needs an explicit recovery strategy`:`Archive transaction ${a.id} is incomplete`,repair:t.recoveryStrategy??"continue"})}}return{findings:i,unfinished:r}}async function IM(e,t,i){let r=[];for(let n of await Gr(e,e.locksDir,xM)){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".lock"))continue;let a=je.join(e.locksDir,n.name);try{let o=await Lo(a);if(o.status==="active")r.push({severity:"warning",code:"lock-active",message:`Native lock is active for ${o.owner?.operation??"an operation"}`,path:a});else if(o.status==="unknown")r.push({severity:"warning",code:"lock-owner-unknown",message:"Native lock owner cannot be proven stale",path:a});else if(o.status==="stale")if(t&&i.length===0){let s=await mh(e,a,o);s.status==="removed"?r.push({severity:"info",code:"stale-lock-removed",message:"Removed a Native lock whose local owner process is absent",path:a}):s.status==="changed"&&r.push({severity:s.diagnosis.status==="active"?"warning":"error",code:"lock-takeover-raced",message:"Native lock changed while doctor was preparing stale takeover",path:a})}else r.push({severity:i.length>0?"error":"warning",code:"lock-stale",message:i.length>0?"Native lock is stale but an unfinished transaction still requires recovery":"Native lock owner process is absent",path:a})}catch(o){r.push({severity:"error",code:"lock-invalid",message:`Native lock metadata is invalid: ${o.message}`,path:a})}}return r}async function jM(e,t,i=5){let r=[],n=t?await bm(e,{maxVerifyFailures:i}).then(a=>a.filter(o=>o.name===t)):await bm(e,{maxVerifyFailures:i});if(t&&n.length===0)return[{severity:"error",code:"change-missing",message:`Native change does not exist: ${t}`}];for(let a of n){if(a.migrationRequired)continue;if(a.phase==="invalid"){r.push({severity:"error",code:"change-invalid",message:a.error??`Native change ${a.name} is invalid`,path:je.join(e.changesDir,a.name,Ie)});continue}let o=await Nm(e,a.name,{details:!0,maxVerifyFailures:i});for(let s of o.findings??[])s.code==="trajectory-tail-incomplete"||s.code==="checkpoint-progress-incomplete"||r.push({severity:s.severity,code:s.code,message:`${a.name}: ${s.message}`,...s.path?{path:je.join(e.projectRoot,s.path)}:{}})}return r}async function $M(e,t){let i=[],r=t.name?[t.name]:(await Gr(e,e.changesDir,Ja)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r)try{let a=await ma(e,n);if(a.status!=="repairable")continue;if(!t.repair){i.push({severity:"error",code:"trajectory-tail-incomplete",message:`Native trajectory for ${n} has an incomplete final line ${a.line}; ${a.discardedBytes} byte(s) are outside the last complete event`,path:a.file,repair:"truncate-tail"});continue}let o=await WN(e,n);o&&i.push({severity:"info",code:"trajectory-tail-repaired",message:`Removed the incomplete Native trajectory tail for ${n} and preserved all complete events`,path:o.file})}catch(a){i.push({severity:"error",code:"trajectory-tail-repair-failed",message:`Native trajectory tail repair failed for ${n}: ${a.message}`,path:je.join(H(e,n),"trajectory.jsonl")})}return i}async function OM(e,t){let i=[],r=t.name?[t.name]:(await Gr(e,e.changesDir,Ja)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=await Do(e,n);if(a.status==="missing"){i.push({severity:"warning",code:"runtime-missing",message:`Native Runtime for ${n} is missing; continue the change to rebuild it`,path:a.path});continue}if(a.status==="invalid"){i.push({severity:"error",code:"runtime-storage-invalid",message:a.message??`Native Runtime storage for ${n} is invalid`,path:a.path});continue}if(a.layout!=="legacy")continue;let o=nn(e,n),s=We(e,n);if(!t.repair){i.push({severity:"warning",code:"runtime-layout-legacy",message:`Native Runtime for ${n} still uses the legacy change-local layout`,path:o,repair:"migrate"});continue}try{await Xn([e],`migrate Runtime layout for ${n}`,async()=>{let c=await Zt({root:e.nativeRoot,directory:o,label:`Legacy Native Runtime ${n}`});await T(e.runtimeDir,s),await nd.mkdir(e.changesRuntimeDir,{recursive:!0});let l=await Zt({root:e.runtimeDir,directory:e.changesRuntimeDir,label:`Native Runtime migration target parent ${n}`});try{throw await nd.lstat(s),new Error(`Target Native Runtime already exists: ${s}`)}catch(u){if(u.code!=="ENOENT")throw u}await c.verify(),await l.verify(),await nd.rename(o,s)}),i.push({severity:"info",code:"runtime-layout-migrated",message:`Moved Native Runtime for ${n} to project-local .comet storage`,path:s})}catch(c){i.push({severity:"error",code:"runtime-layout-migration-failed",message:`Native Runtime layout migration failed for ${n}: ${c.message}`,path:o})}}return i}async function HM(e,t){let i=[],r=t.name?[t.name]:(await Gr(e,e.changesDir,Ja)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r)try{if(!await Qh(e,n))continue;if(!t.repair){i.push({severity:"warning",code:"workspace-identity-migration-required",message:`Native workspace identity for ${n} uses legacy external-probe or hash-only metadata`,path:ga(e,n),repair:"migrate"});continue}let a=await De(e,n);await tb({paths:e,name:n,revision:a.revision})&&i.push({severity:"info",code:"workspace-identity-migrated",message:`Replaced legacy workspace metadata for ${n} with process-free root identities`,path:ga(e,n)})}catch(a){i.push({severity:"error",code:"workspace-identity-migration-failed",message:`Native workspace identity migration failed for ${n}: ${a.message}`,path:ga(e,n)})}return i}async function DM(e,t){let i=[],r=t.name?[t.name]:(await Gr(e,e.changesDir,Ja)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=Ds(e,n);try{let o=await Ls(e,n),s=await vi(e,n);if(!o&&s.status==="current")continue;if(s.status==="runtime-incompatible"){i.push({severity:"error",code:"change-runtime-incompatible",message:s.message??`Native change ${n} requires a newer runtime`,path:je.join(e.changesDir,n,Ie)});continue}if(!t.repair){i.push({severity:"error",code:o?"schema-migration-incomplete":"schema-migration-required",message:o?`Native schema migration ${o.id} is incomplete for ${n}`:`Native change ${n} requires migration to the current schema`,path:o?a:je.join(e.changesDir,n,Ie),repair:"migrate"});continue}await pE({paths:e,name:n}),i.push({severity:"info",code:o?"schema-migration-recovered":"schema-migrated",message:`Migrated Native change ${n} to the current schema`,path:je.join(e.changesDir,n,Ie)})}catch(o){if(o.code==="ENOENT")continue;i.push({severity:"error",code:"schema-migration-failed",message:`Native schema migration failed for ${n}: ${o.message}`,path:a})}}return i}async function LM(e,t){let i=[],r=t.name?[t.name]:(await Gr(e,e.changesDir,Ja)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a;try{a=await Bi(e,n)}catch(o){if(o instanceof ks)continue;i.push({severity:"error",code:"transition-invalid",message:`Native transition journal is invalid: ${o.message}`,path:Ue(e,n)});continue}if(a){if(t.repair&&t.recoveryStrategy==="continue"){try{if(!await Xn([e],`doctor transition recovery ${n}`,async()=>await ad([{paths:e,file:je.join(e.locksDir,"root-move.lock")},{paths:e,file:je.join(e.locksDir,`transition-${n}.lock`)}],i)?(await $k(e,n),!0):!1))continue;i.push({severity:"info",code:"transition-recovered",message:`Continued Native phase transition ${a.id} for ${n}`,path:Ue(e,n)})}catch(o){i.push({severity:"error",code:"transition-recovery-failed",message:`Native transition recovery failed: ${o.message}`,path:Ue(e,n)})}continue}i.push({severity:"error",code:"transition-incomplete",message:t.repair&&t.recoveryStrategy==="rollback"?`Native phase transition ${a.id} only supports deterministic continue recovery`:`Native phase transition ${a.id} is incomplete for ${n}`,path:Ue(e,n),repair:"continue"})}}return i}async function MM(e,t){let i=[],r=t.name?[t.name]:(await Gr(e,e.changesDir,Ja)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=Hr(e,n),o;try{o=await Dr(e,n)}catch(s){if(s.code==="ENOENT")continue;i.push({severity:"error",code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}`,path:a});continue}if(o){if(!t.repair){i.push({severity:"error",code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${o.id} is incomplete for ${n}`,path:a});continue}try{if(!await Xn([e],`doctor checkpoint recovery ${n}`,async()=>await ad([{paths:e,file:je.join(e.locksDir,"root-move.lock")},{paths:e,file:je.join(e.locksDir,`transition-${n}.lock`)}],i)?(await Jk(e,n),!0):!1))continue;i.push({severity:"info",code:"checkpoint-progress-recovered",message:`Continued Native progress checkpoint ${o.id} for ${n}`,path:a})}catch(s){i.push({severity:"error",code:"checkpoint-progress-recovery-failed",message:`Native progress checkpoint recovery failed: ${s.message}`,path:a})}}}return i}async function Vs(e){let t=e.repair??!1,i=[],r=e.paths,n;try{n=await ye(r.projectRoot)}catch(c){return{healthy:!1,findings:[{severity:"error",code:"config-invalid",message:`Comet project config is invalid: ${c.message}`,path:r.configFile}]}}let a=!!n?.native.pending_root_move;if(n?.native.pending_root_move){let c=n.native.pending_root_move,[l,u]=await Promise.all([qe(r.projectRoot,c.fromArtifactRoot),qe(r.projectRoot,c.toArtifactRoot)]);if(t&&e.recoveryStrategy)try{if(!await ad([{paths:l,file:je.join(l.locksDir,"root-move.lock")},{paths:u,file:je.join(u.locksDir,"root-move.lock")}],i))return{healthy:!1,findings:i};let f=await AE({projectRoot:r.projectRoot,strategy:e.recoveryStrategy});r=await qe(r.projectRoot,f.config.native.artifact_root),a=!1,i.push({severity:"info",code:"root-move-recovered",message:`${e.recoveryStrategy==="continue"?"Continued":"Rolled back"} Native root move ${c.id}`})}catch(d){return i.push({severity:"error",code:"root-move-recovery-failed",message:`Native root recovery failed: ${d.message}`}),{healthy:!1,findings:i}}else i.push({severity:"error",code:"root-move-incomplete",message:`Native root move ${c.id} is ${c.stage}; inspect ${l.nativeRoot} and ${u.nativeRoot}`,repair:e.recoveryStrategy??"continue"})}let o=await _M(r);if(i.push(...o),o.length>0)return{healthy:!1,findings:i};let s=await TM(r,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy});return i.push(...s.findings),e.projectOnly||(i.push(...await OM(r,{name:e.name,repair:t})),i.push(...await DM(r,{name:e.name,repair:t})),i.push(...await HM(r,{name:e.name,repair:t})),i.push(...await $M(r,{name:e.name,repair:t})),i.push(...await LM(r,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy})),i.push(...await MM(r,{name:e.name,repair:t})),i.push(...await kE({paths:r,name:e.name,repair:t,now:e.now,deferAll:a||s.unfinished.length>0}))),i.push(...await IM(r,t,s.unfinished)),i.push(...await AM(r,t)),e.projectOnly||i.push(...await jM(r,e.name,n?.native.max_verify_failures??5)),{healthy:i.every(c=>c.severity==="info"),findings:i}}import{randomUUID as FM}from"node:crypto";import{promises as Fe}from"node:fs";import ht from"node:path";var Tm=class extends Error{peers;constructor(t){super(t.length===0?"Native Archive serial capability decision is stale":`Native Archive requires a serial capability decision: ${t.join(", ")}`),this.name="NativePortableArchiveOrderRequiredError",this.peers=[...t]}};function _E(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function TE(e,t){if(!/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error("Native portable Archive ref is invalid");let i=ht.join(e.archiveDir,t);if(!O(e.archiveDir,i))throw new Error("Native Archive path escaped");return i}async function od(e){try{return await Fe.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function IE(e,t){let i=ht.normalize(ht.resolve(e)),r=ht.normalize(ht.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}async function BM(e,t){let i;try{i=await Fe.readdir(e.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return null;throw n}let r=[];for(let n of i){if(!n.isDirectory()||n.isSymbolicLink())continue;let a=ht.join(e.archiveDir,n.name);try{let o=await Ze(ht.join(a,"comet-state.yaml"));o.name===t&&r.push({dir:a,state:o})}catch{}}if(r.length>1)throw new Error(`Multiple Native portable archives exist for ${t}`);return r[0]??null}async function VM(e,t){let i=await ia(e,{kind:"archive",change:t});return i?.kind==="archive"?i.journal:null}async function Cn(e,t){await Fe.mkdir(e.transactionsDir,{recursive:!0}),await ee(gr(e,{kind:"archive",change:t.change}),t,{containedRoot:e.runtimeDir})}async function qM(e){let t=new Set(e.state.spec_changes.map(({capability:a})=>a));if(t.size===0)return[];let i=Jt(e.paths.projectRoot);i.some(a=>IE(a,e.paths.projectRoot))||i.push(e.paths.projectRoot);let r=[];for(let a of i){let o=await ye(a);if(!o)continue;let s=await qe(a,o.native.artifact_root);r.some(c=>IE(c.changesDir,s.changesDir))||r.push(s)}r.length===0&&r.push(e.paths);let n=new Set;for(let a of r){let o;try{o=await Fe.readdir(a.changesDir,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of o)if(!(!s.isDirectory()||s.isSymbolicLink()||s.name===e.state.name))try{let c=await Ze(ht.join(a.changesDir,s.name,"comet-state.yaml"));c.status!=="done"&&c.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.name)}catch{let c=await iu(a,s.name).catch(()=>null);c?.state&&c.state.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.state.name)}}return[...n].sort((a,o)=>a.localeCompare(o,"en"))}function WM(e){if(e===void 0)return null;if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error("Native Archive serial capability decision is invalid");return e}async function zM(e){let t=ht.join(e.paths.specsDir,e.change.capability),i=ht.join(t,"spec.md");if(!O(e.paths.specsDir,i))throw new Error("Native canonical spec path escaped");if(e.change.operation==="remove"){let n;try{n=await Fe.lstat(e.paths.specsDir)}catch(c){if(c.code==="ENOENT")return;throw c}if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native canonical specs root is unsafe");let a;try{a=await Fe.lstat(t)}catch(c){if(c.code==="ENOENT")return;throw c}if(!a.isDirectory()||a.isSymbolicLink())throw new Error(`Canonical Native capability directory is unsafe: ${e.change.capability}`);let[o,s]=await Promise.all([Fe.realpath(e.paths.specsDir),Fe.realpath(t)]);if(!O(o,s))throw new Error("Native canonical capability path escaped");try{let c=await Fe.lstat(i);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await Fe.unlink(i)}catch(c){if(c.code!=="ENOENT")throw c}await Fe.rmdir(t).catch(c=>{if(c.code!=="ENOENT"&&c.code!=="ENOTEMPTY")throw c});return}if(e.change.source===null||e.change.content===null)throw new Error(`Native ${e.change.operation} spec requires frozen source content`);let r=ht.join(Lt(e.paths,e.state.name),e.change.source);await he(r,e.change.content,{containedRoot:e.paths.nativeRoot}),await Fe.mkdir(t,{recursive:!0}),await he(i,e.change.content,{containedRoot:e.paths.nativeRoot})}function jE(e){if(e.phase!=="archive"||e.status!=="active"||e.loop.stage!=="archive-ready"||e.verification_result!=="pass"||e.verification?.verdict!=="pass"||e.verification_report!=="verification.md")throw new Error(`Native change ${e.name} is not archive-ready`)}async function JM(e,t){let i=Lt(e,t.name),r=[];for(let n of t.spec_changes){if(n.source===null){r.push({...n,content:null});continue}let a=await Z({root:i,ref:n.source,maxBytes:null,includeHash:!1});r.push({...n,content:a.text})}return r}function GM(e,t){if(t.archived){if(t.status!=="done"||t.loop.stage!=="done"||t.state_version!==e.start_state_version+1)throw new Error("Native Archive transaction no longer matches the finalized portable state");return}if(t.state_version!==e.start_state_version)throw new Error("Native Archive transaction is stale for the current portable state");if(jE(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function Im(e){return se(e.paths,`archive portable change ${e.name}`,async()=>{let t=WM(e.serialFirstChange);if(t!==null&&t!==e.name)throw new Error("Native Archive --serial-first must name the change being archived");let i=await VM(e.paths,e.name),r=Lt(e.paths,e.name),n=await od(r),a=n?null:await BM(e.paths,e.name),o;if(n)o=await En(e.paths,e.name);else if(i)o=await Ze(ht.join(TE(e.paths,i.archive_ref),"comet-state.yaml"));else if(a)o=a.state;else throw new Error(`Native active change is missing: ${e.name}`);let s=await Ei(e.paths,e.name);if(n&&!o.archived&&i===null){let d=await zS({paths:e.paths,state:o});if(d.drifted){let f=d.reason??"Native confirmed requirements changed";throw await GS({paths:e.paths,state:o,reason:f}),new Error(`${f}; Native change returned to Shape and requires confirmation`)}}if(n&&!o.archived&&s?.finalVerification.status==="pending"&&o.verification_result==="pass"){let d=await JS({paths:e.paths,name:e.name});if(o=d.state,d.action==="rerun-final-verification")throw new Error("Native Supervisor final verification must be rerun for the current integration commit");d.action==="recorded-final-verification"&&(s=await Ei(e.paths,e.name))}let c=TE(e.paths,i?.archive_ref??_E(o)),l=await od(c);if(i&&GM(i,o),n&&l)throw new Error("Native active and archive directories both exist; doctor intervention is required");if(!n&&!i&&a){if(!o.archived||o.status!=="done"||o.loop.stage!=="done")throw new Error("Native archive exists without a completed portable state");return await $s(e.paths,o.name),await Fe.rm(We(e.paths,o.name),{recursive:!0,force:!0}),{change:o.name,archiveDir:a.dir,transactionId:`recovered-${o.state_version}`,state:o}}if(!i){if(!o.archived)jE(o);else if(o.status!=="done"||o.loop.stage!=="done")throw new Error("Native active archived state is inconsistent");let d=await qM({paths:e.paths,state:o});if(!o.archived&&d.length>0&&t!==o.name)throw new Tm(d);i={schema:Rl,id:FM(),change:o.name,start_state_version:o.archived?o.state_version-1:o.state_version,archive_ref:_E(o),status:o.archived?"state-finalized":"prepared",next_spec_index:o.archived?o.spec_changes.length:0,spec_changes:await JM(e.paths,o),created_at:new Date().toISOString()},await Cn(e.paths,i)}if(!n&&l&&i.status==="report-aligned")i={...i,status:"moved"},await Cn(e.paths,i);else if(!n&&l&&i.status!=="moved")throw new Error(`Native Archive layout contradicts transaction state ${i.status}; doctor intervention is required`);let u=!1;if(i.status==="prepared"&&s&&!o.archived&&(s=(await As({paths:e.paths,state:s})).state,u=!0),i.status==="prepared"){for(let d=i.next_spec_index;d<i.spec_changes.length;d+=1)await zM({paths:e.paths,state:o,change:i.spec_changes[d]}),i={...i,next_spec_index:d+1},await Cn(e.paths,i),await e.hooks?.afterSpecApplied?.(d);i={...i,status:"specs-applied"},await Cn(e.paths,i)}if(i.status==="specs-applied"){if(s&&!o.archived&&!u&&(s=(await As({paths:e.paths,state:s})).state,u=!0),!o.archived){let d={...o,phase:"archive",status:"done",state_version:o.state_version+1,archived:!0,blockers:[],loop:{...o.loop,stage:"done",next_action:null}};o=await sn({file:Pt(e.paths,o.name),expectedStateVersion:o.state_version,next:d,containedRoot:e.paths.nativeRoot})}i={...i,status:"state-finalized"},await Cn(e.paths,i),await e.hooks?.afterFinalState?.()}if(i.status==="state-finalized"){let d=await od(r)?r:c;if(await qu({file:ht.join(d,"verification.md"),state:o,...s?{supervisor:s}:{}}),await Vu({file:ht.join(d,"verification.md"),stateVersion:o.state_version})!=="aligned")throw new Error("Native final verification report is not aligned");i={...i,status:"report-aligned"},await Cn(e.paths,i),s&&!u&&(await As({paths:e.paths,state:s}),u=!0),await e.hooks?.afterReportAligned?.()}if(i.status==="report-aligned"){if(s&&!u&&await As({paths:e.paths,state:s}),await Fe.mkdir(e.paths.archiveDir,{recursive:!0}),await od(c))throw new Error(`Native Archive target already exists: ${c}`);await Fe.rename(r,c),i={...i,status:"moved"},await Cn(e.paths,i),await e.hooks?.afterMove?.()}return i.status==="moved"&&(await $s(e.paths,o.name),await Fe.rm(We(e.paths,o.name),{recursive:!0,force:!0}),await e.hooks?.afterRuntimeCleanup?.(),await Fe.rm(gr(e.paths,{kind:"archive",change:o.name}),{force:!0})),{change:o.name,archiveDir:c,transactionId:i.id,state:o}},{allowedPortableTransaction:{kind:"archive",change:e.name}})}function xn(e,t,i){return e.language==="zh-CN"?i:t}function UM(e,t){let i=r=>({required:!1,message:null,suggestedReply:null,agentInstruction:r});if(t&&e.phase==="shape"&&e.status==="active")return{required:!0,message:xn(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:xn(e,"Reply A or B","回复 A 或 B"),agentInstruction:xn(e,"Relay the two coordination choices and wait for the user decision. Do not treat a generic confirmation as a mode selection or run --confirmed without --coordination-mode.","转述这两个推进方式并等待用户选择。不要把普通“确认”视为已选择推进方式,也不要在没有 --coordination-mode 时运行 --confirmed。")};if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready"&&e.loop.next_action!=="await-verifier-result")return i(xn(e,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result")return i(xn(e,"Wait only while the dispatched Verifier task is still active. If the task did not start, failed, timed out, ended without a response, or was lost, immediately submit verifier-execution-error. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","仅在已派发的独立验收任务仍在运行时等待。如果任务未启动、执行失败、超时、结束后没有返回结果或已经丢失,立即提交 verifier-execution-error;只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。"));if(e.status==="blocked"&&e.blockers.some(({resolution_action:r})=>r==="retry-verifier"))return e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable")return e.language==="zh-CN"?{required:!0,message:"独立验收当前不可用,但你的代码和已经完成的检查都已安全保留。你可以直接重新尝试独立验收,也可以明确接受只有自动检查的结果。",suggestedReply:"重新尝试独立验收",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户选择。用户要求重试时执行 commandAlternatives 中的 retry-verifier;只有用户明确接受降级结果时才执行 confirm-verifier-unavailable。不要把“继续”视为接受降级结果,也不要要求用户处理文件、进程、服务或回调。"}:{required:!0,message:"Independent verification is currently unavailable, but your code and completed checks are safely preserved. You can retry independent verification directly or explicitly accept the automatic-check-only result.",suggestedReply:"Retry independent verification",agentInstruction:"Relay only message and suggestedReply, then wait for the user choice. If the user asks to retry, run retry-verifier from commandAlternatives; run confirm-verifier-unavailable only when the user explicitly accepts the degraded result. Do not treat “Continue” as accepting the degraded result, and do not ask the user to manage files, processes, services, or callbacks."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="resolve-verifier-blocker")return e.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="await-user"){let n=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",a=n?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。",o=n?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return e.language==="zh-CN"?{required:!0,message:a,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:o,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}return i(xn(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 $E(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function qs(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function OE(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function KM(e,t,i){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...i]}}function YM(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function XM(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 An(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:$E({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[qs("summary","--summary"),OE(e.name,e.flag)]}}function jm(e){return[An({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),An({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function sd(e,t){let i=YM(t)&&e.coordination_mode===void 0,r={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],userCommunication:UM(e,i)},n=a=>({kind:a,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...r,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:n("none")};if(e.status==="await-user")return e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...r,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[qs("summary","--summary")],commandAlternatives:[An({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...jm({change:e.name,stateVersion:e.state_version})],runnerAction:n("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...r,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[qs("summary","--summary")],commandAlternatives:[An({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),An({name:"confirm-verifier-unavailable",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-verifier-unavailable",flag:"--confirmed",confirmationInput:"user-decision"})],runnerAction:n("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...r,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[qs("summary","--summary")],commandAlternatives:[An({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...jm({change:e.name,stateVersion:e.state_version})],runnerAction:n("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...r,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[qs("summary","--summary")],commandAlternatives:jm({change:e.name,stateVersion:e.state_version}),runnerAction:n("none")}:{...r,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:n("none")};if(e.status==="blocked"){let a=e.blockers.some(({resolution_action:o})=>o==="retry-verifier");return{...r,disposition:"blocked",action:a?"retry-verifier":"none",commandArgs:a?$E({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:a?["summary"]:["repair-runtime"],inputOptions:a?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:n(a?"retry-verifier":"none")}}if(e.phase==="shape")return{...r,disposition:i?"await-user":"continue",action:"confirm-shape",commandArgs:XM({change:e.name,stateVersion:e.state_version,coordinationRequired:i}),requiredInputs:["summary",...i?["coordination-choice"]:[],"shared-understanding-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},...i?[KM("coordination-mode","--coordination-mode",Dy)]:[],OE("confirmed","--confirmed")],runnerAction:n("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...r,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:n("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...r,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:n("none")};if(t.allDone)return{...r,disposition:"continue",action:"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:n("builder-handoff")};let a=t.children.some(({status:s})=>s==="blocked"||s==="needs-reverify"),o=t.children.some(({status:s})=>s==="ready"||s==="active");return{...r,disposition:a&&!o?"blocked":"continue",action:"advance-children",commandArgs:null,requiredInputs:a&&!o?["resolve-child-blocker"]:["ready-children"],inputOptions:[],runnerAction:n("none")}}return{...r,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:n("builder-handoff")}}if(e.phase==="verify"){let a=e.loop.next_action==="await-verifier-result",o=!!e.children_contract_hash,s={id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0};return{...r,userCommunication:!a&&o?{...r.userCommunication,agentInstruction:`${r.userCommunication.agentInstruction} ${xn(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:r.userCommunication,disposition:"continue",action:a?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[a?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:a?[{kind:"verifier-response",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[s]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:[{id:"<acceptance-id>",result:"<passed|failed|blocked>",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:o?[s]:[]}}],runnerAction:n(a?"await-verifier":"dispatch-verifier")}}return e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived?{...r,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],commandAlternatives:[An({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:n("none")}:{...r,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:n("none")}}import{randomUUID as QM}from"node:crypto";import{promises as Ga}from"node:fs";import VE from"node:path";var $m=["evidence.md","repair.md","archive.md","checkpoint.md"],ZM="verification.md";async function eF(e){try{return await Ga.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Om(e,t){let i=ne(e,t),r=[gr(e,{kind:"migration",change:t}),nn(e,t),...$m.map(n=>VE.join(i,n))];return(await Promise.all(r.map(eF))).some(Boolean)}async function tF(e,t){let i=await ia(e,{kind:"migration",change:t});return i?.kind==="migration"?i.journal:null}async function HE(e,t){await Ga.mkdir(e.transactionsDir,{recursive:!0}),await ee(gr(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function DE(e,t,i={}){let r=i.removeVerificationReport===!1?$m:[...$m,ZM];await Promise.all([Ga.rm(We(e,t),{recursive:!0,force:!0}),Ga.rm(nn(e,t),{recursive:!0,force:!0}),...r.map(n=>Ga.rm(VE.join(ne(e,t),n),{force:!0}))])}async function LE(e,t){await qi(Wr(e,t.name),Br({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function ME(e,t){try{let i=await kt(e,t);if(i?.schema==="comet.native.workspace.v3")return{isolation:i.isolation,change_branch:i.changeBranch,target_branch:i.targetBranch,finish:i.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function FE(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let i=fe(e.projectRoot);if(!i.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(i.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${i.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!i.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function iF(e){let t=ne(e.paths,e.state.name),i=await Z({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),r=[];for(let n of e.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await Z({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return yl({briefMarkdown:i.text,specs:r})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function BE(e,t){let i=await iu(e,t);if(!i.state)throw new Error(`Native legacy change ${t} is unreadable`);return i.state}async function Ws(e){return se(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await tF(e.paths,e.name),i=await zr(e.paths,e.name)?await Ze(Pt(e.paths,e.name)):null;if(!t&&i)return await DE(e.paths,e.name,{removeVerificationReport:!1}),await LE(e.paths,i),i;let r=null,n=null;for(t||(r=await BE(e.paths,e.name),n=await ME(e.paths,e.name),FE(e.paths,n),t={schema:Pl,id:QM(),change:r.name,fromSchema:r.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await HE(e.paths,t));;){let a=Fy(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?i||(r??=await BE(e.paths,e.name),n??=await ME(e.paths,e.name),FE(e.paths,n),i=My({state:r,acceptance:await iF({paths:e.paths,state:r}),workspace:n,migratedAt:e.now}),await El(Pt(e.paths,e.name),i,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await DE(e.paths,e.name):a.action==="commit-transaction"&&(i??=await Ze(Pt(e.paths,e.name)),await LE(e.paths,i)),t={...t,status:a.nextStatus},await HE(e.paths,t)}return await Ga.rm(gr(e.paths,{kind:"migration",change:e.name}),{force:!0}),i??Ze(Pt(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as qE}from"node:fs";import WE from"node:path";function rF(e,t){let i=fe(e.projectRoot);if(t.workspace.change_branch!==null){if(!i.isGitWorktree)return"The portable change requires a Git branch/worktree";if(i.currentBranch!==t.workspace.change_branch)return`Expected Native change branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}`}return t.workspace.isolation==="current"?null:i.isGitWorktree?t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree?"The portable change requires its linked worktree":null:"The portable change requires a Git branch/worktree"}function nF(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function aF(e,t,i){let r=new Date().toISOString(),n=e.verification===null?e:on(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:Ii(t),completed_at:r});return ct({...n,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:i?nF(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 oF(e){try{let t=await Bu(e);return t===null?{local:null,reason:"missing"}:{local:t,reason:"available"}}catch(t){if(t.code&&t.code!=="ENOENT")throw t;return{local:null,reason:"invalid"}}}async function zE(e){return se(e.paths,`recover portable change ${e.name}`,async()=>{let t=await En(e.paths,e.name);if(t.status==="done")return await Wu({paths:e.paths,state:t}),{state:t,local:null,action:"done",reason:"done",message:"Archived Native changes do not require a local execution overlay."};let i=rF(e.paths,t);if(i)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:i};let r=Wr(e.paths,e.name),n=await oF(r),a=n.reason==="available"&&(n.local?.change!==t.name||n.local?.basedOnStateVersion!==t.state_version)?"stale":n.reason;if(a==="available"&&!e.preserveRunningExecution&&n.local?.execution!==null&&n.local?.execution?.status!=="completed"&&n.local&&(a="interrupted",n.local.execution?.status==="running"&&(n.local={...n.local,execution:{...n.local.execution,status:"interrupted"},checks:n.local.checks.map(f=>f.status==="planned"||f.status==="running"?{...f,status:"interrupted"}:f)},await qi(r,n.local,{containedRoot:e.paths.runtimeDir}))),a==="available")return await Wu({paths:e.paths,state:t}),{state:t,local:n.local,action:"resume-stable-boundary",reason:a,message:"Native local execution overlay matches the portable state."};let s=a==="interrupted"?n.local?.checks.find(f=>f.status==="interrupted"&&!f.repeatable):void 0;if(s){let f=fm({state:t,reason:`Check ${s.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await sn({file:Pt(e.paths,t.name),expectedStateVersion:t.state_version,next:f,containedRoot:e.paths.nativeRoot}),await qE.rm(WE.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let h=Br({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await qi(r,h,{containedRoot:e.paths.runtimeDir}),{state:t,local:h,action:"resume-stable-boundary",reason:a,message:`Native check ${s.id} was not repeatable; the change returned to Build for a new candidate.`}}let c=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",l=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",u=c||l;if(u){let f=aF(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 sn({file:Pt(e.paths,t.name),expectedStateVersion:t.state_version,next:f,containedRoot:e.paths.nativeRoot})}let d=Br({portableState:t,projectRoot:e.paths.projectRoot,branch:fe(e.paths.projectRoot).currentBranch});return await qE.mkdir(WE.dirname(Wr(e.paths,t.name)),{recursive:!0}),await qi(r,d,{containedRoot:e.paths.runtimeDir}),await Wu({paths:e.paths,state:t}),{state:t,local:d,action:u?"reverify":"resume-stable-boundary",reason:a,message:u?"Rebuilt local execution from the portable boundary; previous pass/execution was not reused.":`Rebuilt local execution from the portable ${t.phase}/${t.loop.stage} boundary.`}})}import{promises as GE}from"node:fs";import cF from"node:path";function sF(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function JE(e){let t=e.acceptance.reduce((i,r)=>({...i,[r.result]:i[r.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0});return{schema:"comet.native.state-summary.v1",name:e.name,phase:e.phase,status:e.status,state_version:e.state_version,...e.coordination_mode===void 0?{}:{coordination_mode:e.coordination_mode},loop:e.loop,acceptance:t,unresolved_acceptance_ids:e.acceptance.filter(({result:i})=>i==="failed"||i==="blocked").map(({id:i})=>i),verification_result:e.verification_result,blockers:e.blockers.slice(0,8).map(i=>({owner:i.owner,reason:sF(i.reason.text),acceptance_ids:i.acceptance_ids,resolution_action:i.resolution_action})),workspace:{isolation:e.workspace.isolation,change_branch:e.workspace.change_branch,target_branch:e.workspace.target_branch,finish:e.workspace.finish},archived:e.archived}}function lF(e,t,i){return`native-details-v2.${e}.${t}.${i.toString(36)}`}function uF(e,t,i){if(!e)return 0;let r=/^native-details-v2\.(\d+)\.(\d+)\.([0-9a-z]+)$/u.exec(e);if(!r||Number(r[1])!==t||Number(r[2])!==i)throw new Error("Native details cursor is stale or invalid");let n=Number.parseInt(r[3],36);if(!Number.isSafeInteger(n)||n<0)throw new Error("Native details cursor offset is invalid");return n}function dF(e,t,i){return[...e.acceptance.map(r=>({kind:"acceptance",value:r})),...e.spec_changes.map(r=>({kind:"spec-change",value:r})),...e.builder_handoff?[{kind:"builder-handoff",value:e.builder_handoff}]:[],...e.verification?[{kind:"verification",value:e.verification}]:[],...e.history.map(r=>({kind:"history",value:r})),{kind:"history-overflow",value:e.history_overflow},{kind:"workspace",value:e.workspace},...e.verification_report?[{kind:"verification-report",value:e.verification_report}]:[],...t?[{kind:"supervisor-integration",value:{...t.integration,worktree:"<worktree>",targetCommit:"<redacted>",headCommit:"<redacted>"}},{kind:"supervisor-final-verification",value:t.finalVerification},...t.children.map(r=>({kind:"supervisor-child",value:pF(r,i)})),...t.history.map(r=>({kind:"supervisor-history",value:mF(r,i)}))]:[]]}function fF(e){return e.acceptance.reduce((t,i)=>({...t,[i.result]:t[i.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0})}function UE(e,t){let i=fe(e.projectRoot),r=null;return t.workspace.change_branch!==null&&(i.isGitWorktree?i.currentBranch!==t.workspace.change_branch&&(r=`Expected branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}.`):r="The Native change requires a registered Git worktree."),r===null&&t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree&&(r="The Native change requires its linked worktree."),{projectRoot:cF.resolve(e.projectRoot),isolation:t.workspace.isolation,bindingState:r===null?"aligned":"mismatch",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:r}}function hF(e,t){return[e.projectRoot,t.integration.worktree,...t.children.flatMap(i=>[i.projectRoot,i.task?.projectRoot])].filter(i=>!!i).map(i=>i.replaceAll("/","\\")).sort((i,r)=>r.length-i.length)}function cd(e,t){return e===null?null:t.reduce((i,r)=>i.replaceAll(r,"<worktree>").replaceAll(r.replaceAll("\\","/"),"<worktree>"),e)}function pF(e,t){return{...e,projectRoot:e.projectRoot?"<worktree>":null,baseCommit:e.baseCommit?"<redacted>":null,candidateCommit:e.candidateCommit?"<redacted>":null,verifiedCommit:e.verifiedCommit?"<redacted>":null,integrationCommit:e.integrationCommit?"<redacted>":null,blocker:cd(e.blocker,t),task:e.task?{...e.task,projectRoot:"<worktree>",baseCommit:"<redacted>",runId:"<redacted>"}:null}}function mF(e,t){return{...e,runId:e.runId?"<redacted>":null,summary:cd(e.summary,t)??""}}async function Ua(e){let t=await US(e),i=JE(t.state),r=t.state.status==="active"&&t.state.loop.stage!=="done",n=await Ts({paths:e.paths,state:t.state}),a=await Ei(e.paths,e.name),o=a?{...UE(e.paths,t.state),projectRoot:"."}:UE(e.paths,t.state),s=sd(t.state,n),c=o.bindingState==="mismatch"?{...s,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["return-to-bound-workspace"],runnerAction:{...s.runnerAction,kind:"none"}}:s,l=a?hF(e.paths,a):[],u=a?(()=>{let h=a.children.filter(({status:y})=>y==="pending"||y==="ready").length,v=a.children.filter(({status:y})=>y==="active"||y==="verified").length,m=a.children.filter(({status:y})=>y==="integrated"||y==="archived").length,p=a.children.filter(({status:y})=>y==="blocked"||y==="needs-reverify").length,b=a.children.filter(({status:y})=>y==="active"||y==="blocked"||y==="needs-reverify").slice(0,16).map(y=>({name:y.name,summary:y.summary,projectRoot:y.task?.projectRoot??y.projectRoot?"<worktree>":null,reason:cd(y.blocker,l)})),g=a.children.flatMap(({blocker:y})=>{let E=cd(y,l);return E?[E]:[]}).slice(0,16);return{targetSpecs:t.state.spec_changes.length,implementationChildren:a.children.length,waiting:h,working:v,integrated:m,blocked:p,active:b,agents:{working:a.children.filter(({task:y})=>y!==null).length,completed:m},risks:g,nextAction:a.finalVerification.status==="passed"?"final-delivery":a.finalVerification.status==="pending"&&m===a.children.length?"parent-verification":h>0?"dispatch-ready-child":p>0?"resolve-blocker":"continue-supervisor"}})():null,d=e.details?(()=>{let h=a?.stateVersion??0,v=dF(t.state,a,l),m=uF(e.cursor,t.state.state_version,h),p=v.slice(m,m+32),b=m+p.length<v.length?lF(t.state.state_version,h,m+p.length):null;return{items:p,nextCursor:b,supervisorStateVersion:h}})():null,f=a?{schema:a.schema,parent:a.parent,integration:{branch:a.integration.branch,targetBranch:a.integration.targetBranch},finalVerification:{status:a.finalVerification.status,summary:a.finalVerification.summary},summary:u}:null;return{schema:"comet.native.status.v2",name:t.state.name,phase:t.state.phase,status:t.state.status,stateVersion:t.state.state_version,...t.state.coordination_mode===void 0?{}:{coordinationMode:t.state.coordination_mode},loop:t.state.loop,acceptance:fF(t.state),unresolvedAcceptanceIds:i.unresolved_acceptance_ids,verificationResult:t.state.verification_result,blockers:a?[]:i.blockers,workspace:o,localExecution:{status:r?t.localStatus:"not-expected",operation:t.localStatus==="available"?t.local?.execution??null:null},...n?{childSummary:n.children.reduce((h,v)=>({...h,[v.status]:(h[v.status]??0)+1}),{total:n.children.length}),readyChildren:n.readyChildren}:{},...f?{supervisor:f}:{},continuation:c,...e.details?{details:{stateVersion:t.state.state_version,...a?{supervisorStateVersion:d.supervisorStateVersion}:{},items:d.items,nextCursor:d.nextCursor,nextPageArgs:d.nextCursor?["comet","native","status",t.state.name,"--details","--cursor",d.nextCursor,"--json","--project-root",e.paths.projectRoot]:null}}:{}}}async function KE(e){let t;try{t=await GE.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}let i=[];for(let r of t)if(!(!r.isDirectory()||r.isSymbolicLink()))try{let n=await GE.readFile(`${Lt(e,r.name)}/comet-state.yaml`,"utf8");/^schema:\s*comet\.native\.v4\s*$/mu.test(n)&&i.push(r.name)}catch(n){if(n.code!=="ENOENT")throw n}return i.sort((r,n)=>r.localeCompare(n,"en"))}import zs from"path";import{realpathSync as _F}from"fs";var Gi={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function YE(e){return e?e.command?`${Gi.next} ${e.command}`:e.ask_user?`${Gi.next} ${e.ask_user}`:null:null}function XE(e,t){let i=[e.summary],r=YE(e.next);return r&&i.push(r),e.user_message&&i.push("",Gi.relay,e.user_message),t!==void 0&&i.push("",Gi.details,JSON.stringify(t,null,2)),`${i.join(`
269
269
  `)}
270
- `}function GE(e,t,i){let r=[e.summary],n=zE(e.next);return n&&r.push(n),e.user_message&&r.push("",Wi.relay,e.user_message),r.push("",`${Wi.detail} ${t}`),i!==void 0&&r.push("",Wi.details,JSON.stringify(i,null,2)),r.join(`
271
- `)}function J(e,t,i){return e==="zh-CN"?i:t}var Om={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function UE(e,t){return typeof e=="string"&&Om[e]?J(t,Om[e].en,Om[e].zh):typeof e=="string"?e:""}function Hm(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&typeof t.passed=="number"&&typeof t.failed=="number"&&typeof t.blocked=="number"&&typeof t.pending=="number"}function uF(e){let t={total:e.length,passed:0,failed:0,blocked:0,pending:0};for(let i of e){if(!i||typeof i!="object")return null;let r=i.result;if(r!=="passed"&&r!=="failed"&&r!=="blocked"&&r!=="pending")return null;t[r]+=1}return t}function KE(e,t){let i=[];e.failed>0&&i.push(J(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&i.push(J(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&i.push(J(t,`${e.pending} pending`,`${e.pending} 项待验`));let r=J(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return i.length>0?`${r} (${i.join(", ")})`:r}function YE(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.change!="string"||t.disposition!=="continue"&&t.disposition!=="await-user"&&t.disposition!=="blocked"&&t.disposition!=="done"||t.commandArgs!==null&&t.commandArgs!==void 0&&!Array.isArray(t.commandArgs))return!1;let i=t.userCommunication;return!!(i&&typeof i=="object"&&typeof i.required=="boolean"&&(i.message===null||typeof i.message=="string")&&typeof i.agentInstruction=="string")}function Dm(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function dF(e,t,i){return e==="done"?J(i,"complete","已完成"):e==="await-user"?J(i,"waiting for a user decision","等待用户决定"):e==="blocked"?J(i,"paused: needs attention","已暂停,需要处理"):t?J(i,"waiting for a user decision","等待用户决定"):J(i,"ready to continue","可继续推进")}function fF(e,t,i){let r=Dm(e),n=[];i&&n.push(i);let a=J(r,`Change ${e.change}`,`需求 ${e.change}`),o=UE(e.phase,r),s=dF(e.disposition,e.userCommunication.required,r);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(KE(t,r));let c=e.userCommunication,l=XE(e,r);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function XE(e,t){let i=e.userCommunication;if(e.disposition==="await-user"&&i.required)return{ask_user:J(t,"Relay the message below, wait for the user decision, then run the matching option (run with --json to see the exact alternative commands).","先转述下方信息并等待用户选择,再执行对应命令(完整候选命令以 --json 输出为准)。")};if(e.commandArgs&&e.commandArgs.length>0)return{command:e.commandArgs.join(" ")};if(e.disposition==="done")return{ask_user:J(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(e.disposition==="blocked")return{ask_user:J(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function hF(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function pF(e,t){let i=typeof e.name=="string"?e.name:"(unnamed)",r=UE(e.phase,t),n=e.status==="await-user"?J(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?J(t,"paused","已暂停"):e.status==="done"?J(t,"complete","已完成"):J(t,"in progress","进行中"),a=Hm(e.acceptance)?`${J(t,", ",",")}${KE(e.acceptance,t)}`:"";return` ${i} · ${r||String(e.phase??"?")} · ${n}${a}`}function mF(e){for(let t of e){let i=t.continuation;if(i?.userCommunication&&typeof i.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(i.userCommunication.agentInstruction))return"zh-CN"}return"en"}function vF(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.healthy!="boolean"?!1:t.findings===void 0||Array.isArray(t.findings)}function gF(e){if(e.healthy){let r=e.repaired?J("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):J("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=wF(e.continuation);return n?{summary:r,next:n}:{summary:r}}let i=Array.isArray(e.findings)?e.findings.length:0;return{summary:J("en",i>0?`Diagnostics found ${i} problem${i===1?"":"s"} that need attention before this change can continue.`:"Diagnostics found problems that need attention before this change can continue.",i>0?`诊断发现 ${i} 个需要处理的问题,处理后该需求才能继续。`:"诊断发现需要处理的问题,处理后该需求才能继续。"),next:{ask_user:J("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function wF(e){return YE(e)?XE(e,Dm(e)):void 0}function QE(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(vF(t))return gF(t);if(hF(t)){let r=mF(t.items);return{summary:[t.total===t.items.length?J(r,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):J(r,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>pF(a,r))].join(`
272
- `)}}let i=t.continuation;if(YE(i))return fF(i,yF(t),NF(t,Dm(i)));if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let r=t.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in t;return{summary:J(r,n?`Comet Native artifacts live under ${t.artifactRoot} (state root: ${t.nativeRoot}).`:`Initialized Comet Native at ${t.nativeRoot} (artifacts: ${t.artifactRoot}).`,n?`Comet Native 产物位于 ${t.artifactRoot}(状态根目录:${t.nativeRoot})。`:`Comet Native 已初始化于 ${t.nativeRoot}(产物目录:${t.artifactRoot})。`)}}}function yF(e){if(Hm(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let i=t;if(Hm(i.acceptance))return i.acceptance;if(Array.isArray(i.acceptance))return uF(i.acceptance)}return null}function NF(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return J(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let i=e.migration;return i&&typeof i=="object"&&i.completed===!0?J(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function ZE(e){let i=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"conflict":return{summary:J("en","This change was updated elsewhere while the command ran, so the command stopped without changing anything. Nothing was lost — reload the latest state and continue from there.","这条需求刚被另一个会话更新,本次命令未做任何改动。没有工作丢失——重新读取最新状态后继续即可。"),...typeof i.change=="string"?{next:{command:`comet native status ${i.change} --json`}}:{}};case"baseline-incomplete":return{summary:J("en","The safety snapshot for this change exceeded its configured size budget, so the command stopped before changing anything. Raise the snapshot limits in .comet/config.yaml or exclude out-of-scope data, then retry.","该需求的安全快照超出配置的容量预算,命令在改动任何内容前已停止。请在 .comet/config.yaml 中调高快照上限,或将范围外的数据加入排除列表后重试。"),next:{ask_user:J("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:J("en","This change runs in its own Git worktree to keep work isolated. Create the linked worktree first, then continue inside it.","这条需求需要在独立的 Git worktree 中执行以保证隔离。请先创建关联的 worktree,然后在其中继续。"),next:{ask_user:J("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:J("en","The change workspace is not fully prepared (for example a branch or worktree is missing). Finish the preparation steps, then retry.","需求的工作区尚未准备完成(例如分支或 worktree 缺失)。请先完成准备步骤,再重试。"),next:{ask_user:J("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:J("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:J("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}var eP=["--project-root <path> Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--verbose Append the raw machine projection after the human/agent text.","--help Show help without requiring an initialized project."],Mm=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",subcommands:["init Initialize Native project configuration.","root show Inspect the configured artifact root.","root move <artifact-root> Move the configured artifact root.","new <change-name> Create a change and prepare its workspace.","spec remove Record a complete capability removal intent.","show <change-name> Read formal artifacts and portable state.","status [<change-name>] Discover stable boundaries and Runner actions.","select <change-name> Select a change in its bound workspace.","next <change-name> Confirm or recover a stable workflow boundary.","archive <change-name> Preview and execute Archive plus workspace finish.","check <change-name> Run the read-only Native verification check.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state."],options:eP,output:"A human summary plus a NEXT step by default (RELAY TO USER blocks carry user decisions); use --json for the structured envelope, --verbose to append the raw machine projection.",examples:["comet native status --json","comet native status my-change --details --json","comet native next --help"]},init:{usage:"comet native init [--root <artifact-root>] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--root <artifact-root> Project-relative artifact root; defaults to docs.","--language en|zh-CN Language for newly generated Native artifacts."],output:"The resolved project configuration and Native paths.",examples:["comet native init --root docs --language zh-CN"]},root:{usage:"comet native root <show|move> [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move <artifact-root> Move Native artifacts and update project configuration."],output:"The current root projection or the completed move result.",examples:["comet native root show","comet native root move artifacts/native"]},"root show":{usage:"comet native root show",purpose:"Print the configured Native artifact root and resolved paths.",output:"The configured artifact root and resolved Native paths."},"root move":{usage:"comet native root move <artifact-root>",purpose:"Transactionally move Native artifacts and update project configuration.",output:"The source, destination, and committed root-move transaction result.",examples:["comet native root move artifacts/native"]},new:{usage:"comet native new <change-name> [--language en|zh-CN] [--isolation current|branch|worktree] [--change-branch <branch>] [--target-branch <branch>] [--worktree-path <path>]",purpose:"Create a portable Native change and prepare the requested branch or linked worktree.",options:["--language en|zh-CN Artifact language; defaults to project configuration.","--isolation <kind> current, branch, or worktree; defaults to current.","--change-branch <branch> Change branch; defaults to comet/<change-name>.","--target-branch <branch> Local base branch; defaults to the current branch.","--worktree-path <path> Worktree directory; defaults to .worktrees/<change-name>."],output:"The portable state, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN","comet native new session-timeout --isolation branch --target-branch main","comet native new session-timeout --isolation worktree --target-branch main"]},spec:{usage:"comet native spec remove <change-name> <capability>",purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove <change-name> <capability> Record a capability removal."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove <change-name> <capability>",purpose:"Record removal of a capability in the complete target specification.",output:"The updated portable state and continuation with the next Runner action."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"The portable state, brief, complete proposed Specs, and continuation; legacy state is reported as migration-required."},status:{usage:"comet native status [<change-name>] [--cursor <token>] [--details]",purpose:"Discover portable stable boundaries, parent child readiness, or the exact next Runner action.",options:["--cursor <token> Continue a status-list page, or a named details/history page.","--details Include one fixed-size page of acceptance, Spec, handoff, verification, history, workspace, and report details."],output:"A compact v2 status page or one compact Loop projection with local execution availability. Use --details and --cursor to read fixed-size detail pages; parent changes expose childSummary and readyChildren.",examples:["comet native status --json","comet native status session-timeout --details --json"]},select:{usage:"comet native select <change-name>",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next <change-name> --summary <text> [--confirmed] [--coordination-mode multi-session|single-session] [--accept-result|--revise-implementation|--revise-requirements|--retry-verifier|--resolve-verifier-blocker] [--max-parallel <n>] [--expected-state-version <n>] [--expected-action <action>]
273
- comet native next <change-name> --runner-input <json-file>`,purpose:"Confirm or recover an Agent boundary, advance parent child changes, handle Supervisor task operations, or use one skill-coordinated JSON bridge for Builder handoff, check-plan dispatch, and Verifier response/error.",options:["--summary <text> Required transition or recovery summary.","--confirmed Confirm Shape or an explicitly degraded verifier-unavailable fallback before Archive.","--coordination-mode multi-session|single-session Required when confirming a multi-child Supervisor Shape.","--accept-result Accept the current skill-coordinated Verify result and make it archive-ready.","--revise-implementation Keep confirmed requirements unchanged and return Verify to Build for implementation revision.","--revise-requirements Return Verify or Archive to Shape when user-visible goals or acceptance criteria must change.","--retry-verifier Retry a blocked Verifier execution when the continuation allows it.","--resolve-verifier-blocker Resolve a semantic Verifier blocker without changing the candidate, then dispatch a new attempt.","--max-parallel <n> Supervisor task concurrency cap; defaults to 2, use 1 for serial fallback.","--expected-state-version <n> Continuation-issued guard that rejects stale public transition decisions.","--expected-action <action> Continuation-issued guard that binds the public transition decision to its intended action.","--runner-input <file> Skill-coordinated JSON: builder-handoff, dispatch-verifier, verifier-response, verifier-execution-error, or verifier-unavailable. Identity/provider/execution/candidate fields are rejected."," builder-handoff fields: kind, summary, addressed_acceptance_ids, checks, known_limits, review. review fields: status=passed, summary, reviewer_execution_ref from a separate read-only review."," dispatch-verifier fields: kind, checks (an explicitly resolved plan; [] is allowed)."," verifier-response fields: kind, response (request-checks or final-result)."," verifier-execution-error fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch."," verifier-unavailable fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch; accepted only after the explicit Runtime check plan completed and passed."," Supervisor task fields: supervisor-builder-result (child, runId, candidateCommit), supervisor-builder-failure (child, runId, reason), supervisor-verifier-result (child, runId, verdict, verification data), supervisor-reconnect (child, runId), supervisor-cancel (child, runId, reason), or supervisor-integrate (child, checks)."],output:'A compact portable state summary, explicit skill-coordinated label, Runtime-owned check results, scoped verifierDispatch, bounded request-check response, continuation.runnerAction, machine-readable continuation.inputOptions, and continuation.userCommunication with a user-ready message and Agent relay guidance. Read acceptance text and other long fields from paged status --details output. Human-readable verification statuses include "Host independently verified", "Checks completed, but your confirmation is required", "Full verification was unavailable; only automatic checks completed", and "You accepted the incomplete verification result". This generic bridge is not trusted identity attestation: a passing result waits for explicit user confirmation before Archive.',examples:['comet native next session-timeout --summary "Shape confirmed" --confirmed','comet native next session-timeout --summary "Current result accepted" --accept-result','comet native next session-timeout --summary "Implementation needs revision" --revise-implementation','comet native next session-timeout --summary "Acceptance criteria changed" --revise-requirements','comet native next session-timeout --summary "Retry verifier infrastructure" --retry-verifier','comet native next session-timeout --summary "Retry semantic verification" --resolve-verifier-blocker',"comet native next session-timeout --runner-input <temporary-json-file>"]},archive:{usage:`comet native archive <change-name> --dry-run [--finish merge|push|pull-request|keep]
274
- comet native archive <change-name> [--confirmed] [--serial-first <current-change>]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Inspect readiness without rerunning verification.","--finish <action> Persist merge, push, pull-request, or keep for an isolated workspace.","--serial-first <current-change> During execution only, confirm that this change archives before detected capability peers; the value must equal <change-name>.","--confirmed Confirm Archive when project policy requires it."],output:"Readiness plus continuation, or the completed Archive transaction and workspace finish result; Archive does not repeat verification."},doctor:{usage:"comet native doctor [<change-name>] [--repair]",purpose:"Inspect portable state, migrate a legacy active change, or rebuild its local execution overlay.",options:["--repair Apply deterministic migration or rebuild from the portable stable boundary."],output:"Health, migration or recovery details, and the continuation with the next Runner action."}});function Lm(e,t){return`${e}:
270
+ `}function QE(e,t,i){let r=[e.summary],n=YE(e.next);return n&&r.push(n),e.user_message&&r.push("",Gi.relay,e.user_message),r.push("",`${Gi.detail} ${t}`),i!==void 0&&r.push("",Gi.details,JSON.stringify(i,null,2)),r.join(`
271
+ `)}function J(e,t,i){return e==="zh-CN"?i:t}var Hm={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function ZE(e,t){return typeof e=="string"&&Hm[e]?J(t,Hm[e].en,Hm[e].zh):typeof e=="string"?e:""}function Dm(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 vF(e){let t={total:e.length,passed:0,failed:0,blocked:0,pending:0};for(let i of e){if(!i||typeof i!="object")return null;let r=i.result;if(r!=="passed"&&r!=="failed"&&r!=="blocked"&&r!=="pending")return null;t[r]+=1}return t}function eP(e,t){let i=[];e.failed>0&&i.push(J(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&i.push(J(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&i.push(J(t,`${e.pending} pending`,`${e.pending} 项待验`));let r=J(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return i.length>0?`${r} (${i.join(", ")})`:r}function tP(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.change!="string"||t.disposition!=="continue"&&t.disposition!=="await-user"&&t.disposition!=="blocked"&&t.disposition!=="done"||t.commandArgs!==null&&t.commandArgs!==void 0&&!Array.isArray(t.commandArgs))return!1;let i=t.userCommunication;return!!(i&&typeof i=="object"&&typeof i.required=="boolean"&&(i.message===null||typeof i.message=="string")&&typeof i.agentInstruction=="string")}function Lm(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function gF(e,t,i){return e==="done"?J(i,"complete","已完成"):e==="await-user"?J(i,"waiting for a user decision","等待用户决定"):e==="blocked"?J(i,"paused: needs attention","已暂停,需要处理"):t?J(i,"waiting for a user decision","等待用户决定"):J(i,"ready to continue","可继续推进")}function wF(e,t,i){let r=Lm(e),n=[];i&&n.push(i);let a=J(r,`Change ${e.change}`,`需求 ${e.change}`),o=ZE(e.phase,r),s=gF(e.disposition,e.userCommunication.required,r);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(eP(t,r));let c=e.userCommunication,l=iP(e,r);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function iP(e,t){let i=e.userCommunication;if(e.disposition==="await-user"&&i.required)return{ask_user:J(t,"Relay the message below, wait for the user decision, then run the matching option (run with --json to see the exact alternative commands).","先转述下方信息并等待用户选择,再执行对应命令(完整候选命令以 --json 输出为准)。")};if(e.commandArgs&&e.commandArgs.length>0)return{command:e.commandArgs.join(" ")};if(e.disposition==="done")return{ask_user:J(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(e.disposition==="blocked")return{ask_user:J(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function yF(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function NF(e,t){let i=typeof e.name=="string"?e.name:"(unnamed)",r=ZE(e.phase,t),n=e.status==="await-user"?J(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?J(t,"paused","已暂停"):e.status==="done"?J(t,"complete","已完成"):J(t,"in progress","进行中"),a=Dm(e.acceptance)?`${J(t,", ",",")}${eP(e.acceptance,t)}`:"";return` ${i} · ${r||String(e.phase??"?")} · ${n}${a}`}function bF(e){for(let t of e){let i=t.continuation;if(i?.userCommunication&&typeof i.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(i.userCommunication.agentInstruction))return"zh-CN"}return"en"}function kF(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 SF(e){if(e.healthy){let r=e.repaired?J("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):J("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=EF(e.continuation);return n?{summary:r,next:n}:{summary:r}}let i=Array.isArray(e.findings)?e.findings.length:0;return{summary:J("en",i>0?`Diagnostics found ${i} problem${i===1?"":"s"} that need attention before this change can continue.`:"Diagnostics found problems that need attention before this change can continue.",i>0?`诊断发现 ${i} 个需要处理的问题,处理后该需求才能继续。`:"诊断发现需要处理的问题,处理后该需求才能继续。"),next:{ask_user:J("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function EF(e){return tP(e)?iP(e,Lm(e)):void 0}function rP(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(kF(t))return SF(t);if(yF(t)){let r=bF(t.items);return{summary:[t.total===t.items.length?J(r,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):J(r,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>NF(a,r))].join(`
272
+ `)}}let i=t.continuation;if(tP(i))return wF(i,PF(t),RF(t,Lm(i)));if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let r=t.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in t;return{summary:J(r,n?`Comet Native artifacts live under ${t.artifactRoot} (state root: ${t.nativeRoot}).`:`Initialized Comet Native at ${t.nativeRoot} (artifacts: ${t.artifactRoot}).`,n?`Comet Native 产物位于 ${t.artifactRoot}(状态根目录:${t.nativeRoot})。`:`Comet Native 已初始化于 ${t.nativeRoot}(产物目录:${t.artifactRoot})。`)}}}function PF(e){if(Dm(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let i=t;if(Dm(i.acceptance))return i.acceptance;if(Array.isArray(i.acceptance))return vF(i.acceptance)}return null}function RF(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return J(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let i=e.migration;return i&&typeof i=="object"&&i.completed===!0?J(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function nP(e){let i=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"conflict":return{summary:J("en","This change was updated elsewhere while the command ran, so the command stopped without changing anything. Nothing was lost — reload the latest state and continue from there.","这条需求刚被另一个会话更新,本次命令未做任何改动。没有工作丢失——重新读取最新状态后继续即可。"),...typeof i.change=="string"?{next:{command:`comet native status ${i.change} --json`}}:{}};case"baseline-incomplete":return{summary:J("en","The safety snapshot for this change exceeded its configured size budget, so the command stopped before changing anything. Raise the snapshot limits in .comet/config.yaml or exclude out-of-scope data, then retry.","该需求的安全快照超出配置的容量预算,命令在改动任何内容前已停止。请在 .comet/config.yaml 中调高快照上限,或将范围外的数据加入排除列表后重试。"),next:{ask_user:J("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:J("en","This change runs in its own Git worktree to keep work isolated. Create the linked worktree first, then continue inside it.","这条需求需要在独立的 Git worktree 中执行以保证隔离。请先创建关联的 worktree,然后在其中继续。"),next:{ask_user:J("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:J("en","The change workspace is not fully prepared (for example a branch or worktree is missing). Finish the preparation steps, then retry.","需求的工作区尚未准备完成(例如分支或 worktree 缺失)。请先完成准备步骤,再重试。"),next:{ask_user:J("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:J("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:J("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}var aP=["--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."],Fm=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",subcommands:["init Initialize Native project configuration.","root show Inspect the configured artifact root.","root move <artifact-root> Move the configured artifact root.","new <change-name> Create a change and prepare its workspace.","spec remove Record a complete capability removal intent.","show <change-name> Read formal artifacts and portable state.","status [<change-name>] Discover stable boundaries and Runner actions.","select <change-name> Select a change in its bound workspace.","next <change-name> Confirm or recover a stable workflow boundary.","archive <change-name> Preview and execute Archive plus workspace finish.","check <change-name> Run the read-only Native verification check.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state."],options:aP,output:"A human summary plus a NEXT step by default (RELAY TO USER blocks carry user decisions); use --json for the structured envelope, --verbose to append the raw machine projection.",examples:["comet native status --json","comet native status my-change --details --json","comet native next --help"]},init:{usage:"comet native init [--root <artifact-root>] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--root <artifact-root> Project-relative artifact root; defaults to docs.","--language en|zh-CN Language for newly generated Native artifacts."],output:"The resolved project configuration and Native paths.",examples:["comet native init --root docs --language zh-CN"]},root:{usage:"comet native root <show|move> [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move <artifact-root> Move Native artifacts and update project configuration."],output:"The current root projection or the completed move result.",examples:["comet native root show","comet native root move artifacts/native"]},"root show":{usage:"comet native root show",purpose:"Print the configured Native artifact root and resolved paths.",output:"The configured artifact root and resolved Native paths."},"root move":{usage:"comet native root move <artifact-root>",purpose:"Transactionally move Native artifacts and update project configuration.",output:"The source, destination, and committed root-move transaction result.",examples:["comet native root move artifacts/native"]},new:{usage:"comet native new <change-name> [--language en|zh-CN] [--isolation current|branch|worktree] [--change-branch <branch>] [--target-branch <branch>] [--worktree-path <path>]",purpose:"Create a portable Native change and prepare the requested branch or linked worktree.",options:["--language en|zh-CN Artifact language; defaults to project configuration.","--isolation <kind> current, branch, or worktree; defaults to current.","--change-branch <branch> Change branch; defaults to comet/<change-name>.","--target-branch <branch> Local base branch; defaults to the current branch.","--worktree-path <path> Worktree directory; defaults to .worktrees/<change-name>."],output:"The portable state, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN","comet native new session-timeout --isolation branch --target-branch main","comet native new session-timeout --isolation worktree --target-branch main"]},spec:{usage:"comet native spec remove <change-name> <capability>",purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove <change-name> <capability> Record a capability removal."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove <change-name> <capability>",purpose:"Record removal of a capability in the complete target specification.",output:"The updated portable state and continuation with the next Runner action."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"The portable state, brief, complete proposed Specs, and continuation; legacy state is reported as migration-required."},status:{usage:"comet native status [<change-name>] [--cursor <token>] [--details]",purpose:"Discover portable stable boundaries, parent child readiness, or the exact next Runner action.",options:["--cursor <token> Continue a status-list page, or a named details/history page.","--details Include one fixed-size page of acceptance, Spec, handoff, verification, history, workspace, and report details."],output:"A compact v2 status page or one compact Loop projection with local execution availability. Use --details and --cursor to read fixed-size detail pages; parent changes expose childSummary and readyChildren.",examples:["comet native status --json","comet native status session-timeout --details --json"]},select:{usage:"comet native select <change-name>",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next <change-name> --summary <text> [--confirmed] [--coordination-mode multi-session|single-session] [--accept-result|--revise-implementation|--revise-requirements|--retry-verifier|--resolve-verifier-blocker] [--max-parallel <n>] [--expected-state-version <n>] [--expected-action <action>]
273
+ comet native next <change-name> --runner-input <json-file>`,purpose:"Confirm or recover an Agent boundary, advance parent child changes, handle Supervisor task operations, or use one skill-coordinated JSON bridge for Builder handoff, check-plan dispatch, and Verifier response/error.",options:["--summary <text> Required transition or recovery summary.","--confirmed Confirm Shape or an explicitly degraded verifier-unavailable fallback before Archive.","--coordination-mode multi-session|single-session Required when confirming a multi-child Supervisor Shape.","--accept-result Accept the current skill-coordinated Verify result and make it archive-ready.","--revise-implementation Keep confirmed requirements unchanged and return Verify to Build for implementation revision.","--revise-requirements Return Verify or Archive to Shape when user-visible goals or acceptance criteria must change.","--retry-verifier Retry a 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]
274
+ comet native archive <change-name> [--confirmed] [--serial-first <current-change>]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Inspect readiness without rerunning verification.","--finish <action> Persist merge, push, pull-request, or keep for an isolated workspace.","--serial-first <current-change> During execution only, confirm that this change archives before detected capability peers; the value must equal <change-name>.","--confirmed Confirm Archive when project policy requires it."],output:"Readiness plus continuation, or the completed Archive transaction and workspace finish result; Archive does not repeat verification."},doctor:{usage:"comet native doctor [<change-name>] [--repair]",purpose:"Inspect portable state, migrate a legacy active change, or rebuild its local execution overlay.",options:["--repair Apply deterministic migration or rebuild from the portable stable boundary."],output:"Health, migration or recovery details, and the continuation with the next Runner action."}});function Mm(e,t){return`${e}:
275
275
  ${t.map(i=>` ${i}`).join(`
276
- `)}`}function bF(e){let t=e.filter(r=>r!=="--help");if(t.length===0)return"";let i=t.slice(0,2).join(" ");return Mm[i]||t.length>1&&Mm[t[0]]?.subcommands?i:t[0]}function kF(e=[]){let t=bF(e),i=Mm[t];if(!i)throw new Error(`Unknown Native help topic: ${t}`);let r=[`Usage: ${i.usage}`,"",i.purpose];i.subcommands&&r.push("",Lm("Commands",i.subcommands));let n=t===""?i.options:[...i.options??[],...eP];return n&&n.length>0&&r.push("",Lm("Options",n)),r.push("",`Output:
277
- ${i.output}`),i.examples&&r.push("",Lm("Examples",i.examples)),t===""&&r.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${r.join(`
276
+ `)}`}function CF(e){let t=e.filter(r=>r!=="--help");if(t.length===0)return"";let i=t.slice(0,2).join(" ");return Fm[i]||t.length>1&&Fm[t[0]]?.subcommands?i:t[0]}function xF(e=[]){let t=CF(e),i=Fm[t];if(!i)throw new Error(`Unknown Native help topic: ${t}`);let r=[`Usage: ${i.usage}`,"",i.purpose];i.subcommands&&r.push("",Mm("Commands",i.subcommands));let n=t===""?i.options:[...i.options??[],...aP];return n&&n.length>0&&r.push("",Mm("Options",n)),r.push("",`Output:
277
+ ${i.output}`),i.examples&&r.push("",Mm("Examples",i.examples)),t===""&&r.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${r.join(`
278
278
  `)}
279
- `}}var SF=kF().usage;var F8=10*1024*1024,Bt=class extends Error{};function qs(e,t){let i=e.flatMap((r,n)=>r===t?[n]:[]);if(i.length>1)throw new Bt(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function nd(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new Bt(`${t} may only be provided once`);if(i.length===0)return;let r=i[0],n=e[r+1];if(n===void 0||n.startsWith("--"))throw new Bt(`${t} requires a value`);return e.splice(r,2),n}function iP(e){if(e.length>0)throw new Bt(`Unexpected argument: ${e[0]}`)}function Fm(e,t){let i=Vs.normalize(tP(e)),r=Vs.normalize(tP(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function tP(e){let t=Vs.resolve(e);try{return EF.native(t)}catch{return t}}function PF(e){let t=Vs.resolve(e),i=fe(process.cwd());if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return t;let r=fe(t);return!r.isGitWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null||!Fm(i.primaryWorktreeRoot,r.primaryWorktreeRoot)||Fm(i.currentWorktreeRoot,r.currentWorktreeRoot)?t:Fm(process.cwd(),i.currentWorktreeRoot)?Vs.resolve(process.cwd()):i.currentWorktreeRoot}async function rP(e){return e?PF(e):ch(process.cwd())}async function nP(e){let t=await ye(e);return qe(e,t?.native.artifact_root??"docs")}function aP(e){return JSON.stringify(e,null,2)+`
280
- `}function zi(e,t,i){return{command:e,exitCode:0,data:t,text:i??aP(t)}}function RF(e,t){if(t instanceof Bt)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Fu)return{command:e,exitCode:73,data:{capability:t.capability,expectedHash:t.expectedHash,actualHash:t.actualHash,canonicalPath:t.canonicalPath},error:{code:"conflict",message:t.message}};if(t instanceof Is)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof es)return{command:e,exitCode:73,data:{change:t.change,expectedRevision:t.expectedRevision,actualRevision:t.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:t.message}};if(t instanceof ts)return{command:e,exitCode:73,data:{requestedIsolation:t.requestedIsolation,activeChanges:t.activeChanges,requiredAction:"create-native-worktree"},error:{code:"workspace-isolation-required",message:t.message}};if(t instanceof Cu)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof ha)return{command:e,exitCode:65,data:{change:t.change,complete:!1,omittedCount:t.omittedCount,omittedByReason:t.omittedByReason,samplePaths:t.samplePaths,sampleTruncated:t.sampleTruncated,effectiveLimits:t.effectiveLimits,policyHash:t.policyHash,configPath:".comet/config.yaml",supportedFixes:["increase native.snapshot.max_files, native.snapshot.max_total_bytes, or native.snapshot.max_duration_ms","add an explicit native.snapshot.exclude pattern for data outside implementation scope"],requiredAction:"resolve-native-baseline"},error:{code:"baseline-incomplete",message:t.message}};if(t instanceof Hr)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof bs)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let i=t.code;if(i&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(i))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let r=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:r?73:65,error:{code:r?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function oP(e,t){let i=RF(e,t),r=i.error;if(!r)return i;let n=ZE({code:r.code,message:r.message,data:i.data});return n?{...i,envelope:n}:i}function sP(e,t,i=!1){let r=e.envelope??QE(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...r===void 0?{}:{summary:r.summary,...r.next===void 0?{}:{next:r.next},...r.user_message===void 0?{}:{user_message:r.user_message}},...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
281
- `}:e.error?{exitCode:e.exitCode,stderr:r?GE(r,e.error.message,i?e.data:void 0):e.error.message}:r?{exitCode:e.exitCode,stdout:JE(r,i?e.data:void 0)}:i&&e.text!==void 0&&e.data!==void 0&&e.text!==aP(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
282
- ${Wi.details}
279
+ `}}var AF=xF().usage;var K8=10*1024*1024,Bt=class extends Error{};function Js(e,t){let i=e.flatMap((r,n)=>r===t?[n]:[]);if(i.length>1)throw new Bt(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function ld(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new Bt(`${t} may only be provided once`);if(i.length===0)return;let r=i[0],n=e[r+1];if(n===void 0||n.startsWith("--"))throw new Bt(`${t} requires a value`);return e.splice(r,2),n}function sP(e){if(e.length>0)throw new Bt(`Unexpected argument: ${e[0]}`)}function Bm(e,t){let i=zs.normalize(oP(e)),r=zs.normalize(oP(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function oP(e){let t=zs.resolve(e);try{return _F.native(t)}catch{return t}}function TF(e){let t=zs.resolve(e),i=fe(process.cwd());if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return t;let r=fe(t);return!r.isGitWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null||!Bm(i.primaryWorktreeRoot,r.primaryWorktreeRoot)||Bm(i.currentWorktreeRoot,r.currentWorktreeRoot)?t:Bm(process.cwd(),i.currentWorktreeRoot)?zs.resolve(process.cwd()):i.currentWorktreeRoot}async function cP(e){return e?TF(e):dh(process.cwd())}async function lP(e){let t=await ye(e);return qe(e,t?.native.artifact_root??"docs")}function uP(e){return JSON.stringify(e,null,2)+`
280
+ `}function Ui(e,t,i){return{command:e,exitCode:0,data:t,text:i??uP(t)}}function IF(e,t){if(t instanceof Bt)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Ju)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 Os)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof ns)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 as)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 Iu)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof ya)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 Lr)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof Ps)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let i=t.code;if(i&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(i))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let r=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:r?73:65,error:{code:r?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function dP(e,t){let i=IF(e,t),r=i.error;if(!r)return i;let n=nP({code:r.code,message:r.message,data:i.data});return n?{...i,envelope:n}:i}function fP(e,t,i=!1){let r=e.envelope??rP(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...r===void 0?{}:{summary:r.summary,...r.next===void 0?{}:{next:r.next},...r.user_message===void 0?{}:{user_message:r.user_message}},...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
281
+ `}:e.error?{exitCode:e.exitCode,stderr:r?QE(r,e.error.message,i?e.data:void 0):e.error.message}:r?{exitCode:e.exitCode,stdout:XE(r,i?e.data:void 0)}:i&&e.text!==void 0&&e.data!==void 0&&e.text!==uP(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
282
+ ${Gi.details}
283
283
  ${JSON.stringify(e.data,null,2)}
284
- `}:{exitCode:e.exitCode,stdout:e.text}}async function Ws(e,t){let i=await Cs({paths:e,state:t});return id(t,i)}async function CF(e){let t;try{t=await uP.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}return t.filter(i=>i.isDirectory()&&!i.isSymbolicLink()).map(i=>i.name).sort((i,r)=>i.localeCompare(r,"en"))}function xF(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}async function cP(e,t){let i;try{i=await uP.readdir(e.archiveDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return null;throw a}let r=new RegExp(`^\\d{4}-\\d{2}-\\d{2}-${xF(t)}$`,"u"),n=i.find(a=>a.isDirectory()&&!a.isSymbolicLink()&&r.test(a.name));return n?{severity:"error",code:"portable-active-archive-conflict",message:`Native change ${t} exists in both active and Archive storage`,path:od.join(e.archiveDir,n.name)}:null}function AF(e){let t=new Map;for(let i of e){let r=[i.severity,i.code,i.message,i.path??""].join("\0");t.set(r,i)}return[...t.values()]}function ad(e){return{command:"doctor",exitCode:65,data:e,error:{code:"invalid-data",message:"Native project needs attention"}}}function lP(e,t){return{severity:"error",code:"portable-migration-incomplete",message:`Native portable migration is incomplete for ${t}`,path:od.join(e.changesDir,t,"comet-state.yaml"),repair:"migrate"}}async function _F(e,t){let i=[],r=[];for(let n of await Wy(e)){let a=sn(n);if(t&&a.change!==t)continue;let o=od.join(e.transactionsDir,n);try{let s=await Mo(e,n);if(!s)continue;i.push(s),r.push(s.kind==="archive"?{severity:"error",code:"portable-archive-transaction-incomplete",message:`Native portable Archive transaction ${s.journal.id} is incomplete for ${s.change}`,path:s.file,repair:"continue"}:{severity:"error",code:"portable-migration-incomplete",message:s.journal.status==="committed"?`Native portable migration cleanup is incomplete for ${s.change}`:`Native portable migration transaction ${s.journal.id} is incomplete for ${s.change}`,path:s.file,repair:"migrate"})}catch(s){r.push({severity:"error",code:"portable-transaction-invalid",message:`Native portable transaction ${n} is invalid: ${s.message}`,path:o})}}return{transactions:i,findings:r}}async function Bm(e,t){let i=qs(e,"--repair"),r=nd(e,"--strategy");if(r!==void 0&&r!=="continue"&&r!=="rollback")throw new Bt("--strategy must be continue or rollback");let n=e[0]?.startsWith("--")?void 0:e.shift();iP(e);let a=await nP(t),o=await _F(a,n);if(n&&o.findings.length>0){if(r)throw new Bt("--strategy is only available to the legacy transaction doctor");let d=await qr(a,n)?await qa({paths:a,name:n,details:!0}):void 0;if(i&&o.transactions.length===1&&o.findings.length===1){if(o.transactions[0].kind==="archive"){let v=await _m({paths:a,name:n});return zi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,archive:{recovered:!0,transactionId:v.transactionId},state:v.state,continuation:await Ws(a,v.state)})}let h=await Bs({paths:a,name:n});return zi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{recovered:!0,to:h.schema,stateVersion:h.state_version},state:h,continuation:await Ws(a,h)})}return ad({healthy:!1,workflow:"native-portable",change:n,repaired:!1,...d?{result:d,continuation:d.continuation}:{},findings:o.findings})}if(n&&await qr(a,n)){if(r)throw new Bt("--strategy is only available to the legacy transaction doctor");let[u,d]=await Promise.all([cP(a,n),$m(a,n)]);if(u){let h=await qa({paths:a,name:n,details:!0});return ad({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:h,findings:[u],continuation:h.continuation})}if(d&&!i){let h=await qa({paths:a,name:n,details:!0});return ad({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:h,findings:[lP(a,n)],continuation:h.continuation})}if(i){if(d){let v=await Bs({paths:a,name:n});return zi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{recovered:!0,to:v.schema,stateVersion:v.state_version},state:v,continuation:await Ws(a,v)})}let h=await FE({paths:a,name:n});return zi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,result:h,continuation:await Ws(a,h.state)})}let f=await qa({paths:a,name:n,details:!0});return zi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!1,result:f,continuation:f.continuation})}if(n){if(i){let u=await Bs({paths:a,name:n});return zi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{from:"legacy",to:u.schema,stateVersion:u.state_version},state:u,continuation:await Ws(a,u)})}return{command:"doctor",exitCode:65,data:{healthy:!1,change:n,migrationRequired:!0,repairCommand:`comet native doctor ${n} --repair`},error:{code:"invalid-data",message:`Native active change ${n} requires migration to portable Runtime`}}}let s=await WE(a),c=o;if(s.length>0||c.findings.length>0){if(r)throw new Bt("--strategy is only available to the legacy transaction doctor");if(i){let k=await Ms({paths:a,repair:!0,projectOnly:!0}),S=[];for(let w of c.transactions)w.kind==="archive"?await _m({paths:a,name:w.change}):await Bs({paths:a,name:w.change}),S.push({kind:w.kind,change:w.change,transactionId:w.journal.id});let R=await Bm([],t),N=R.data&&typeof R.data=="object"&&!Array.isArray(R.data)?R.data:{};return{...R,data:{...N,repaired:!0,repairedPortableTransactions:S,repairFindings:k.findings}}}let u=await CF(a),d=new Set(s),f=new Set(c.transactions.filter(k=>k.kind==="migration").map(({change:k})=>k)),h=u.filter(k=>!d.has(k)),[v,m,p,b,g]=await Promise.all([Promise.all(s.map(k=>qa({paths:a,name:k}))),Promise.all(s.map(k=>cP(a,k))),Promise.all(s.map(k=>$m(a,k))),Promise.all(h.map(k=>Ms({paths:a,name:k}))),Ms({paths:a,projectOnly:!0})]),y=AF([...m.filter(k=>k!==null),...s.flatMap((k,S)=>p[S]&&!f.has(k)?[lP(a,k)]:[]),...c.findings,...h.map(k=>({severity:"error",code:"portable-migration-required",message:`Native active change ${k} requires migration to portable Runtime`,path:od.join(a.changesDir,k,"comet-state.yaml"),repair:"migrate"})),...b.flatMap(({findings:k})=>k),...g.findings]),E={healthy:y.every(k=>k.severity==="info"),workflow:h.length>0?"native-mixed":"native-portable",changes:v,legacyChanges:h,findings:y};return E.healthy?zi("doctor",E):ad(E)}let l=await Ms({paths:a,...n?{name:n}:{},repair:i,...r?{recoveryStrategy:r}:{}});return l.healthy?zi("doctor",l):{command:"doctor",exitCode:65,data:l,error:{code:"invalid-data",message:"Native project needs attention"}}}async function dP(e,t,i=process.argv.slice(2)){let r=i.indexOf("--"),n=r<0?[...i]:i.slice(0,r),a=r<0?[]:i.slice(r),o=n.includes("--json"),s=n.includes("--verbose"),c,l;try{qs(n,"--json"),qs(n,"--verbose"),c=nd(n,"--project-root");let d=[...n,...a],f=await rP(c);l=await t(d,f)}catch(d){l=oP(e,d)}let u=sP(l,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
284
+ `}:{exitCode:e.exitCode,stdout:e.text}}async function Gs(e,t){let i=await Ts({paths:e,state:t});return sd(t,i)}async function jF(e){let t;try{t=await mP.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}return t.filter(i=>i.isDirectory()&&!i.isSymbolicLink()).map(i=>i.name).sort((i,r)=>i.localeCompare(r,"en"))}function $F(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}async function hP(e,t){let i;try{i=await mP.readdir(e.archiveDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return null;throw a}let r=new RegExp(`^\\d{4}-\\d{2}-\\d{2}-${$F(t)}$`,"u"),n=i.find(a=>a.isDirectory()&&!a.isSymbolicLink()&&r.test(a.name));return n?{severity:"error",code:"portable-active-archive-conflict",message:`Native change ${t} exists in both active and Archive storage`,path:dd.join(e.archiveDir,n.name)}:null}function OF(e){let t=new Map;for(let i of e){let r=[i.severity,i.code,i.message,i.path??""].join("\0");t.set(r,i)}return[...t.values()]}function ud(e){return{command:"doctor",exitCode:65,data:e,error:{code:"invalid-data",message:"Native project needs attention"}}}function pP(e,t){return{severity:"error",code:"portable-migration-incomplete",message:`Native portable migration is incomplete for ${t}`,path:dd.join(e.changesDir,t,"comet-state.yaml"),repair:"migrate"}}async function HF(e,t){let i=[],r=[];for(let n of await zy(e)){let a=un(n);if(t&&a.change!==t)continue;let o=dd.join(e.transactionsDir,n);try{let s=await qo(e,n);if(!s)continue;i.push(s),r.push(s.kind==="archive"?{severity:"error",code:"portable-archive-transaction-incomplete",message:`Native portable Archive transaction ${s.journal.id} is incomplete for ${s.change}`,path:s.file,repair:"continue"}:{severity:"error",code:"portable-migration-incomplete",message:s.journal.status==="committed"?`Native portable migration cleanup is incomplete for ${s.change}`:`Native portable migration transaction ${s.journal.id} is incomplete for ${s.change}`,path:s.file,repair:"migrate"})}catch(s){r.push({severity:"error",code:"portable-transaction-invalid",message:`Native portable transaction ${n} is invalid: ${s.message}`,path:o})}}return{transactions:i,findings:r}}async function Vm(e,t){let i=Js(e,"--repair"),r=ld(e,"--strategy");if(r!==void 0&&r!=="continue"&&r!=="rollback")throw new Bt("--strategy must be continue or rollback");let n=e[0]?.startsWith("--")?void 0:e.shift();sP(e);let a=await lP(t),o=await HF(a,n);if(n&&o.findings.length>0){if(r)throw new Bt("--strategy is only available to the legacy transaction doctor");let d=await zr(a,n)?await Ua({paths:a,name:n,details:!0}):void 0;if(i&&o.transactions.length===1&&o.findings.length===1){if(o.transactions[0].kind==="archive"){let v=await Im({paths:a,name:n});return Ui("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,archive:{recovered:!0,transactionId:v.transactionId},state:v.state,continuation:await Gs(a,v.state)})}let h=await Ws({paths:a,name:n});return Ui("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{recovered:!0,to:h.schema,stateVersion:h.state_version},state:h,continuation:await Gs(a,h)})}return ud({healthy:!1,workflow:"native-portable",change:n,repaired:!1,...d?{result:d,continuation:d.continuation}:{},findings:o.findings})}if(n&&await zr(a,n)){if(r)throw new Bt("--strategy is only available to the legacy transaction doctor");let[u,d]=await Promise.all([hP(a,n),Om(a,n)]);if(u){let h=await Ua({paths:a,name:n,details:!0});return ud({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:h,findings:[u],continuation:h.continuation})}if(d&&!i){let h=await Ua({paths:a,name:n,details:!0});return ud({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:h,findings:[pP(a,n)],continuation:h.continuation})}if(i){if(d){let v=await Ws({paths:a,name:n});return Ui("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{recovered:!0,to:v.schema,stateVersion:v.state_version},state:v,continuation:await Gs(a,v)})}let h=await zE({paths:a,name:n});return Ui("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,result:h,continuation:await Gs(a,h.state)})}let f=await Ua({paths:a,name:n,details:!0});return Ui("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!1,result:f,continuation:f.continuation})}if(n){if(i){let u=await Ws({paths:a,name:n});return Ui("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{from:"legacy",to:u.schema,stateVersion:u.state_version},state:u,continuation:await Gs(a,u)})}return{command:"doctor",exitCode:65,data:{healthy:!1,change:n,migrationRequired:!0,repairCommand:`comet native doctor ${n} --repair`},error:{code:"invalid-data",message:`Native active change ${n} requires migration to portable Runtime`}}}let s=await KE(a),c=o;if(s.length>0||c.findings.length>0){if(r)throw new Bt("--strategy is only available to the legacy transaction doctor");if(i){let k=await Vs({paths:a,repair:!0,projectOnly:!0}),S=[];for(let w of c.transactions)w.kind==="archive"?await Im({paths:a,name:w.change}):await Ws({paths:a,name:w.change}),S.push({kind:w.kind,change:w.change,transactionId:w.journal.id});let R=await Vm([],t),N=R.data&&typeof R.data=="object"&&!Array.isArray(R.data)?R.data:{};return{...R,data:{...N,repaired:!0,repairedPortableTransactions:S,repairFindings:k.findings}}}let u=await jF(a),d=new Set(s),f=new Set(c.transactions.filter(k=>k.kind==="migration").map(({change:k})=>k)),h=u.filter(k=>!d.has(k)),[v,m,p,b,g]=await Promise.all([Promise.all(s.map(k=>Ua({paths:a,name:k}))),Promise.all(s.map(k=>hP(a,k))),Promise.all(s.map(k=>Om(a,k))),Promise.all(h.map(k=>Vs({paths:a,name:k}))),Vs({paths:a,projectOnly:!0})]),y=OF([...m.filter(k=>k!==null),...s.flatMap((k,S)=>p[S]&&!f.has(k)?[pP(a,k)]:[]),...c.findings,...h.map(k=>({severity:"error",code:"portable-migration-required",message:`Native active change ${k} requires migration to portable Runtime`,path:dd.join(a.changesDir,k,"comet-state.yaml"),repair:"migrate"})),...b.flatMap(({findings:k})=>k),...g.findings]),E={healthy:y.every(k=>k.severity==="info"),workflow:h.length>0?"native-mixed":"native-portable",changes:v,legacyChanges:h,findings:y};return E.healthy?Ui("doctor",E):ud(E)}let l=await Vs({paths:a,...n?{name:n}:{},repair:i,...r?{recoveryStrategy:r}:{}});return l.healthy?Ui("doctor",l):{command:"doctor",exitCode:65,data:l,error:{code:"invalid-data",message:"Native project needs attention"}}}async function vP(e,t,i=process.argv.slice(2)){let r=i.indexOf("--"),n=r<0?[...i]:i.slice(0,r),a=r<0?[]:i.slice(r),o=n.includes("--json"),s=n.includes("--verbose"),c,l;try{Js(n,"--json"),Js(n,"--verbose"),c=ld(n,"--project-root");let d=[...n,...a],f=await cP(c);l=await t(d,f)}catch(d){l=dP(e,d)}let u=fP(l,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
285
285
  `)?"":`
286
- `)),u.exitCode}process.exitCode=await dP("doctor",Bm);
286
+ `)),u.exitCode}process.exitCode=await vP("doctor",Vm);