@rpamis/comet 0.4.4 → 0.4.5

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 (245) hide show
  1. package/README.md +41 -1
  2. package/assets/manifest.json +1 -1
  3. package/assets/skills/comet/scripts/comet-archive.mjs +97 -94
  4. package/assets/skills/comet/scripts/comet-guard.mjs +131 -131
  5. package/assets/skills/comet/scripts/comet-hook-guard.mjs +91 -91
  6. package/assets/skills/comet/scripts/comet-hook-router.mjs +202 -193
  7. package/assets/skills/comet/scripts/comet-resume-probe.mjs +82 -82
  8. package/assets/skills/comet/scripts/comet-runtime.mjs +287 -285
  9. package/assets/skills/comet/scripts/comet-state.mjs +199 -198
  10. package/assets/skills/comet-archive/SKILL.md +9 -5
  11. package/assets/skills/comet-native/reference/artifacts.md +44 -0
  12. package/assets/skills/comet-native/reference/clarification.md +1 -1
  13. package/assets/skills/comet-native/scripts/comet-native-archive.mjs +199 -192
  14. package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +173 -166
  15. package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +150 -143
  16. package/assets/skills/comet-native/scripts/comet-native-init.mjs +103 -99
  17. package/assets/skills/comet-native/scripts/comet-native-new.mjs +209 -205
  18. package/assets/skills/comet-native/scripts/comet-native-next.mjs +180 -173
  19. package/assets/skills/comet-native/scripts/comet-native-root.mjs +106 -102
  20. package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +182 -175
  21. package/assets/skills/comet-native/scripts/comet-native-select.mjs +124 -117
  22. package/assets/skills/comet-native/scripts/comet-native-show.mjs +99 -95
  23. package/assets/skills/comet-native/scripts/comet-native-spec.mjs +143 -136
  24. package/assets/skills/comet-native/scripts/comet-native-status.mjs +120 -113
  25. package/assets/skills-zh/comet-archive/SKILL.md +9 -5
  26. package/assets/skills-zh/comet-native/reference/artifacts.md +44 -0
  27. package/assets/skills-zh/comet-native/reference/clarification.md +1 -1
  28. package/dist/app/cli/index.js +1 -0
  29. package/dist/app/cli/index.js.map +1 -1
  30. package/dist/app/commands/doctor.d.ts.map +1 -1
  31. package/dist/app/commands/doctor.js +17 -10
  32. package/dist/app/commands/doctor.js.map +1 -1
  33. package/dist/app/commands/i18n.d.ts +1 -1
  34. package/dist/app/commands/i18n.d.ts.map +1 -1
  35. package/dist/app/commands/i18n.js +4 -0
  36. package/dist/app/commands/i18n.js.map +1 -1
  37. package/dist/app/commands/project-knowledge.d.ts +2 -0
  38. package/dist/app/commands/project-knowledge.d.ts.map +1 -1
  39. package/dist/app/commands/project-knowledge.js +64 -7
  40. package/dist/app/commands/project-knowledge.js.map +1 -1
  41. package/dist/app/commands/uninstall.d.ts +1 -0
  42. package/dist/app/commands/uninstall.d.ts.map +1 -1
  43. package/dist/app/commands/uninstall.js +65 -10
  44. package/dist/app/commands/uninstall.js.map +1 -1
  45. package/dist/domains/agent-learning/coordinator.d.ts +8 -1
  46. package/dist/domains/agent-learning/coordinator.d.ts.map +1 -1
  47. package/dist/domains/agent-learning/coordinator.js +58 -0
  48. package/dist/domains/agent-learning/coordinator.js.map +1 -1
  49. package/dist/domains/agent-learning/experience-journal.d.ts +21 -1
  50. package/dist/domains/agent-learning/experience-journal.d.ts.map +1 -1
  51. package/dist/domains/agent-learning/experience-journal.js +190 -11
  52. package/dist/domains/agent-learning/experience-journal.js.map +1 -1
  53. package/dist/domains/bundle/bundle-platform.d.ts.map +1 -1
  54. package/dist/domains/bundle/bundle-platform.js +6 -1
  55. package/dist/domains/bundle/bundle-platform.js.map +1 -1
  56. package/dist/domains/comet-classic/classic-archive.d.ts.map +1 -1
  57. package/dist/domains/comet-classic/classic-archive.js +5 -1
  58. package/dist/domains/comet-classic/classic-archive.js.map +1 -1
  59. package/dist/domains/comet-classic/classic-design-readiness.d.ts +1 -1
  60. package/dist/domains/comet-classic/classic-progress.d.ts +60 -2
  61. package/dist/domains/comet-classic/classic-progress.d.ts.map +1 -1
  62. package/dist/domains/comet-classic/classic-progress.js +199 -22
  63. package/dist/domains/comet-classic/classic-progress.js.map +1 -1
  64. package/dist/domains/comet-classic/classic-recovery.d.ts +20 -1
  65. package/dist/domains/comet-classic/classic-recovery.d.ts.map +1 -1
  66. package/dist/domains/comet-native/native-artifact-language.d.ts +7 -0
  67. package/dist/domains/comet-native/native-artifact-language.d.ts.map +1 -1
  68. package/dist/domains/comet-native/native-artifact-language.js +61 -1
  69. package/dist/domains/comet-native/native-artifact-language.js.map +1 -1
  70. package/dist/domains/comet-native/native-artifacts.d.ts +2 -0
  71. package/dist/domains/comet-native/native-artifacts.d.ts.map +1 -1
  72. package/dist/domains/comet-native/native-artifacts.js +116 -19
  73. package/dist/domains/comet-native/native-artifacts.js.map +1 -1
  74. package/dist/domains/comet-native/native-hook-guard.d.ts.map +1 -1
  75. package/dist/domains/comet-native/native-hook-guard.js +3 -2
  76. package/dist/domains/comet-native/native-hook-guard.js.map +1 -1
  77. package/dist/domains/comet-native/native-portable-requirements.d.ts.map +1 -1
  78. package/dist/domains/comet-native/native-portable-requirements.js +12 -5
  79. package/dist/domains/comet-native/native-portable-requirements.js.map +1 -1
  80. package/dist/domains/comet-native/native-portable-state.d.ts.map +1 -1
  81. package/dist/domains/comet-native/native-portable-state.js +4 -2
  82. package/dist/domains/comet-native/native-portable-state.js.map +1 -1
  83. package/dist/domains/comet-native/native-portable-types.d.ts +1 -1
  84. package/dist/domains/comet-native/native-portable-types.d.ts.map +1 -1
  85. package/dist/domains/comet-plugin/integration.d.ts +1 -0
  86. package/dist/domains/comet-plugin/integration.d.ts.map +1 -1
  87. package/dist/domains/comet-plugin/integration.js +20 -10
  88. package/dist/domains/comet-plugin/integration.js.map +1 -1
  89. package/dist/domains/comet-plugin/plugin-runtime.d.ts +8 -2
  90. package/dist/domains/comet-plugin/plugin-runtime.d.ts.map +1 -1
  91. package/dist/domains/comet-plugin/plugin-runtime.js +18 -4
  92. package/dist/domains/comet-plugin/plugin-runtime.js.map +1 -1
  93. package/dist/domains/dashboard/project-directory.d.ts +4 -0
  94. package/dist/domains/dashboard/project-directory.d.ts.map +1 -1
  95. package/dist/domains/dashboard/project-directory.js +30 -2
  96. package/dist/domains/dashboard/project-directory.js.map +1 -1
  97. package/dist/domains/dashboard/server.d.ts.map +1 -1
  98. package/dist/domains/dashboard/server.js +28 -3
  99. package/dist/domains/dashboard/server.js.map +1 -1
  100. package/dist/domains/dashboard/web/assets/{abnfDiagram-VCTEODGH-CFEU4PQU.js → abnfDiagram-VCTEODGH-m9_t3fwH.js} +1 -1
  101. package/dist/domains/dashboard/web/assets/{arc-BeYYJor9.js → arc-CDiwRrMg.js} +1 -1
  102. package/dist/domains/dashboard/web/assets/architecture-7GRP2DOG-ypJOsR2Y.js +1 -0
  103. package/dist/domains/dashboard/web/assets/{architectureDiagram-5GKGNRK7-CqTy4fyH.js → architectureDiagram-5GKGNRK7-Xwj-hlQB.js} +1 -1
  104. package/dist/domains/dashboard/web/assets/{blockDiagram-I7D4REHJ-SR_5S4SA.js → blockDiagram-I7D4REHJ-Cme6qNK_.js} +1 -1
  105. package/dist/domains/dashboard/web/assets/{c4Diagram-7LVT6UL2-DzphG2XS.js → c4Diagram-7LVT6UL2-Cxs1dU7y.js} +1 -1
  106. package/dist/domains/dashboard/web/assets/channel-BFTjR7Ng.js +1 -0
  107. package/dist/domains/dashboard/web/assets/{chunk-4HAMMTFA-BpthUtIs.js → chunk-4HAMMTFA-DBQykIWE.js} +1 -1
  108. package/dist/domains/dashboard/web/assets/{chunk-75Z2AOVW-CxAdhPhG.js → chunk-75Z2AOVW-Dh-E6TAx.js} +1 -1
  109. package/dist/domains/dashboard/web/assets/{chunk-DU6HZSFF-5peVNfxp.js → chunk-DU6HZSFF-W3lPaoVP.js} +2 -2
  110. package/dist/domains/dashboard/web/assets/{chunk-F27PBJKO-CwG4xi2V.js → chunk-F27PBJKO-dzf1fpYi.js} +1 -1
  111. package/dist/domains/dashboard/web/assets/{chunk-GMAD6QVW-BuFFY783.js → chunk-GMAD6QVW-CeuSGVHV.js} +1 -1
  112. package/dist/domains/dashboard/web/assets/{chunk-GVQU2GXP-OyUFmjE-.js → chunk-GVQU2GXP-BrGrIBgk.js} +1 -1
  113. package/dist/domains/dashboard/web/assets/{chunk-IMKFNOWR-DmTme45C.js → chunk-IMKFNOWR-DXiTC1Xo.js} +1 -1
  114. package/dist/domains/dashboard/web/assets/{chunk-L3NEJ4N5-D6BHbKty.js → chunk-L3NEJ4N5-DnyD3Ocj.js} +1 -1
  115. package/dist/domains/dashboard/web/assets/{chunk-OSK3NFVY-CCz1v1Nv.js → chunk-OSK3NFVY-6vxhPm51.js} +1 -1
  116. package/dist/domains/dashboard/web/assets/{chunk-P2QGCYS3-C1_7kDYS.js → chunk-P2QGCYS3-DChNsVqO.js} +1 -1
  117. package/dist/domains/dashboard/web/assets/{chunk-POPQ4Y6H-buFKlAdG.js → chunk-POPQ4Y6H-RBgha6dE.js} +1 -1
  118. package/dist/domains/dashboard/web/assets/{chunk-PWAF6VOD-B_K6Jrsv.js → chunk-PWAF6VOD-CayoKmnh.js} +1 -1
  119. package/dist/domains/dashboard/web/assets/{chunk-SHT3W25Y-CRRLsXmS.js → chunk-SHT3W25Y-sOkLJZoB.js} +1 -1
  120. package/dist/domains/dashboard/web/assets/{chunk-SVP7TREG-Q5zCQTul.js → chunk-SVP7TREG-j0QRwmsq.js} +1 -1
  121. package/dist/domains/dashboard/web/assets/{chunk-TICWLB2K-Zc5XaO5Z.js → chunk-TICWLB2K-D7Re_d_T.js} +1 -1
  122. package/dist/domains/dashboard/web/assets/{chunk-XXDRQBXY-BAIB2h_r.js → chunk-XXDRQBXY-BFV70fKF.js} +1 -1
  123. package/dist/domains/dashboard/web/assets/classDiagram-ZZMXUADV-gDSLbV2K.js +1 -0
  124. package/dist/domains/dashboard/web/assets/classDiagram-v2-VYDZK3BY-gDSLbV2K.js +1 -0
  125. package/dist/domains/dashboard/web/assets/{cose-bilkent-JH36ORCC-C7jkFYhm.js → cose-bilkent-JH36ORCC-k7gqx2Br.js} +1 -1
  126. package/dist/domains/dashboard/web/assets/{cynefin-OW5HDTMX-4yS-l7kx.js → cynefin-OW5HDTMX-CWI6FZT8.js} +1 -1
  127. package/dist/domains/dashboard/web/assets/{cynefinDiagram-5FMLGOSQ-DAkfQ8jW.js → cynefinDiagram-5FMLGOSQ-D-O3RrOu.js} +1 -1
  128. package/dist/domains/dashboard/web/assets/{dagre-GXQ25YYZ-D3b16ruz.js → dagre-GXQ25YYZ-BR1jxWfn.js} +1 -1
  129. package/dist/domains/dashboard/web/assets/{diagram-S7CK7UJ4-BXZHtdNz.js → diagram-S7CK7UJ4-B6gXFYBj.js} +1 -1
  130. package/dist/domains/dashboard/web/assets/{diagram-UQ7AKVKN-B4nIzofw.js → diagram-UQ7AKVKN-BBW6aRk8.js} +1 -1
  131. package/dist/domains/dashboard/web/assets/{diagram-VSXAHHWV-B6d7KNj1.js → diagram-VSXAHHWV-BC0CZeyH.js} +1 -1
  132. package/dist/domains/dashboard/web/assets/{diagram-VX7I27RA-CHr0Rg8a.js → diagram-VX7I27RA-BmwBIkwS.js} +1 -1
  133. package/dist/domains/dashboard/web/assets/{diagram-Z3DM3KII-BO2IxR9N.js → diagram-Z3DM3KII-DTZgX9SF.js} +1 -1
  134. package/dist/domains/dashboard/web/assets/{dist-0wyW4qbm.js → dist-brXLwleg.js} +1 -1
  135. package/dist/domains/dashboard/web/assets/{ebnfDiagram-PWID7BFC-CHRK8Hyg.js → ebnfDiagram-PWID7BFC-CsMXo0C6.js} +1 -1
  136. package/dist/domains/dashboard/web/assets/{erDiagram-RLTQ6QDP-_HFHzZlc.js → erDiagram-RLTQ6QDP-DQ9ewX94.js} +1 -1
  137. package/dist/domains/dashboard/web/assets/{es-kjndkyYX.js → es-CgcAhzLf.js} +1 -1
  138. package/dist/domains/dashboard/web/assets/eventmodeling-NTZA5JFV-Ll12Q19y.js +1 -0
  139. package/dist/domains/dashboard/web/assets/flowDiagram-HODETNUW-Bf2-9XUn.js +1 -0
  140. package/dist/domains/dashboard/web/assets/{ganttDiagram-EL5Y4UJY-CxhSw1PI.js → ganttDiagram-EL5Y4UJY-DIFkXe6G.js} +1 -1
  141. package/dist/domains/dashboard/web/assets/{gitGraph-4MIJSDKK-Cbw-3Dnk.js → gitGraph-4MIJSDKK-BHY8ZnpE.js} +1 -1
  142. package/dist/domains/dashboard/web/assets/{gitGraphDiagram-WWUBYQGX-Cx93hwtL.js → gitGraphDiagram-WWUBYQGX-cBn9dMzs.js} +1 -1
  143. package/dist/domains/dashboard/web/assets/{index-CQb8j5OE.js → index-C_6nf1Fw.js} +2 -2
  144. package/dist/domains/dashboard/web/assets/{info-A6RAGUB7--d4EMiIK.js → info-A6RAGUB7-DtUaS9jN.js} +1 -1
  145. package/dist/domains/dashboard/web/assets/{infoDiagram-27XIBGKW-DMkRRNGB.js → infoDiagram-27XIBGKW-CIl0e_EN.js} +1 -1
  146. package/dist/domains/dashboard/web/assets/{ishikawaDiagram-5VMMS53U-CjKh_jHT.js → ishikawaDiagram-5VMMS53U-DAdtPZ_c.js} +1 -1
  147. package/dist/domains/dashboard/web/assets/{journeyDiagram-3NMN7TZE-CG735M_M.js → journeyDiagram-3NMN7TZE-CBokRgde.js} +1 -1
  148. package/dist/domains/dashboard/web/assets/{kanban-definition-UXKFOSKX-CgXFmhFM.js → kanban-definition-UXKFOSKX-DrqCYJ-7.js} +1 -1
  149. package/dist/domains/dashboard/web/assets/katex-D29apahB.js +257 -0
  150. package/dist/domains/dashboard/web/assets/{line-Bhf8l3gG.js → line-BDlVqlh4.js} +1 -1
  151. package/dist/domains/dashboard/web/assets/{linear-YWT9mnmu.js → linear-DTAzui9x.js} +1 -1
  152. package/dist/domains/dashboard/web/assets/{mermaid-parser.core-COzQ1kq0.js → mermaid-parser.core-CFw-xbYY.js} +3 -3
  153. package/dist/domains/dashboard/web/assets/{mermaid.core-Cc1lMpx-.js → mermaid.core-Ck7fB8UD.js} +4 -4
  154. package/dist/domains/dashboard/web/assets/{mindmap-definition-YA3MSWOX-B_VOgUSO.js → mindmap-definition-YA3MSWOX-C7kb9KL9.js} +1 -1
  155. package/dist/domains/dashboard/web/assets/{packet-AYTQ26CC-CXbJLNC9.js → packet-AYTQ26CC-P8Mtt0tp.js} +1 -1
  156. package/dist/domains/dashboard/web/assets/{pegDiagram-XKGWAZYB-BuS0hioo.js → pegDiagram-XKGWAZYB-DUDD9qv5.js} +1 -1
  157. package/dist/domains/dashboard/web/assets/{pie-WAS4IAKB-BEaGwdWZ.js → pie-WAS4IAKB-dEmLxiDR.js} +1 -1
  158. package/dist/domains/dashboard/web/assets/{pieDiagram-E7YTZNPT-DDzYv-_9.js → pieDiagram-E7YTZNPT-BUssAcqk.js} +1 -1
  159. package/dist/domains/dashboard/web/assets/{quadrantDiagram-AXDQQJYC-DExT--Ut.js → quadrantDiagram-AXDQQJYC-BzaAWdQL.js} +1 -1
  160. package/dist/domains/dashboard/web/assets/{radar-RG4KPBEZ-C1JtzGr8.js → radar-RG4KPBEZ-mqtvaz9w.js} +1 -1
  161. package/dist/domains/dashboard/web/assets/{railroad-74A4TZTK-CMpkXATR.js → railroad-74A4TZTK-7tTnGpoz.js} +1 -1
  162. package/dist/domains/dashboard/web/assets/railroad-abnf-HS5TGJTU-CpJvyBJM.js +1 -0
  163. package/dist/domains/dashboard/web/assets/railroad-ebnf-LZEXJU2U-BJ5g77l6.js +1 -0
  164. package/dist/domains/dashboard/web/assets/railroad-peg-WCYAUIDC-BslCK-Gr.js +1 -0
  165. package/dist/domains/dashboard/web/assets/{railroadDiagram-O6MQD6OU-BCE65sLR.js → railroadDiagram-O6MQD6OU-DM1AKXm0.js} +1 -1
  166. package/dist/domains/dashboard/web/assets/{requirementDiagram-BXWQKSXE-CmyX3vGG.js → requirementDiagram-BXWQKSXE--H5KiPSc.js} +1 -1
  167. package/dist/domains/dashboard/web/assets/{sankeyDiagram-P5KCCOFB-BFKrX2dv.js → sankeyDiagram-P5KCCOFB-JweUq_u2.js} +1 -1
  168. package/dist/domains/dashboard/web/assets/{sequenceDiagram-WJ2MYXX4-DqodS9W-.js → sequenceDiagram-WJ2MYXX4-pxb1iTGb.js} +1 -1
  169. package/dist/domains/dashboard/web/assets/{src-BVUP3QzK.js → src-joFOxopw.js} +1 -1
  170. package/dist/domains/dashboard/web/assets/{stateDiagram-D77RDMKH-nHai_EZh.js → stateDiagram-D77RDMKH-CDu5crd8.js} +1 -1
  171. package/dist/domains/dashboard/web/assets/stateDiagram-v2-MP3YSRHH-wV5AqWaM.js +1 -0
  172. package/dist/domains/dashboard/web/assets/{swimlanes-42K2YHIH-BODBARYN.js → swimlanes-42K2YHIH-ioSqowJ4.js} +1 -1
  173. package/dist/domains/dashboard/web/assets/swimlanesDiagram-VR7AAH4N-DOPLn-V5.js +8 -0
  174. package/dist/domains/dashboard/web/assets/{timeline-definition-24CTP7MA-RVnG8rgK.js → timeline-definition-24CTP7MA-2YXSYkS3.js} +1 -1
  175. package/dist/domains/dashboard/web/assets/{treeView-Q6P3EWNA-B6lrg3KQ.js → treeView-Q6P3EWNA-DEGims38.js} +1 -1
  176. package/dist/domains/dashboard/web/assets/{treemap-WGGIJYW6-CJfMKVf4.js → treemap-WGGIJYW6-CJvBhTlR.js} +1 -1
  177. package/dist/domains/dashboard/web/assets/{vennDiagram-4TSXK5OY-CZMWJiN7.js → vennDiagram-4TSXK5OY-CHdNWhBK.js} +1 -1
  178. package/dist/domains/dashboard/web/assets/{wardley-WFR3VGLG-BoUsbNlx.js → wardley-WFR3VGLG-CVO9PCjo.js} +1 -1
  179. package/dist/domains/dashboard/web/assets/{wardleyDiagram-VM6X3IG4-BwBCykVb.js → wardleyDiagram-VM6X3IG4-RToPmij6.js} +1 -1
  180. package/dist/domains/dashboard/web/assets/{xychartDiagram-S5SC5T6Z-vutnbx57.js → xychartDiagram-S5SC5T6Z-DaWHnpHE.js} +1 -1
  181. package/dist/domains/dashboard/web/index.html +1 -1
  182. package/dist/domains/project-knowledge/host-review.d.ts +15 -2
  183. package/dist/domains/project-knowledge/host-review.d.ts.map +1 -1
  184. package/dist/domains/project-knowledge/host-review.js +65 -25
  185. package/dist/domains/project-knowledge/host-review.js.map +1 -1
  186. package/dist/domains/project-knowledge/index.d.ts +1 -0
  187. package/dist/domains/project-knowledge/index.d.ts.map +1 -1
  188. package/dist/domains/project-knowledge/index.js +1 -0
  189. package/dist/domains/project-knowledge/index.js.map +1 -1
  190. package/dist/domains/project-knowledge/learning.d.ts +2 -1
  191. package/dist/domains/project-knowledge/learning.d.ts.map +1 -1
  192. package/dist/domains/project-knowledge/learning.js +6 -0
  193. package/dist/domains/project-knowledge/learning.js.map +1 -1
  194. package/dist/domains/project-knowledge/plugin.d.ts.map +1 -1
  195. package/dist/domains/project-knowledge/plugin.js +3 -1
  196. package/dist/domains/project-knowledge/plugin.js.map +1 -1
  197. package/dist/domains/skill/dsh-adapter.d.ts +5 -1
  198. package/dist/domains/skill/dsh-adapter.d.ts.map +1 -1
  199. package/dist/domains/skill/dsh-adapter.js +222 -87
  200. package/dist/domains/skill/dsh-adapter.js.map +1 -1
  201. package/dist/domains/skill/platform-inspect.d.ts +1 -0
  202. package/dist/domains/skill/platform-inspect.d.ts.map +1 -1
  203. package/dist/domains/skill/platform-inspect.js +8 -4
  204. package/dist/domains/skill/platform-inspect.js.map +1 -1
  205. package/dist/domains/skill/platform-install.d.ts.map +1 -1
  206. package/dist/domains/skill/platform-install.js +7 -7
  207. package/dist/domains/skill/platform-install.js.map +1 -1
  208. package/dist/platform/fs/file-system.d.ts +2 -0
  209. package/dist/platform/fs/file-system.d.ts.map +1 -1
  210. package/dist/platform/fs/file-system.js +11 -0
  211. package/dist/platform/fs/file-system.js.map +1 -1
  212. package/dist/platform/install/dsh-profiles.d.ts +3 -0
  213. package/dist/platform/install/dsh-profiles.d.ts.map +1 -0
  214. package/dist/platform/install/dsh-profiles.js +40 -0
  215. package/dist/platform/install/dsh-profiles.js.map +1 -0
  216. package/dist/platform/install/platforms.d.ts.map +1 -1
  217. package/dist/platform/install/platforms.js +1 -0
  218. package/dist/platform/install/platforms.js.map +1 -1
  219. package/dist/platform/install/project-registry.d.ts +7 -1
  220. package/dist/platform/install/project-registry.d.ts.map +1 -1
  221. package/dist/platform/install/project-registry.js +49 -5
  222. package/dist/platform/install/project-registry.js.map +1 -1
  223. package/dist/platform/paths/project-worktree-root.d.ts +3 -0
  224. package/dist/platform/paths/project-worktree-root.d.ts.map +1 -0
  225. package/dist/platform/paths/project-worktree-root.js +14 -0
  226. package/dist/platform/paths/project-worktree-root.js.map +1 -0
  227. package/dist/platform/process/hook-adapter.d.ts.map +1 -1
  228. package/dist/platform/process/hook-adapter.js +13 -0
  229. package/dist/platform/process/hook-adapter.js.map +1 -1
  230. package/eval/local/tasks/comet-classic-layout-lifecycle/environment/current-comet-package.json +11 -3
  231. package/eval/local/tasks/comet-native-wave-f-dashboard-readonly/environment/current-comet-package.json +11 -3
  232. package/eval/local/tests/scaffold/test_task_resolution.py +6 -2
  233. package/package.json +14 -8
  234. package/dist/domains/dashboard/web/assets/architecture-7GRP2DOG-YphM8Wtg.js +0 -1
  235. package/dist/domains/dashboard/web/assets/channel-BkwcGbYR.js +0 -1
  236. package/dist/domains/dashboard/web/assets/classDiagram-ZZMXUADV-DzpQhyL3.js +0 -1
  237. package/dist/domains/dashboard/web/assets/classDiagram-v2-VYDZK3BY-DzpQhyL3.js +0 -1
  238. package/dist/domains/dashboard/web/assets/eventmodeling-NTZA5JFV-CG-cVTEg.js +0 -1
  239. package/dist/domains/dashboard/web/assets/flowDiagram-HODETNUW-C3RaJz-z.js +0 -1
  240. package/dist/domains/dashboard/web/assets/katex-CXMH3UgJ.js +0 -257
  241. package/dist/domains/dashboard/web/assets/railroad-abnf-HS5TGJTU-BM35gYWg.js +0 -1
  242. package/dist/domains/dashboard/web/assets/railroad-ebnf-LZEXJU2U-CN60GGp0.js +0 -1
  243. package/dist/domains/dashboard/web/assets/railroad-peg-WCYAUIDC-DRUSW4g7.js +0 -1
  244. package/dist/domains/dashboard/web/assets/stateDiagram-v2-MP3YSRHH-BL6vE1m9.js +0 -1
  245. package/dist/domains/dashboard/web/assets/swimlanesDiagram-VR7AAH4N-XHK_nuTj.js +0 -8
@@ -1,78 +1,78 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cometCreateRequire } from 'module';
3
3
  const require = __cometCreateRequire(import.meta.url);
4
- var uS=Object.create;var Dl=Object.defineProperty;var dS=Object.getOwnPropertyDescriptor;var pS=Object.getOwnPropertyNames;var fS=Object.getPrototypeOf,hS=Object.prototype.hasOwnProperty;var zo=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var I=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(i){throw r=[i],i}};var R=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},mS=(e,t)=>{for(var r in t)Dl(e,r,{get:t[r],enumerable:!0})},vS=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of pS(t))!hS.call(e,n)&&n!==r&&Dl(e,n,{get:()=>t[n],enumerable:!(i=dS(t,n))||i.enumerable});return e};var Kt=(e,t,r)=>(r=e!=null?uS(fS(e)):{},vS(t||!e||!e.__esModule?Dl(r,"default",{value:e,enumerable:!0}):r,e));import{AsyncLocalStorage as gS}from"node:async_hooks";import{performance as Ph}from"node:perf_hooks";function Bl(e=0){wS+=1,yS+=e;let t=NS.getStore();t&&(t.gitCommands+=1,t.gitDurationMs+=e)}function zn(e){let t=Ph.now();try{return e()}finally{Bl(Ph.now()-t)}}var wS,yS,NS,Hi=I(()=>{"use strict";wS=0,yS=0,NS=new gS});var $D,Gn=I(()=>{"use strict";$D=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ")});var BD,Di=I(()=>{"use strict";Hi();Gn();BD=8*1024*1024});import{createHash as RS}from"crypto";function dt(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function PS(e,t){t.has(e)&&dt("cyclic structures are not supported"),t.add(e);try{let r=Object.keys(e);for(let i=0;i<e.length;i+=1)Object.prototype.hasOwnProperty.call(e,i)||dt("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&dt("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&dt("symbol properties are not supported"),`[${e.map(i=>Fl(i,t)).join(",")}]`}finally{t.delete(e)}}function _S(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&dt("only plain objects are supported"),t.has(e)&&dt("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&dt("symbol properties are not supported"),t.add(e);try{let i=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=i[o];return(!s||!("value"in s))&&dt("accessor properties are not supported"),`${JSON.stringify(o)}:${Fl(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function Fl(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)||dt("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?PS(e,t):_S(e,t);case"bigint":case"function":case"symbol":case"undefined":return dt(`${typeof e} values are not supported`)}return dt("unsupported value type")}function Yn(e){return Fl(e,new Set)}function T(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 RS("sha256").update(`${e}
5
- ${Yn(t)}`).digest("hex")}var ue=I(()=>{"use strict"});var W=R(ke=>{"use strict";var Ll=Symbol.for("yaml.alias"),Oh=Symbol.for("yaml.document"),Jo=Symbol.for("yaml.map"),Hh=Symbol.for("yaml.pair"),ql=Symbol.for("yaml.scalar"),Uo=Symbol.for("yaml.seq"),Xt=Symbol.for("yaml.node.type"),AS=e=>!!e&&typeof e=="object"&&e[Xt]===Ll,IS=e=>!!e&&typeof e=="object"&&e[Xt]===Oh,TS=e=>!!e&&typeof e=="object"&&e[Xt]===Jo,jS=e=>!!e&&typeof e=="object"&&e[Xt]===Hh,Dh=e=>!!e&&typeof e=="object"&&e[Xt]===ql,$S=e=>!!e&&typeof e=="object"&&e[Xt]===Uo;function Bh(e){if(e&&typeof e=="object")switch(e[Xt]){case Jo:case Uo:return!0}return!1}function OS(e){if(e&&typeof e=="object")switch(e[Xt]){case Ll:case Jo:case ql:case Uo:return!0}return!1}var HS=e=>(Dh(e)||Bh(e))&&!!e.anchor;ke.ALIAS=Ll;ke.DOC=Oh;ke.MAP=Jo;ke.NODE_TYPE=Xt;ke.PAIR=Hh;ke.SCALAR=ql;ke.SEQ=Uo;ke.hasAnchor=HS;ke.isAlias=AS;ke.isCollection=Bh;ke.isDocument=IS;ke.isMap=TS;ke.isNode=OS;ke.isPair=jS;ke.isScalar=Dh;ke.isSeq=$S});var Xn=R(Ml=>{"use strict";var ge=W(),Be=Symbol("break visit"),Fh=Symbol("skip children"),_t=Symbol("remove node");function Ko(e,t){let r=Lh(t);ge.isDocument(e)?Bi(null,e.contents,r,Object.freeze([e]))===_t&&(e.contents=null):Bi(null,e,r,Object.freeze([]))}Ko.BREAK=Be;Ko.SKIP=Fh;Ko.REMOVE=_t;function Bi(e,t,r,i){let n=qh(e,t,r,i);if(ge.isNode(n)||ge.isPair(n))return Mh(e,i,n),Bi(e,n,r,i);if(typeof n!="symbol"){if(ge.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=Bi(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===Be)return Be;o===_t&&(t.items.splice(a,1),a-=1)}}}else if(ge.isPair(t)){i=Object.freeze(i.concat(t));let a=Bi("key",t.key,r,i);if(a===Be)return Be;a===_t&&(t.key=null);let o=Bi("value",t.value,r,i);if(o===Be)return Be;o===_t&&(t.value=null)}}return n}async function Yo(e,t){let r=Lh(t);ge.isDocument(e)?await Fi(null,e.contents,r,Object.freeze([e]))===_t&&(e.contents=null):await Fi(null,e,r,Object.freeze([]))}Yo.BREAK=Be;Yo.SKIP=Fh;Yo.REMOVE=_t;async function Fi(e,t,r,i){let n=await qh(e,t,r,i);if(ge.isNode(n)||ge.isPair(n))return Mh(e,i,n),Fi(e,n,r,i);if(typeof n!="symbol"){if(ge.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await Fi(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===Be)return Be;o===_t&&(t.items.splice(a,1),a-=1)}}}else if(ge.isPair(t)){i=Object.freeze(i.concat(t));let a=await Fi("key",t.key,r,i);if(a===Be)return Be;a===_t&&(t.key=null);let o=await Fi("value",t.value,r,i);if(o===Be)return Be;o===_t&&(t.value=null)}}return n}function Lh(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 qh(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(ge.isMap(t))return r.Map?.(e,t,i);if(ge.isSeq(t))return r.Seq?.(e,t,i);if(ge.isPair(t))return r.Pair?.(e,t,i);if(ge.isScalar(t))return r.Scalar?.(e,t,i);if(ge.isAlias(t))return r.Alias?.(e,t,i)}function Mh(e,t,r){let i=t[t.length-1];if(ge.isCollection(i))i.items[e]=r;else if(ge.isPair(i))e==="key"?i.key=r:i.value=r;else if(ge.isDocument(i))i.contents=r;else{let n=ge.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}Ml.visit=Ko;Ml.visitAsync=Yo});var Vl=R(Wh=>{"use strict";var Vh=W(),DS=Xn(),BS={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},FS=e=>e.replace(/[!,[\]{}]/g,t=>BS[t]),Qn=class e{constructor(t,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,r)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,r){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let i=t.trim().split(/[ \t]+/),n=i.shift();switch(n){case"%TAG":{if(i.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[a,o]=i;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;let[a]=i;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return r(6,`Unsupported YAML version ${a}`,o),!1}}default:return r(0,`Unknown directive ${n}`,!0),!1}}tagName(t,r){if(t==="!")return"!";if(t[0]!=="!")return r(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}let[,i,n]=t.match(/^(.*!)([^!]*)$/s);n||r(`The ${t} tag has no suffix`);let a=this.tags[i];if(a)try{return a+decodeURIComponent(n)}catch(o){return r(String(o)),null}return i==="!"?t:(r(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[r,i]of Object.entries(this.tags))if(t.startsWith(i))return r+FS(t.substring(i.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),n;if(t&&i.length>0&&Vh.isNode(t.contents)){let a={};DS.visit(t.contents,(o,s)=>{Vh.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of i)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&r.push(`%TAG ${a} ${o}`);return r.join(`
6
- `)}};Qn.defaultYaml={explicit:!1,version:"1.2"};Qn.defaultTags={"!!":"tag:yaml.org,2002:"};Wh.Directives=Qn});var Xo=R(Zn=>{"use strict";var zh=W(),LS=Xn();function qS(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(r)}return!0}function Gh(e){let t=new Set;return LS.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function Jh(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function MS(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=Gh(e));let o=Jh(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(zh.isScalar(o.node)||zh.isCollection(o.node)))o.node.anchor=o.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=a,s}}},sourceObjects:i}}Zn.anchorIsValid=qS;Zn.anchorNames=Gh;Zn.createNodeAnchors=MS;Zn.findNewAnchor=Jh});var Wl=R(Uh=>{"use strict";function ea(e,t,r,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let n=0,a=i.length;n<a;++n){let o=i[n],s=ea(e,i,String(n),o);s===void 0?delete i[n]:s!==o&&(i[n]=s)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let a=i.get(n),o=ea(e,i,n,a);o===void 0?i.delete(n):o!==a&&i.set(n,o)}else if(i instanceof Set)for(let n of Array.from(i)){let a=ea(e,i,n,n);a===void 0?i.delete(n):a!==n&&(i.delete(n),i.add(a))}else for(let[n,a]of Object.entries(i)){let o=ea(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}Uh.applyReviver=ea});var Nr=R(Yh=>{"use strict";var VS=W();function Kh(e,t,r){if(Array.isArray(e))return e.map((i,n)=>Kh(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!VS.hasAnchor(e))return e.toJSON(t,r);let i={aliasCount:0,count:1,res:void 0};r.anchors.set(e,i),r.onCreate=a=>{i.res=a,delete r.onCreate};let n=e.toJSON(t,r);return r.onCreate&&r.onCreate(n),n}return typeof e=="bigint"&&!r?.keep?Number(e):e}Yh.toJS=Kh});var Qo=R(Qh=>{"use strict";var WS=Wl(),Xh=W(),zS=Nr(),zl=class{constructor(t){Object.defineProperty(this,Xh.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:r,maxAliasCount:i,onAnchor:n,reviver:a}={}){if(!Xh.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},s=zS.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?WS.applyReviver(a,{"":s},"",s):s}};Qh.NodeBase=zl});var ta=R(Zh=>{"use strict";var GS=Xo(),JS=Xn(),Li=W(),US=Qo(),KS=Nr(),Gl=class extends US.NodeBase{constructor(t){super(Li.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,r){if(r?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;r?.aliasResolveCache?i=r.aliasResolveCache:(i=[],JS.visit(t,{Node:(a,o)=>{(Li.isAlias(o)||Li.hasAnchor(o))&&i.push(o)}}),r&&(r.aliasResolveCache=i));let n;for(let a of i){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,r){if(!r)return{source:this.source};let{anchors:i,doc:n,maxAliasCount:a}=r,o=this.resolve(n,r);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=i.get(o);if(s||(KS.toJS(o,null,r),s=i.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=Zo(n,o,i)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,r,i){let n=`*${this.source}`;if(t){if(GS.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 Zo(e,t,r){if(Li.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(Li.isCollection(t)){let i=0;for(let n of t.items){let a=Zo(e,n,r);a>i&&(i=a)}return i}else if(Li.isPair(t)){let i=Zo(e,t.key,r),n=Zo(e,t.value,r);return Math.max(i,n)}return 1}Zh.Alias=Gl});var de=R(Jl=>{"use strict";var YS=W(),XS=Qo(),QS=Nr(),ZS=e=>!e||typeof e!="function"&&typeof e!="object",br=class extends XS.NodeBase{constructor(t){super(YS.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:QS.toJS(this.value,t,r)}toString(){return String(this.value)}};br.BLOCK_FOLDED="BLOCK_FOLDED";br.BLOCK_LITERAL="BLOCK_LITERAL";br.PLAIN="PLAIN";br.QUOTE_DOUBLE="QUOTE_DOUBLE";br.QUOTE_SINGLE="QUOTE_SINGLE";Jl.Scalar=br;Jl.isScalarValue=ZS});var ra=R(tm=>{"use strict";var eE=ta(),oi=W(),em=de(),tE="tag:yaml.org,2002:";function rE(e,t,r){if(t){let i=r.filter(a=>a.tag===t),n=i.find(a=>!a.format)??i[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return r.find(i=>i.identify?.(e)&&!i.format)}function iE(e,t,r){if(oi.isDocument(e)&&(e=e.contents),oi.isNode(e))return e;if(oi.isPair(e)){let d=r.schema[oi.MAP].createNode?.(r.schema,null,r);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:i,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=r,c;if(i&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new eE.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=tE+t.slice(2));let l=rE(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new em.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[oi.MAP]:Symbol.iterator in Object(e)?o[oi.SEQ]:o[oi.MAP]}a&&(a(l),delete r.onTagObj);let u=l?.createNode?l.createNode(r.schema,e,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,e,r):new em.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}tm.createNode=iE});var ts=R(es=>{"use strict";var nE=ra(),At=W(),aE=Qo();function Ul(e,t,r){let i=r;for(let n=t.length-1;n>=0;--n){let a=t[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=i,i=o}else i=new Map([[a,i]])}return nE.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var rm=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Kl=class extends aE.NodeBase{constructor(t,r){super(t),Object.defineProperty(this,"schema",{value:r,configurable:!0,enumerable:!1,writable:!0})}clone(t){let r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(r.schema=t),r.items=r.items.map(i=>At.isNode(i)||At.isPair(i)?i.clone(t):i),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(rm(t))this.add(r);else{let[i,...n]=t,a=this.get(i,!0);if(At.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,Ul(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}deleteIn(t){let[r,...i]=t;if(i.length===0)return this.delete(r);let n=this.get(r,!0);if(At.isCollection(n))return n.deleteIn(i);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}getIn(t,r){let[i,...n]=t,a=this.get(i,!0);return n.length===0?!r&&At.isScalar(a)?a.value:a:At.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!At.isPair(r))return!1;let i=r.value;return i==null||t&&At.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(t){let[r,...i]=t;if(i.length===0)return this.has(r);let n=this.get(r,!0);return At.isCollection(n)?n.hasIn(i):!1}setIn(t,r){let[i,...n]=t;if(n.length===0)this.set(i,r);else{let a=this.get(i,!0);if(At.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,Ul(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};es.Collection=Kl;es.collectionFromPath=Ul;es.isEmptyPath=rm});var ia=R(rs=>{"use strict";var oE=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Yl(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var sE=(e,t,r)=>e.endsWith(`
7
- `)?Yl(r,t):r.includes(`
4
+ var bS=Object.create;var Ll=Object.defineProperty;var kS=Object.getOwnPropertyDescriptor;var SS=Object.getOwnPropertyNames;var ES=Object.getPrototypeOf,xS=Object.prototype.hasOwnProperty;var Jo=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var I=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(i){throw r=[i],i}};var R=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},CS=(e,t)=>{for(var r in t)Ll(e,r,{get:t[r],enumerable:!0})},RS=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of SS(t))!xS.call(e,n)&&n!==r&&Ll(e,n,{get:()=>t[n],enumerable:!(i=kS(t,n))||i.enumerable});return e};var Kt=(e,t,r)=>(r=e!=null?bS(ES(e)):{},RS(t||!e||!e.__esModule?Ll(r,"default",{value:e,enumerable:!0}):r,e));import{AsyncLocalStorage as PS}from"node:async_hooks";import{performance as Th}from"node:perf_hooks";function ql(e=0){_S+=1,AS+=e;let t=IS.getStore();t&&(t.gitCommands+=1,t.gitDurationMs+=e)}function Gn(e){let t=Th.now();try{return e()}finally{ql(Th.now()-t)}}var _S,AS,IS,Di=I(()=>{"use strict";_S=0,AS=0,IS=new PS});var JD,Jn=I(()=>{"use strict";JD=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ")});var XD,Bi=I(()=>{"use strict";Di();Jn();XD=8*1024*1024});import{createHash as BS}from"crypto";function dt(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function FS(e,t){t.has(e)&&dt("cyclic structures are not supported"),t.add(e);try{let r=Object.keys(e);for(let i=0;i<e.length;i+=1)Object.prototype.hasOwnProperty.call(e,i)||dt("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&dt("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&dt("symbol properties are not supported"),`[${e.map(i=>Ml(i,t)).join(",")}]`}finally{t.delete(e)}}function LS(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&dt("only plain objects are supported"),t.has(e)&&dt("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&dt("symbol properties are not supported"),t.add(e);try{let i=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=i[o];return(!s||!("value"in s))&&dt("accessor properties are not supported"),`${JSON.stringify(o)}:${Ml(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function Ml(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)||dt("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?FS(e,t):LS(e,t);case"bigint":case"function":case"symbol":case"undefined":return dt(`${typeof e} values are not supported`)}return dt("unsupported value type")}function Xn(e){return Ml(e,new Set)}function T(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 BS("sha256").update(`${e}
5
+ ${Xn(t)}`).digest("hex")}var ue=I(()=>{"use strict"});var W=R(ke=>{"use strict";var Vl=Symbol.for("yaml.alias"),Fh=Symbol.for("yaml.document"),Ko=Symbol.for("yaml.map"),Lh=Symbol.for("yaml.pair"),Wl=Symbol.for("yaml.scalar"),Yo=Symbol.for("yaml.seq"),Xt=Symbol.for("yaml.node.type"),qS=e=>!!e&&typeof e=="object"&&e[Xt]===Vl,MS=e=>!!e&&typeof e=="object"&&e[Xt]===Fh,VS=e=>!!e&&typeof e=="object"&&e[Xt]===Ko,WS=e=>!!e&&typeof e=="object"&&e[Xt]===Lh,qh=e=>!!e&&typeof e=="object"&&e[Xt]===Wl,zS=e=>!!e&&typeof e=="object"&&e[Xt]===Yo;function Mh(e){if(e&&typeof e=="object")switch(e[Xt]){case Ko:case Yo:return!0}return!1}function GS(e){if(e&&typeof e=="object")switch(e[Xt]){case Vl:case Ko:case Wl:case Yo:return!0}return!1}var JS=e=>(qh(e)||Mh(e))&&!!e.anchor;ke.ALIAS=Vl;ke.DOC=Fh;ke.MAP=Ko;ke.NODE_TYPE=Xt;ke.PAIR=Lh;ke.SCALAR=Wl;ke.SEQ=Yo;ke.hasAnchor=JS;ke.isAlias=qS;ke.isCollection=Mh;ke.isDocument=MS;ke.isMap=VS;ke.isNode=GS;ke.isPair=WS;ke.isScalar=qh;ke.isSeq=zS});var Qn=R(zl=>{"use strict";var ge=W(),Be=Symbol("break visit"),Vh=Symbol("skip children"),_t=Symbol("remove node");function Xo(e,t){let r=Wh(t);ge.isDocument(e)?Fi(null,e.contents,r,Object.freeze([e]))===_t&&(e.contents=null):Fi(null,e,r,Object.freeze([]))}Xo.BREAK=Be;Xo.SKIP=Vh;Xo.REMOVE=_t;function Fi(e,t,r,i){let n=zh(e,t,r,i);if(ge.isNode(n)||ge.isPair(n))return Gh(e,i,n),Fi(e,n,r,i);if(typeof n!="symbol"){if(ge.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=Fi(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===Be)return Be;o===_t&&(t.items.splice(a,1),a-=1)}}}else if(ge.isPair(t)){i=Object.freeze(i.concat(t));let a=Fi("key",t.key,r,i);if(a===Be)return Be;a===_t&&(t.key=null);let o=Fi("value",t.value,r,i);if(o===Be)return Be;o===_t&&(t.value=null)}}return n}async function Qo(e,t){let r=Wh(t);ge.isDocument(e)?await Li(null,e.contents,r,Object.freeze([e]))===_t&&(e.contents=null):await Li(null,e,r,Object.freeze([]))}Qo.BREAK=Be;Qo.SKIP=Vh;Qo.REMOVE=_t;async function Li(e,t,r,i){let n=await zh(e,t,r,i);if(ge.isNode(n)||ge.isPair(n))return Gh(e,i,n),Li(e,n,r,i);if(typeof n!="symbol"){if(ge.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await Li(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===Be)return Be;o===_t&&(t.items.splice(a,1),a-=1)}}}else if(ge.isPair(t)){i=Object.freeze(i.concat(t));let a=await Li("key",t.key,r,i);if(a===Be)return Be;a===_t&&(t.key=null);let o=await Li("value",t.value,r,i);if(o===Be)return Be;o===_t&&(t.value=null)}}return n}function Wh(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 zh(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(ge.isMap(t))return r.Map?.(e,t,i);if(ge.isSeq(t))return r.Seq?.(e,t,i);if(ge.isPair(t))return r.Pair?.(e,t,i);if(ge.isScalar(t))return r.Scalar?.(e,t,i);if(ge.isAlias(t))return r.Alias?.(e,t,i)}function Gh(e,t,r){let i=t[t.length-1];if(ge.isCollection(i))i.items[e]=r;else if(ge.isPair(i))e==="key"?i.key=r:i.value=r;else if(ge.isDocument(i))i.contents=r;else{let n=ge.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}zl.visit=Xo;zl.visitAsync=Qo});var Gl=R(Uh=>{"use strict";var Jh=W(),US=Qn(),KS={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},YS=e=>e.replace(/[!,[\]{}]/g,t=>KS[t]),Zn=class e{constructor(t,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,r)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,r){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let i=t.trim().split(/[ \t]+/),n=i.shift();switch(n){case"%TAG":{if(i.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[a,o]=i;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;let[a]=i;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return r(6,`Unsupported YAML version ${a}`,o),!1}}default:return r(0,`Unknown directive ${n}`,!0),!1}}tagName(t,r){if(t==="!")return"!";if(t[0]!=="!")return r(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}let[,i,n]=t.match(/^(.*!)([^!]*)$/s);n||r(`The ${t} tag has no suffix`);let a=this.tags[i];if(a)try{return a+decodeURIComponent(n)}catch(o){return r(String(o)),null}return i==="!"?t:(r(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[r,i]of Object.entries(this.tags))if(t.startsWith(i))return r+YS(t.substring(i.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),n;if(t&&i.length>0&&Jh.isNode(t.contents)){let a={};US.visit(t.contents,(o,s)=>{Jh.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of i)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&r.push(`%TAG ${a} ${o}`);return r.join(`
6
+ `)}};Zn.defaultYaml={explicit:!1,version:"1.2"};Zn.defaultTags={"!!":"tag:yaml.org,2002:"};Uh.Directives=Zn});var Zo=R(ea=>{"use strict";var Kh=W(),XS=Qn();function QS(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(r)}return!0}function Yh(e){let t=new Set;return XS.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function Xh(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function ZS(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=Yh(e));let o=Xh(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(Kh.isScalar(o.node)||Kh.isCollection(o.node)))o.node.anchor=o.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=a,s}}},sourceObjects:i}}ea.anchorIsValid=QS;ea.anchorNames=Yh;ea.createNodeAnchors=ZS;ea.findNewAnchor=Xh});var Jl=R(Qh=>{"use strict";function ta(e,t,r,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let n=0,a=i.length;n<a;++n){let o=i[n],s=ta(e,i,String(n),o);s===void 0?delete i[n]:s!==o&&(i[n]=s)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let a=i.get(n),o=ta(e,i,n,a);o===void 0?i.delete(n):o!==a&&i.set(n,o)}else if(i instanceof Set)for(let n of Array.from(i)){let a=ta(e,i,n,n);a===void 0?i.delete(n):a!==n&&(i.delete(n),i.add(a))}else for(let[n,a]of Object.entries(i)){let o=ta(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}Qh.applyReviver=ta});var Nr=R(em=>{"use strict";var eE=W();function Zh(e,t,r){if(Array.isArray(e))return e.map((i,n)=>Zh(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!eE.hasAnchor(e))return e.toJSON(t,r);let i={aliasCount:0,count:1,res:void 0};r.anchors.set(e,i),r.onCreate=a=>{i.res=a,delete r.onCreate};let n=e.toJSON(t,r);return r.onCreate&&r.onCreate(n),n}return typeof e=="bigint"&&!r?.keep?Number(e):e}em.toJS=Zh});var es=R(rm=>{"use strict";var tE=Jl(),tm=W(),rE=Nr(),Ul=class{constructor(t){Object.defineProperty(this,tm.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:r,maxAliasCount:i,onAnchor:n,reviver:a}={}){if(!tm.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},s=rE.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?tE.applyReviver(a,{"":s},"",s):s}};rm.NodeBase=Ul});var ra=R(im=>{"use strict";var iE=Zo(),nE=Qn(),qi=W(),aE=es(),oE=Nr(),Kl=class extends aE.NodeBase{constructor(t){super(qi.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,r){if(r?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;r?.aliasResolveCache?i=r.aliasResolveCache:(i=[],nE.visit(t,{Node:(a,o)=>{(qi.isAlias(o)||qi.hasAnchor(o))&&i.push(o)}}),r&&(r.aliasResolveCache=i));let n;for(let a of i){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,r){if(!r)return{source:this.source};let{anchors:i,doc:n,maxAliasCount:a}=r,o=this.resolve(n,r);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=i.get(o);if(s||(oE.toJS(o,null,r),s=i.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=ts(n,o,i)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,r,i){let n=`*${this.source}`;if(t){if(iE.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 ts(e,t,r){if(qi.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(qi.isCollection(t)){let i=0;for(let n of t.items){let a=ts(e,n,r);a>i&&(i=a)}return i}else if(qi.isPair(t)){let i=ts(e,t.key,r),n=ts(e,t.value,r);return Math.max(i,n)}return 1}im.Alias=Kl});var de=R(Yl=>{"use strict";var sE=W(),cE=es(),lE=Nr(),uE=e=>!e||typeof e!="function"&&typeof e!="object",br=class extends cE.NodeBase{constructor(t){super(sE.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:lE.toJS(this.value,t,r)}toString(){return String(this.value)}};br.BLOCK_FOLDED="BLOCK_FOLDED";br.BLOCK_LITERAL="BLOCK_LITERAL";br.PLAIN="PLAIN";br.QUOTE_DOUBLE="QUOTE_DOUBLE";br.QUOTE_SINGLE="QUOTE_SINGLE";Yl.Scalar=br;Yl.isScalarValue=uE});var ia=R(am=>{"use strict";var dE=ra(),oi=W(),nm=de(),pE="tag:yaml.org,2002:";function fE(e,t,r){if(t){let i=r.filter(a=>a.tag===t),n=i.find(a=>!a.format)??i[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return r.find(i=>i.identify?.(e)&&!i.format)}function hE(e,t,r){if(oi.isDocument(e)&&(e=e.contents),oi.isNode(e))return e;if(oi.isPair(e)){let d=r.schema[oi.MAP].createNode?.(r.schema,null,r);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:i,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=r,c;if(i&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new dE.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=pE+t.slice(2));let l=fE(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new nm.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[oi.MAP]:Symbol.iterator in Object(e)?o[oi.SEQ]:o[oi.MAP]}a&&(a(l),delete r.onTagObj);let u=l?.createNode?l.createNode(r.schema,e,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,e,r):new nm.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}am.createNode=hE});var is=R(rs=>{"use strict";var mE=ia(),At=W(),vE=es();function Xl(e,t,r){let i=r;for(let n=t.length-1;n>=0;--n){let a=t[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=i,i=o}else i=new Map([[a,i]])}return mE.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var om=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Ql=class extends vE.NodeBase{constructor(t,r){super(t),Object.defineProperty(this,"schema",{value:r,configurable:!0,enumerable:!1,writable:!0})}clone(t){let r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(r.schema=t),r.items=r.items.map(i=>At.isNode(i)||At.isPair(i)?i.clone(t):i),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(om(t))this.add(r);else{let[i,...n]=t,a=this.get(i,!0);if(At.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,Xl(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}deleteIn(t){let[r,...i]=t;if(i.length===0)return this.delete(r);let n=this.get(r,!0);if(At.isCollection(n))return n.deleteIn(i);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}getIn(t,r){let[i,...n]=t,a=this.get(i,!0);return n.length===0?!r&&At.isScalar(a)?a.value:a:At.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!At.isPair(r))return!1;let i=r.value;return i==null||t&&At.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(t){let[r,...i]=t;if(i.length===0)return this.has(r);let n=this.get(r,!0);return At.isCollection(n)?n.hasIn(i):!1}setIn(t,r){let[i,...n]=t;if(n.length===0)this.set(i,r);else{let a=this.get(i,!0);if(At.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,Xl(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};rs.Collection=Ql;rs.collectionFromPath=Xl;rs.isEmptyPath=om});var na=R(ns=>{"use strict";var gE=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Zl(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var wE=(e,t,r)=>e.endsWith(`
7
+ `)?Zl(r,t):r.includes(`
8
8
  `)?`
9
- `+Yl(r,t):(e.endsWith(" ")?"":" ")+r;rs.indentComment=Yl;rs.lineComment=sE;rs.stringifyComment=oE});var nm=R(na=>{"use strict";var cE="flow",Xl="block",is="quoted";function lE(e,t,r="flow",{indentAtStart:i,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;n<a&&(a=0);let c=Math.max(1+a,1+n-t.length);if(e.length<=c)return e;let l=[],u={},d=n-t.length;typeof i=="number"&&(i>n-Math.max(2,a)?l.push(0):d=n-i);let p,f,m=!1,h=-1,v=-1,g=-1;r===Xl&&(h=im(e,h,t.length),h!==-1&&(d=h+c));for(let k;k=e[h+=1];){if(r===is&&k==="\\"){switch(v=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}g=h}if(k===`
10
- `)r===Xl&&(h=im(e,h,t.length)),d=h+t.length+c,p=void 0;else{if(k===" "&&f&&f!==" "&&f!==`
9
+ `+Zl(r,t):(e.endsWith(" ")?"":" ")+r;ns.indentComment=Zl;ns.lineComment=wE;ns.stringifyComment=gE});var cm=R(aa=>{"use strict";var yE="flow",eu="block",as="quoted";function NE(e,t,r="flow",{indentAtStart:i,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;n<a&&(a=0);let c=Math.max(1+a,1+n-t.length);if(e.length<=c)return e;let l=[],u={},d=n-t.length;typeof i=="number"&&(i>n-Math.max(2,a)?l.push(0):d=n-i);let p,f,m=!1,h=-1,v=-1,g=-1;r===eu&&(h=sm(e,h,t.length),h!==-1&&(d=h+c));for(let k;k=e[h+=1];){if(r===as&&k==="\\"){switch(v=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}g=h}if(k===`
10
+ `)r===eu&&(h=sm(e,h,t.length)),d=h+t.length+c,p=void 0;else{if(k===" "&&f&&f!==" "&&f!==`
11
11
  `&&f!==" "){let N=e[h+1];N&&N!==" "&&N!==`
12
- `&&N!==" "&&(p=h)}if(h>=d)if(p)l.push(p),d=p+c,p=void 0;else if(r===is){for(;f===" "||f===" ";)f=k,k=e[h+=1],m=!0;let N=h>g+1?h-2:v-1;if(u[N])return e;l.push(N),u[N]=!0,d=N+c,p=void 0}else m=!0}f=k}if(m&&s&&s(),l.length===0)return e;o&&o();let b=e.slice(0,l[0]);for(let k=0;k<l.length;++k){let N=l[k],x=l[k+1]||e.length;N===0?b=`
13
- ${t}${e.slice(0,x)}`:(r===is&&u[N]&&(b+=`${e[N]}\\`),b+=`
14
- ${t}${e.slice(N+1,x)}`)}return b}function im(e,t,r){let i=t,n=t+1,a=e[n];for(;a===" "||a===" ";)if(t<n+r)a=e[++t];else{do a=e[++t];while(a&&a!==`
15
- `);i=t,n=t+1,a=e[n]}return i}na.FOLD_BLOCK=Xl;na.FOLD_FLOW=cE;na.FOLD_QUOTED=is;na.foldFlowLines=lE});var oa=R(am=>{"use strict";var pt=de(),kr=nm(),as=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),os=e=>/^(%|---|\.\.\.)/m.test(e);function uE(e,t,r){if(!t||t<0)return!1;let i=t-r,n=e.length;if(n<=i)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
16
- `){if(a-o>i)return!0;if(o=a+1,n-o<=i)return!1}return!0}function aa(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:i}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(os(e)?" ":""),o="",s=0;for(let c=0,l=r[c];l;l=r[++c])if(l===" "&&r[c+1]==="\\"&&r[c+2]==="n"&&(o+=r.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(r[c+1]){case"u":{o+=r.slice(s,c);let u=r.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+=r.substr(c,6)}c+=5,s=c+1}break;case"n":if(i||r[c+2]==='"'||r.length<n)c+=1;else{for(o+=r.slice(s,c)+`
12
+ `&&N!==" "&&(p=h)}if(h>=d)if(p)l.push(p),d=p+c,p=void 0;else if(r===as){for(;f===" "||f===" ";)f=k,k=e[h+=1],m=!0;let N=h>g+1?h-2:v-1;if(u[N])return e;l.push(N),u[N]=!0,d=N+c,p=void 0}else m=!0}f=k}if(m&&s&&s(),l.length===0)return e;o&&o();let b=e.slice(0,l[0]);for(let k=0;k<l.length;++k){let N=l[k],x=l[k+1]||e.length;N===0?b=`
13
+ ${t}${e.slice(0,x)}`:(r===as&&u[N]&&(b+=`${e[N]}\\`),b+=`
14
+ ${t}${e.slice(N+1,x)}`)}return b}function sm(e,t,r){let i=t,n=t+1,a=e[n];for(;a===" "||a===" ";)if(t<n+r)a=e[++t];else{do a=e[++t];while(a&&a!==`
15
+ `);i=t,n=t+1,a=e[n]}return i}aa.FOLD_BLOCK=eu;aa.FOLD_FLOW=yE;aa.FOLD_QUOTED=as;aa.foldFlowLines=NE});var sa=R(lm=>{"use strict";var pt=de(),kr=cm(),ss=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),cs=e=>/^(%|---|\.\.\.)/m.test(e);function bE(e,t,r){if(!t||t<0)return!1;let i=t-r,n=e.length;if(n<=i)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
16
+ `){if(a-o>i)return!0;if(o=a+1,n-o<=i)return!1}return!0}function oa(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:i}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(cs(e)?" ":""),o="",s=0;for(let c=0,l=r[c];l;l=r[++c])if(l===" "&&r[c+1]==="\\"&&r[c+2]==="n"&&(o+=r.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(r[c+1]){case"u":{o+=r.slice(s,c);let u=r.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+=r.substr(c,6)}c+=5,s=c+1}break;case"n":if(i||r[c+2]==='"'||r.length<n)c+=1;else{for(o+=r.slice(s,c)+`
17
17
 
18
18
  `;r[c+2]==="\\"&&r[c+3]==="n"&&r[c+4]!=='"';)o+=`
19
- `,c+=2;o+=a,r[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+r.slice(s):r,i?o:kr.foldFlowLines(o,a,kr.FOLD_QUOTED,as(t,!1))}function Ql(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
20
- `)||/[ \t]\n|\n[ \t]/.test(e))return aa(e,t);let r=t.indent||(os(e)?" ":""),i="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
21
- ${r}`)+"'";return t.implicitKey?i:kr.foldFlowLines(i,r,kr.FOLD_FLOW,as(t,!1))}function qi(e,t){let{singleQuote:r}=t.options,i;if(r===!1)i=aa;else{let n=e.includes('"'),a=e.includes("'");n&&!a?i=Ql:a&&!n?i=aa:i=r?Ql:aa}return i(e,t)}var Zl;try{Zl=new RegExp(`(^|(?<!
19
+ `,c+=2;o+=a,r[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+r.slice(s):r,i?o:kr.foldFlowLines(o,a,kr.FOLD_QUOTED,ss(t,!1))}function tu(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
20
+ `)||/[ \t]\n|\n[ \t]/.test(e))return oa(e,t);let r=t.indent||(cs(e)?" ":""),i="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
21
+ ${r}`)+"'";return t.implicitKey?i:kr.foldFlowLines(i,r,kr.FOLD_FLOW,ss(t,!1))}function Mi(e,t){let{singleQuote:r}=t.options,i;if(r===!1)i=oa;else{let n=e.includes('"'),a=e.includes("'");n&&!a?i=tu:a&&!n?i=oa:i=r?tu:oa}return i(e,t)}var ru;try{ru=new RegExp(`(^|(?<!
22
22
  ))
23
23
  +(?!
24
- |$)`,"g")}catch{Zl=/\n+(?!\n|$)/g}function ns({comment:e,type:t,value:r},i,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=i.options;if(!o||/\n[\t ]+$/.test(r))return qi(r,i);let l=i.indent||(i.forceBlockIndent||os(r)?" ":""),u=o==="literal"?!0:o==="folded"||t===pt.Scalar.BLOCK_FOLDED?!1:t===pt.Scalar.BLOCK_LITERAL?!0:!uE(r,c,l.length);if(!r)return u?`|
24
+ |$)`,"g")}catch{ru=/\n+(?!\n|$)/g}function os({comment:e,type:t,value:r},i,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=i.options;if(!o||/\n[\t ]+$/.test(r))return Mi(r,i);let l=i.indent||(i.forceBlockIndent||cs(r)?" ":""),u=o==="literal"?!0:o==="folded"||t===pt.Scalar.BLOCK_FOLDED?!1:t===pt.Scalar.BLOCK_LITERAL?!0:!bE(r,c,l.length);if(!r)return u?`|
25
25
  `:`>
26
26
  `;let d,p;for(p=r.length;p>0;--p){let x=r[p-1];if(x!==`
27
27
  `&&x!==" "&&x!==" ")break}let f=r.substring(p),m=f.indexOf(`
28
28
  `);m===-1?d="-":r===f||m!==f.length-1?(d="+",a&&a()):d="",f&&(r=r.slice(0,-f.length),f[f.length-1]===`
29
- `&&(f=f.slice(0,-1)),f=f.replace(Zl,`$&${l}`));let h=!1,v,g=-1;for(v=0;v<r.length;++v){let x=r[v];if(x===" ")h=!0;else if(x===`
29
+ `&&(f=f.slice(0,-1)),f=f.replace(ru,`$&${l}`));let h=!1,v,g=-1;for(v=0;v<r.length;++v){let x=r[v];if(x===" ")h=!0;else if(x===`
30
30
  `)g=v;else break}let b=r.substring(0,g<v?g+1:v);b&&(r=r.substring(b.length),b=b.replace(/\n+/g,`$&${l}`));let N=(h?l?"2":"1":"")+d;if(e&&(N+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!u){let x=r.replace(/\n+/g,`
31
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),w=!1,S=as(i,!0);o!=="folded"&&t!==pt.Scalar.BLOCK_FOLDED&&(S.onOverflow=()=>{w=!0});let E=kr.foldFlowLines(`${b}${x}${f}`,l,kr.FOLD_BLOCK,S);if(!w)return`>${N}
31
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),w=!1,S=ss(i,!0);o!=="folded"&&t!==pt.Scalar.BLOCK_FOLDED&&(S.onOverflow=()=>{w=!0});let E=kr.foldFlowLines(`${b}${x}${f}`,l,kr.FOLD_BLOCK,S);if(!w)return`>${N}
32
32
  ${l}${E}`}return r=r.replace(/\n+/g,`$&${l}`),`|${N}
33
- ${l}${b}${r}${f}`}function dE(e,t,r,i){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
34
- `)||u&&/[[\]{},]/.test(a))return qi(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
35
- `)?qi(a,t):ns(e,t,r,i);if(!s&&!u&&n!==pt.Scalar.PLAIN&&a.includes(`
36
- `))return ns(e,t,r,i);if(os(a)){if(c==="")return t.forceBlockIndent=!0,ns(e,t,r,i);if(s&&c===l)return qi(a,t)}let d=a.replace(/\n+/g,`$&
37
- ${c}`);if(o){let p=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:f,tags:m}=t.doc.schema;if(m.some(p)||f?.some(p))return qi(a,t)}return s?d:kr.foldFlowLines(d,c,kr.FOLD_FLOW,as(t,!1))}function pE(e,t,r,i){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==pt.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=pt.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case pt.Scalar.BLOCK_FOLDED:case pt.Scalar.BLOCK_LITERAL:return n||a?qi(o.value,t):ns(o,t,r,i);case pt.Scalar.QUOTE_DOUBLE:return aa(o.value,t);case pt.Scalar.QUOTE_SINGLE:return Ql(o.value,t);case pt.Scalar.PLAIN:return dE(o,t,r,i);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:d}=t.options,p=n&&u||d;if(l=c(p),l===null)throw new Error(`Unsupported default string type ${p}`)}return l}am.stringifyString=pE});var sa=R(eu=>{"use strict";var fE=Xo(),Sr=W(),hE=ia(),mE=oa();function vE(e,t){let r=Object.assign({blockQuote:!0,commentString:hE.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),i;switch(r.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:e,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:i,options:r}}function gE(e,t){if(t.tag){let n=e.filter(a=>a.tag===t.tag);if(n.length>0)return n.find(a=>a.format===t.format)??n[0]}let r,i;if(Sr.isScalar(t)){i=t.value;let n=e.filter(a=>a.identify?.(i));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}r=n.find(a=>a.format===t.format)??n.find(a=>!a.format)}else i=t,r=e.find(n=>n.nodeClass&&i instanceof n.nodeClass);if(!r){let n=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${n} value`)}return r}function wE(e,t,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=(Sr.isScalar(e)||Sr.isCollection(e))&&e.anchor;a&&fE.anchorIsValid(a)&&(r.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(i.directives.tagString(o)),n.join(" ")}function yE(e,t,r,i){if(Sr.isPair(e))return e.toString(t,r,i);if(Sr.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=Sr.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=gE(t.doc.schema.tags,a));let o=wE(a,n,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,t,r,i):Sr.isScalar(a)?mE.stringifyString(a,t,r,i):a.toString(t,r,i);return o?Sr.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
38
- ${t.indent}${s}`:s}eu.createStringifyContext=vE;eu.stringify=yE});var lm=R(cm=>{"use strict";var Qt=W(),om=de(),sm=sa(),ca=ia();function NE({key:e,value:t},r,i,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=r,p=Qt.isNode(e)&&e.comment||null;if(d){if(p)throw new Error("With simple keys, key nodes cannot have comments");if(Qt.isCollection(e)||!Qt.isNode(e)&&typeof e=="object"){let S="With simple keys, collection cannot be used as a key value";throw new Error(S)}}let f=!d&&(!e||p&&t==null&&!r.inFlow||Qt.isCollection(e)||(Qt.isScalar(e)?e.type===om.Scalar.BLOCK_FOLDED||e.type===om.Scalar.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!f&&(d||!a),indent:s+c});let m=!1,h=!1,v=sm.stringify(e,r,()=>m=!0,()=>h=!0);if(!f&&!r.inFlow&&v.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");f=!0}if(r.inFlow){if(a||t==null)return m&&i&&i(),v===""?"?":f?`? ${v}`:v}else if(a&&!d||t==null&&f)return v=`? ${v}`,p&&!m?v+=ca.lineComment(v,r.indent,l(p)):h&&n&&n(),v;m&&(p=null),f?(p&&(v+=ca.lineComment(v,r.indent,l(p))),v=`? ${v}
39
- ${s}:`):(v=`${v}:`,p&&(v+=ca.lineComment(v,r.indent,l(p))));let g,b,k;Qt.isNode(t)?(g=!!t.spaceBefore,b=t.commentBefore,k=t.comment):(g=!1,b=null,k=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!f&&!p&&Qt.isScalar(t)&&(r.indentAtStart=v.length+1),h=!1,!u&&c.length>=2&&!r.inFlow&&!f&&Qt.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let N=!1,x=sm.stringify(t,r,()=>N=!0,()=>h=!0),w=" ";if(p||g||b){if(w=g?`
33
+ ${l}${b}${r}${f}`}function kE(e,t,r,i){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
34
+ `)||u&&/[[\]{},]/.test(a))return Mi(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
35
+ `)?Mi(a,t):os(e,t,r,i);if(!s&&!u&&n!==pt.Scalar.PLAIN&&a.includes(`
36
+ `))return os(e,t,r,i);if(cs(a)){if(c==="")return t.forceBlockIndent=!0,os(e,t,r,i);if(s&&c===l)return Mi(a,t)}let d=a.replace(/\n+/g,`$&
37
+ ${c}`);if(o){let p=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:f,tags:m}=t.doc.schema;if(m.some(p)||f?.some(p))return Mi(a,t)}return s?d:kr.foldFlowLines(d,c,kr.FOLD_FLOW,ss(t,!1))}function SE(e,t,r,i){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==pt.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=pt.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case pt.Scalar.BLOCK_FOLDED:case pt.Scalar.BLOCK_LITERAL:return n||a?Mi(o.value,t):os(o,t,r,i);case pt.Scalar.QUOTE_DOUBLE:return oa(o.value,t);case pt.Scalar.QUOTE_SINGLE:return tu(o.value,t);case pt.Scalar.PLAIN:return kE(o,t,r,i);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:d}=t.options,p=n&&u||d;if(l=c(p),l===null)throw new Error(`Unsupported default string type ${p}`)}return l}lm.stringifyString=SE});var ca=R(iu=>{"use strict";var EE=Zo(),Sr=W(),xE=na(),CE=sa();function RE(e,t){let r=Object.assign({blockQuote:!0,commentString:xE.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),i;switch(r.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:e,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:i,options:r}}function PE(e,t){if(t.tag){let n=e.filter(a=>a.tag===t.tag);if(n.length>0)return n.find(a=>a.format===t.format)??n[0]}let r,i;if(Sr.isScalar(t)){i=t.value;let n=e.filter(a=>a.identify?.(i));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}r=n.find(a=>a.format===t.format)??n.find(a=>!a.format)}else i=t,r=e.find(n=>n.nodeClass&&i instanceof n.nodeClass);if(!r){let n=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${n} value`)}return r}function _E(e,t,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=(Sr.isScalar(e)||Sr.isCollection(e))&&e.anchor;a&&EE.anchorIsValid(a)&&(r.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(i.directives.tagString(o)),n.join(" ")}function AE(e,t,r,i){if(Sr.isPair(e))return e.toString(t,r,i);if(Sr.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=Sr.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=PE(t.doc.schema.tags,a));let o=_E(a,n,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,t,r,i):Sr.isScalar(a)?CE.stringifyString(a,t,r,i):a.toString(t,r,i);return o?Sr.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
38
+ ${t.indent}${s}`:s}iu.createStringifyContext=RE;iu.stringify=AE});var fm=R(pm=>{"use strict";var Qt=W(),um=de(),dm=ca(),la=na();function IE({key:e,value:t},r,i,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=r,p=Qt.isNode(e)&&e.comment||null;if(d){if(p)throw new Error("With simple keys, key nodes cannot have comments");if(Qt.isCollection(e)||!Qt.isNode(e)&&typeof e=="object"){let S="With simple keys, collection cannot be used as a key value";throw new Error(S)}}let f=!d&&(!e||p&&t==null&&!r.inFlow||Qt.isCollection(e)||(Qt.isScalar(e)?e.type===um.Scalar.BLOCK_FOLDED||e.type===um.Scalar.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!f&&(d||!a),indent:s+c});let m=!1,h=!1,v=dm.stringify(e,r,()=>m=!0,()=>h=!0);if(!f&&!r.inFlow&&v.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");f=!0}if(r.inFlow){if(a||t==null)return m&&i&&i(),v===""?"?":f?`? ${v}`:v}else if(a&&!d||t==null&&f)return v=`? ${v}`,p&&!m?v+=la.lineComment(v,r.indent,l(p)):h&&n&&n(),v;m&&(p=null),f?(p&&(v+=la.lineComment(v,r.indent,l(p))),v=`? ${v}
39
+ ${s}:`):(v=`${v}:`,p&&(v+=la.lineComment(v,r.indent,l(p))));let g,b,k;Qt.isNode(t)?(g=!!t.spaceBefore,b=t.commentBefore,k=t.comment):(g=!1,b=null,k=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!f&&!p&&Qt.isScalar(t)&&(r.indentAtStart=v.length+1),h=!1,!u&&c.length>=2&&!r.inFlow&&!f&&Qt.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let N=!1,x=dm.stringify(t,r,()=>N=!0,()=>h=!0),w=" ";if(p||g||b){if(w=g?`
40
40
  `:"",b){let S=l(b);w+=`
41
- ${ca.indentComment(S,r.indent)}`}x===""&&!r.inFlow?w===`
41
+ ${la.indentComment(S,r.indent)}`}x===""&&!r.inFlow?w===`
42
42
  `&&k&&(w=`
43
43
 
44
44
  `):w+=`
45
45
  ${r.indent}`}else if(!f&&Qt.isCollection(t)){let S=x[0],E=x.indexOf(`
46
46
  `),y=E!==-1,C=r.inFlow??t.flow??t.items.length===0;if(y||!C){let O=!1;if(y&&(S==="&"||S==="!")){let j=x.indexOf(" ");S==="&"&&j!==-1&&j<E&&x[j+1]==="!"&&(j=x.indexOf(" ",j+1)),(j===-1||E<j)&&(O=!0)}O||(w=`
47
47
  ${r.indent}`)}}else(x===""||x[0]===`
48
- `)&&(w="");return v+=w+x,r.inFlow?N&&i&&i():k&&!N?v+=ca.lineComment(v,r.indent,l(k)):h&&n&&n(),v}cm.stringifyPair=NE});var ru=R(tu=>{"use strict";var um=zo("process");function bE(e,...t){e==="debug"&&console.log(...t)}function kE(e,t){(e==="debug"||e==="warn")&&(typeof um.emitWarning=="function"?um.emitWarning(t):console.warn(t))}tu.debug=bE;tu.warn=kE});var ds=R(us=>{"use strict";var ls=W(),dm=de(),ss="<<",cs={identify:e=>e===ss||typeof e=="symbol"&&e.description===ss,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new dm.Scalar(Symbol(ss)),{addToJSMap:pm}),stringify:()=>ss},SE=(e,t)=>(cs.identify(t)||ls.isScalar(t)&&(!t.type||t.type===dm.Scalar.PLAIN)&&cs.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===cs.tag&&r.default);function pm(e,t,r){let i=fm(e,r);if(ls.isSeq(i))for(let n of i.items)iu(e,t,n);else if(Array.isArray(i))for(let n of i)iu(e,t,n);else iu(e,t,i)}function iu(e,t,r){let i=fm(e,r);if(!ls.isMap(i))throw new Error("Merge sources must be maps or map aliases");let n=i.toJSON(null,e,Map);for(let[a,o]of n)t instanceof Map?t.has(a)||t.set(a,o):t instanceof Set?t.add(a):Object.prototype.hasOwnProperty.call(t,a)||Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function fm(e,t){return e&&ls.isAlias(t)?t.resolve(e.doc,e):t}us.addMergeToJSMap=pm;us.isMergeKey=SE;us.merge=cs});var au=R(vm=>{"use strict";var EE=ru(),hm=ds(),xE=sa(),mm=W(),nu=Nr();function CE(e,t,{key:r,value:i}){if(mm.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,i);else if(hm.isMergeKey(e,r))hm.addMergeToJSMap(e,t,i);else{let n=nu.toJS(r,"",e);if(t instanceof Map)t.set(n,nu.toJS(i,n,e));else if(t instanceof Set)t.add(n);else{let a=RE(r,n,e),o=nu.toJS(i,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function RE(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(mm.isNode(e)&&r?.doc){let i=xE.createStringifyContext(r.doc,{});i.anchors=new Set;for(let a of r.anchors.keys())i.anchors.add(a.anchor);i.inFlow=!0,i.inStringifyKey=!0;let n=e.toString(i);if(!r.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),EE.warn(r.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),r.mapKeyWarned=!0}return n}return JSON.stringify(t)}vm.addPairToJSMap=CE});var Er=R(ou=>{"use strict";var gm=ra(),PE=lm(),_E=au(),ps=W();function AE(e,t,r){let i=gm.createNode(e,void 0,r),n=gm.createNode(t,void 0,r);return new fs(i,n)}var fs=class e{constructor(t,r=null){Object.defineProperty(this,ps.NODE_TYPE,{value:ps.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:i}=this;return ps.isNode(r)&&(r=r.clone(t)),ps.isNode(i)&&(i=i.clone(t)),new e(r,i)}toJSON(t,r){let i=r?.mapAsMap?new Map:{};return _E.addPairToJSMap(r,i,this)}toString(t,r,i){return t?.doc?PE.stringifyPair(this,t,r,i):JSON.stringify(this)}};ou.Pair=fs;ou.createPair=AE});var su=R(ym=>{"use strict";var si=W(),wm=sa(),hs=ia();function IE(e,t,r){return(t.inFlow??e.flow?jE:TE)(e,t,r)}function TE({comment:e,items:t},r,{blockItemPrefix:i,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=r,u=Object.assign({},r,{indent:a,type:null}),d=!1,p=[];for(let m=0;m<t.length;++m){let h=t[m],v=null;if(si.isNode(h))!d&&h.spaceBefore&&p.push(""),ms(r,p,h.commentBefore,d),h.comment&&(v=h.comment);else if(si.isPair(h)){let b=si.isNode(h.key)?h.key:null;b&&(!d&&b.spaceBefore&&p.push(""),ms(r,p,b.commentBefore,d))}d=!1;let g=wm.stringify(h,u,()=>v=null,()=>d=!0);v&&(g+=hs.lineComment(g,a,l(v))),d&&v&&(d=!1),p.push(i+g)}let f;if(p.length===0)f=n.start+n.end;else{f=p[0];for(let m=1;m<p.length;++m){let h=p[m];f+=h?`
48
+ `)&&(w="");return v+=w+x,r.inFlow?N&&i&&i():k&&!N?v+=la.lineComment(v,r.indent,l(k)):h&&n&&n(),v}pm.stringifyPair=IE});var au=R(nu=>{"use strict";var hm=Jo("process");function TE(e,...t){e==="debug"&&console.log(...t)}function jE(e,t){(e==="debug"||e==="warn")&&(typeof hm.emitWarning=="function"?hm.emitWarning(t):console.warn(t))}nu.debug=TE;nu.warn=jE});var fs=R(ps=>{"use strict";var ds=W(),mm=de(),ls="<<",us={identify:e=>e===ls||typeof e=="symbol"&&e.description===ls,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new mm.Scalar(Symbol(ls)),{addToJSMap:vm}),stringify:()=>ls},$E=(e,t)=>(us.identify(t)||ds.isScalar(t)&&(!t.type||t.type===mm.Scalar.PLAIN)&&us.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===us.tag&&r.default);function vm(e,t,r){let i=gm(e,r);if(ds.isSeq(i))for(let n of i.items)ou(e,t,n);else if(Array.isArray(i))for(let n of i)ou(e,t,n);else ou(e,t,i)}function ou(e,t,r){let i=gm(e,r);if(!ds.isMap(i))throw new Error("Merge sources must be maps or map aliases");let n=i.toJSON(null,e,Map);for(let[a,o]of n)t instanceof Map?t.has(a)||t.set(a,o):t instanceof Set?t.add(a):Object.prototype.hasOwnProperty.call(t,a)||Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function gm(e,t){return e&&ds.isAlias(t)?t.resolve(e.doc,e):t}ps.addMergeToJSMap=vm;ps.isMergeKey=$E;ps.merge=us});var cu=R(Nm=>{"use strict";var OE=au(),wm=fs(),HE=ca(),ym=W(),su=Nr();function DE(e,t,{key:r,value:i}){if(ym.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,i);else if(wm.isMergeKey(e,r))wm.addMergeToJSMap(e,t,i);else{let n=su.toJS(r,"",e);if(t instanceof Map)t.set(n,su.toJS(i,n,e));else if(t instanceof Set)t.add(n);else{let a=BE(r,n,e),o=su.toJS(i,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function BE(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(ym.isNode(e)&&r?.doc){let i=HE.createStringifyContext(r.doc,{});i.anchors=new Set;for(let a of r.anchors.keys())i.anchors.add(a.anchor);i.inFlow=!0,i.inStringifyKey=!0;let n=e.toString(i);if(!r.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),OE.warn(r.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),r.mapKeyWarned=!0}return n}return JSON.stringify(t)}Nm.addPairToJSMap=DE});var Er=R(lu=>{"use strict";var bm=ia(),FE=fm(),LE=cu(),hs=W();function qE(e,t,r){let i=bm.createNode(e,void 0,r),n=bm.createNode(t,void 0,r);return new ms(i,n)}var ms=class e{constructor(t,r=null){Object.defineProperty(this,hs.NODE_TYPE,{value:hs.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:i}=this;return hs.isNode(r)&&(r=r.clone(t)),hs.isNode(i)&&(i=i.clone(t)),new e(r,i)}toJSON(t,r){let i=r?.mapAsMap?new Map:{};return LE.addPairToJSMap(r,i,this)}toString(t,r,i){return t?.doc?FE.stringifyPair(this,t,r,i):JSON.stringify(this)}};lu.Pair=ms;lu.createPair=qE});var uu=R(Sm=>{"use strict";var si=W(),km=ca(),vs=na();function ME(e,t,r){return(t.inFlow??e.flow?WE:VE)(e,t,r)}function VE({comment:e,items:t},r,{blockItemPrefix:i,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=r,u=Object.assign({},r,{indent:a,type:null}),d=!1,p=[];for(let m=0;m<t.length;++m){let h=t[m],v=null;if(si.isNode(h))!d&&h.spaceBefore&&p.push(""),gs(r,p,h.commentBefore,d),h.comment&&(v=h.comment);else if(si.isPair(h)){let b=si.isNode(h.key)?h.key:null;b&&(!d&&b.spaceBefore&&p.push(""),gs(r,p,b.commentBefore,d))}d=!1;let g=km.stringify(h,u,()=>v=null,()=>d=!0);v&&(g+=vs.lineComment(g,a,l(v))),d&&v&&(d=!1),p.push(i+g)}let f;if(p.length===0)f=n.start+n.end;else{f=p[0];for(let m=1;m<p.length;++m){let h=p[m];f+=h?`
49
49
  ${c}${h}`:`
50
50
  `}}return e?(f+=`
51
- `+hs.indentComment(l(e),c),s&&s()):d&&o&&o(),f}function jE({items:e},t,{flowChars:r,itemIndent:i}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;i+=a;let c=Object.assign({},t,{indent:i,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let m=0;m<e.length;++m){let h=e[m],v=null;if(si.isNode(h))h.spaceBefore&&d.push(""),ms(t,d,h.commentBefore,!1),h.comment&&(v=h.comment);else if(si.isPair(h)){let b=si.isNode(h.key)?h.key:null;b&&(b.spaceBefore&&d.push(""),ms(t,d,b.commentBefore,!1),b.comment&&(l=!0));let k=si.isNode(h.value)?h.value:null;k?(k.comment&&(v=k.comment),k.commentBefore&&(l=!0)):h.value==null&&b?.comment&&(v=b.comment)}v&&(l=!0);let g=wm.stringify(h,c,()=>v=null);l||(l=d.length>u||g.includes(`
52
- `)),m<e.length-1?g+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((b,k)=>b+k.length+2,2)+(g.length+2)>t.options.lineWidth)),l&&(g+=",")),v&&(g+=hs.lineComment(g,i,s(v))),d.push(g),u=d.length}let{start:p,end:f}=r;if(d.length===0)return p+f;if(!l){let m=d.reduce((h,v)=>h+v.length+2,2);l=t.options.lineWidth>0&&m>t.options.lineWidth}if(l){let m=p;for(let h of d)m+=h?`
51
+ `+vs.indentComment(l(e),c),s&&s()):d&&o&&o(),f}function WE({items:e},t,{flowChars:r,itemIndent:i}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;i+=a;let c=Object.assign({},t,{indent:i,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let m=0;m<e.length;++m){let h=e[m],v=null;if(si.isNode(h))h.spaceBefore&&d.push(""),gs(t,d,h.commentBefore,!1),h.comment&&(v=h.comment);else if(si.isPair(h)){let b=si.isNode(h.key)?h.key:null;b&&(b.spaceBefore&&d.push(""),gs(t,d,b.commentBefore,!1),b.comment&&(l=!0));let k=si.isNode(h.value)?h.value:null;k?(k.comment&&(v=k.comment),k.commentBefore&&(l=!0)):h.value==null&&b?.comment&&(v=b.comment)}v&&(l=!0);let g=km.stringify(h,c,()=>v=null);l||(l=d.length>u||g.includes(`
52
+ `)),m<e.length-1?g+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((b,k)=>b+k.length+2,2)+(g.length+2)>t.options.lineWidth)),l&&(g+=",")),v&&(g+=vs.lineComment(g,i,s(v))),d.push(g),u=d.length}let{start:p,end:f}=r;if(d.length===0)return p+f;if(!l){let m=d.reduce((h,v)=>h+v.length+2,2);l=t.options.lineWidth>0&&m>t.options.lineWidth}if(l){let m=p;for(let h of d)m+=h?`
53
53
  ${a}${n}${h}`:`
54
54
  `;return`${m}
55
- ${n}${f}`}else return`${p}${o}${d.join(" ")}${o}${f}`}function ms({indent:e,options:{commentString:t}},r,i,n){if(i&&n&&(i=i.replace(/^\n+/,"")),i){let a=hs.indentComment(t(i),e);r.push(a.trimStart())}}ym.stringifyCollection=IE});var Cr=R(lu=>{"use strict";var $E=su(),OE=au(),HE=ts(),xr=W(),vs=Er(),DE=de();function la(e,t){let r=xr.isScalar(t)?t.value:t;for(let i of e)if(xr.isPair(i)&&(i.key===t||i.key===r||xr.isScalar(i.key)&&i.key.value===r))return i}var cu=class extends HE.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(xr.MAP,t),this.items=[]}static from(t,r,i){let{keepUndefined:n,replacer:a}=i,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(r,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||n)&&o.items.push(vs.createPair(c,l,i))};if(r instanceof Map)for(let[c,l]of r)s(c,l);else if(r&&typeof r=="object")for(let c of Object.keys(r))s(c,r[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,r){let i;xr.isPair(t)?i=t:!t||typeof t!="object"||!("key"in t)?i=new vs.Pair(t,t?.value):i=new vs.Pair(t.key,t.value);let n=la(this.items,i.key),a=this.schema?.sortMapEntries;if(n){if(!r)throw new Error(`Key ${i.key} already set`);xr.isScalar(n.value)&&DE.isScalarValue(i.value)?n.value.value=i.value:n.value=i.value}else if(a){let o=this.items.findIndex(s=>a(i,s)<0);o===-1?this.items.push(i):this.items.splice(o,0,i)}else this.items.push(i)}delete(t){let r=la(this.items,t);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(t,r){let n=la(this.items,t)?.value;return(!r&&xr.isScalar(n)?n.value:n)??void 0}has(t){return!!la(this.items,t)}set(t,r){this.add(new vs.Pair(t,r),!0)}toJSON(t,r,i){let n=i?new i:r?.mapAsMap?new Map:{};r?.onCreate&&r.onCreate(n);for(let a of this.items)OE.addPairToJSMap(r,n,a);return n}toString(t,r,i){if(!t)return JSON.stringify(this);for(let n of this.items)if(!xr.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})),$E.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:i,onComment:r})}};lu.YAMLMap=cu;lu.findPair=la});var Mi=R(bm=>{"use strict";var BE=W(),Nm=Cr(),FE={collection:"map",default:!0,nodeClass:Nm.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return BE.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>Nm.YAMLMap.from(e,t,r)};bm.map=FE});var Rr=R(km=>{"use strict";var LE=ra(),qE=su(),ME=ts(),ws=W(),VE=de(),WE=Nr(),uu=class extends ME.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(ws.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let r=gs(t);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(t,r){let i=gs(t);if(typeof i!="number")return;let n=this.items[i];return!r&&ws.isScalar(n)?n.value:n}has(t){let r=gs(t);return typeof r=="number"&&r<this.items.length}set(t,r){let i=gs(t);if(typeof i!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[i];ws.isScalar(n)&&VE.isScalarValue(r)?n.value=r:this.items[i]=r}toJSON(t,r){let i=[];r?.onCreate&&r.onCreate(i);let n=0;for(let a of this.items)i.push(WE.toJS(a,String(n++),r));return i}toString(t,r,i){return t?qE.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:i,onComment:r}):JSON.stringify(this)}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r)){let o=0;for(let s of r){if(typeof n=="function"){let c=r instanceof Set?s:String(o++);s=n.call(r,c,s)}a.items.push(LE.createNode(s,void 0,i))}}return a}};function gs(e){let t=ws.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}km.YAMLSeq=uu});var Vi=R(Em=>{"use strict";var zE=W(),Sm=Rr(),GE={collection:"seq",default:!0,nodeClass:Sm.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return zE.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>Sm.YAMLSeq.from(e,t,r)};Em.seq=GE});var ua=R(xm=>{"use strict";var JE=oa(),UE={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,r,i){return t=Object.assign({actualString:!0},t),JE.stringifyString(e,t,r,i)}};xm.string=UE});var ys=R(Pm=>{"use strict";var Cm=de(),Rm={identify:e=>e==null,createNode:()=>new Cm.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Cm.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Rm.test.test(e)?e:t.options.nullStr};Pm.nullTag=Rm});var du=R(Am=>{"use strict";var KE=de(),_m={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new KE.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&_m.test.test(e)){let i=e[0]==="t"||e[0]==="T";if(t===i)return e}return t?r.options.trueStr:r.options.falseStr}};Am.boolTag=_m});var Wi=R(Im=>{"use strict";function YE({format:e,minFractionDigits:t,tag:r,value:i}){if(typeof i=="bigint")return String(i);let n=typeof i=="number"?i:Number(i);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let a=Object.is(i,-0)?"-0":JSON.stringify(i);if(!e&&t&&(!r||r==="tag:yaml.org,2002:float")&&/^-?\d/.test(a)&&!a.includes("e")){let o=a.indexOf(".");o<0&&(o=a.length,a+=".");let s=t-(a.length-o-1);for(;s-- >0;)a+="0"}return a}Im.stringifyNumber=YE});var fu=R(Ns=>{"use strict";var XE=de(),pu=Wi(),QE={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:pu.stringifyNumber},ZE={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():pu.stringifyNumber(e)}},ex={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 XE.Scalar(parseFloat(e)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:pu.stringifyNumber};Ns.float=ex;Ns.floatExp=ZE;Ns.floatNaN=QE});var mu=R(ks=>{"use strict";var Tm=Wi(),bs=e=>typeof e=="bigint"||Number.isInteger(e),hu=(e,t,r,{intAsBigInt:i})=>i?BigInt(e):parseInt(e.substring(t),r);function jm(e,t,r){let{value:i}=e;return bs(i)&&i>=0?r+i.toString(t):Tm.stringifyNumber(e)}var tx={identify:e=>bs(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>hu(e,2,8,r),stringify:e=>jm(e,8,"0o")},rx={identify:bs,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>hu(e,0,10,r),stringify:Tm.stringifyNumber},ix={identify:e=>bs(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>hu(e,2,16,r),stringify:e=>jm(e,16,"0x")};ks.int=rx;ks.intHex=ix;ks.intOct=tx});var Om=R($m=>{"use strict";var nx=Mi(),ax=ys(),ox=Vi(),sx=ua(),cx=du(),vu=fu(),gu=mu(),lx=[nx.map,ox.seq,sx.string,ax.nullTag,cx.boolTag,gu.intOct,gu.int,gu.intHex,vu.floatNaN,vu.floatExp,vu.float];$m.schema=lx});var Bm=R(Dm=>{"use strict";var ux=de(),dx=Mi(),px=Vi();function Hm(e){return typeof e=="bigint"||Number.isInteger(e)}var Ss=({value:e})=>JSON.stringify(e),fx=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Ss},{identify:e=>e==null,createNode:()=>new ux.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Ss},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Ss},{identify:Hm,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:r})=>r?BigInt(e):parseInt(e,10),stringify:({value:e})=>Hm(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:Ss}],hx={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},mx=[dx.map,px.seq].concat(fx,hx);Dm.schema=mx});var yu=R(Fm=>{"use strict";var da=zo("buffer"),wu=de(),vx=oa(),gx={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof da.Buffer=="function")return da.Buffer.from(e,"base64");if(typeof atob=="function"){let r=atob(e.replace(/[\n\r]/g,"")),i=new Uint8Array(r.length);for(let n=0;n<r.length;++n)i[n]=r.charCodeAt(n);return i}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:r},i,n,a){if(!r)return"";let o=r,s;if(typeof da.Buffer=="function")s=o instanceof da.Buffer?o.toString("base64"):da.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=wu.Scalar.BLOCK_LITERAL),t!==wu.Scalar.QUOTE_DOUBLE){let c=Math.max(i.options.lineWidth-i.indent.length,i.options.minContentWidth),l=Math.ceil(s.length/c),u=new Array(l);for(let d=0,p=0;d<l;++d,p+=c)u[d]=s.substr(p,c);s=u.join(t===wu.Scalar.BLOCK_LITERAL?`
56
- `:" ")}return vx.stringifyString({comment:e,type:t,value:s},i,n,a)}};Fm.binary=gx});var Cs=R(xs=>{"use strict";var Es=W(),Nu=Er(),wx=de(),yx=Rr();function Lm(e,t){if(Es.isSeq(e))for(let r=0;r<e.items.length;++r){let i=e.items[r];if(!Es.isPair(i)){if(Es.isMap(i)){i.items.length>1&&t("Each pair must have its own sequence indicator");let n=i.items[0]||new Nu.Pair(new wx.Scalar(null));if(i.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${i.commentBefore}
55
+ ${n}${f}`}else return`${p}${o}${d.join(" ")}${o}${f}`}function gs({indent:e,options:{commentString:t}},r,i,n){if(i&&n&&(i=i.replace(/^\n+/,"")),i){let a=vs.indentComment(t(i),e);r.push(a.trimStart())}}Sm.stringifyCollection=ME});var Cr=R(pu=>{"use strict";var zE=uu(),GE=cu(),JE=is(),xr=W(),ws=Er(),UE=de();function ua(e,t){let r=xr.isScalar(t)?t.value:t;for(let i of e)if(xr.isPair(i)&&(i.key===t||i.key===r||xr.isScalar(i.key)&&i.key.value===r))return i}var du=class extends JE.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(xr.MAP,t),this.items=[]}static from(t,r,i){let{keepUndefined:n,replacer:a}=i,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(r,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||n)&&o.items.push(ws.createPair(c,l,i))};if(r instanceof Map)for(let[c,l]of r)s(c,l);else if(r&&typeof r=="object")for(let c of Object.keys(r))s(c,r[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,r){let i;xr.isPair(t)?i=t:!t||typeof t!="object"||!("key"in t)?i=new ws.Pair(t,t?.value):i=new ws.Pair(t.key,t.value);let n=ua(this.items,i.key),a=this.schema?.sortMapEntries;if(n){if(!r)throw new Error(`Key ${i.key} already set`);xr.isScalar(n.value)&&UE.isScalarValue(i.value)?n.value.value=i.value:n.value=i.value}else if(a){let o=this.items.findIndex(s=>a(i,s)<0);o===-1?this.items.push(i):this.items.splice(o,0,i)}else this.items.push(i)}delete(t){let r=ua(this.items,t);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(t,r){let n=ua(this.items,t)?.value;return(!r&&xr.isScalar(n)?n.value:n)??void 0}has(t){return!!ua(this.items,t)}set(t,r){this.add(new ws.Pair(t,r),!0)}toJSON(t,r,i){let n=i?new i:r?.mapAsMap?new Map:{};r?.onCreate&&r.onCreate(n);for(let a of this.items)GE.addPairToJSMap(r,n,a);return n}toString(t,r,i){if(!t)return JSON.stringify(this);for(let n of this.items)if(!xr.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})),zE.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:i,onComment:r})}};pu.YAMLMap=du;pu.findPair=ua});var Vi=R(xm=>{"use strict";var KE=W(),Em=Cr(),YE={collection:"map",default:!0,nodeClass:Em.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return KE.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>Em.YAMLMap.from(e,t,r)};xm.map=YE});var Rr=R(Cm=>{"use strict";var XE=ia(),QE=uu(),ZE=is(),Ns=W(),ex=de(),tx=Nr(),fu=class extends ZE.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Ns.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let r=ys(t);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(t,r){let i=ys(t);if(typeof i!="number")return;let n=this.items[i];return!r&&Ns.isScalar(n)?n.value:n}has(t){let r=ys(t);return typeof r=="number"&&r<this.items.length}set(t,r){let i=ys(t);if(typeof i!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[i];Ns.isScalar(n)&&ex.isScalarValue(r)?n.value=r:this.items[i]=r}toJSON(t,r){let i=[];r?.onCreate&&r.onCreate(i);let n=0;for(let a of this.items)i.push(tx.toJS(a,String(n++),r));return i}toString(t,r,i){return t?QE.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:i,onComment:r}):JSON.stringify(this)}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r)){let o=0;for(let s of r){if(typeof n=="function"){let c=r instanceof Set?s:String(o++);s=n.call(r,c,s)}a.items.push(XE.createNode(s,void 0,i))}}return a}};function ys(e){let t=Ns.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Cm.YAMLSeq=fu});var Wi=R(Pm=>{"use strict";var rx=W(),Rm=Rr(),ix={collection:"seq",default:!0,nodeClass:Rm.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return rx.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>Rm.YAMLSeq.from(e,t,r)};Pm.seq=ix});var da=R(_m=>{"use strict";var nx=sa(),ax={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,r,i){return t=Object.assign({actualString:!0},t),nx.stringifyString(e,t,r,i)}};_m.string=ax});var bs=R(Tm=>{"use strict";var Am=de(),Im={identify:e=>e==null,createNode:()=>new Am.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Am.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Im.test.test(e)?e:t.options.nullStr};Tm.nullTag=Im});var hu=R($m=>{"use strict";var ox=de(),jm={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new ox.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&jm.test.test(e)){let i=e[0]==="t"||e[0]==="T";if(t===i)return e}return t?r.options.trueStr:r.options.falseStr}};$m.boolTag=jm});var zi=R(Om=>{"use strict";function sx({format:e,minFractionDigits:t,tag:r,value:i}){if(typeof i=="bigint")return String(i);let n=typeof i=="number"?i:Number(i);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let a=Object.is(i,-0)?"-0":JSON.stringify(i);if(!e&&t&&(!r||r==="tag:yaml.org,2002:float")&&/^-?\d/.test(a)&&!a.includes("e")){let o=a.indexOf(".");o<0&&(o=a.length,a+=".");let s=t-(a.length-o-1);for(;s-- >0;)a+="0"}return a}Om.stringifyNumber=sx});var vu=R(ks=>{"use strict";var cx=de(),mu=zi(),lx={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:mu.stringifyNumber},ux={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():mu.stringifyNumber(e)}},dx={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 cx.Scalar(parseFloat(e)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:mu.stringifyNumber};ks.float=dx;ks.floatExp=ux;ks.floatNaN=lx});var wu=R(Es=>{"use strict";var Hm=zi(),Ss=e=>typeof e=="bigint"||Number.isInteger(e),gu=(e,t,r,{intAsBigInt:i})=>i?BigInt(e):parseInt(e.substring(t),r);function Dm(e,t,r){let{value:i}=e;return Ss(i)&&i>=0?r+i.toString(t):Hm.stringifyNumber(e)}var px={identify:e=>Ss(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>gu(e,2,8,r),stringify:e=>Dm(e,8,"0o")},fx={identify:Ss,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>gu(e,0,10,r),stringify:Hm.stringifyNumber},hx={identify:e=>Ss(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>gu(e,2,16,r),stringify:e=>Dm(e,16,"0x")};Es.int=fx;Es.intHex=hx;Es.intOct=px});var Fm=R(Bm=>{"use strict";var mx=Vi(),vx=bs(),gx=Wi(),wx=da(),yx=hu(),yu=vu(),Nu=wu(),Nx=[mx.map,gx.seq,wx.string,vx.nullTag,yx.boolTag,Nu.intOct,Nu.int,Nu.intHex,yu.floatNaN,yu.floatExp,yu.float];Bm.schema=Nx});var Mm=R(qm=>{"use strict";var bx=de(),kx=Vi(),Sx=Wi();function Lm(e){return typeof e=="bigint"||Number.isInteger(e)}var xs=({value:e})=>JSON.stringify(e),Ex=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:xs},{identify:e=>e==null,createNode:()=>new bx.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:xs},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:xs},{identify:Lm,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:r})=>r?BigInt(e):parseInt(e,10),stringify:({value:e})=>Lm(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:xs}],xx={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},Cx=[kx.map,Sx.seq].concat(Ex,xx);qm.schema=Cx});var ku=R(Vm=>{"use strict";var pa=Jo("buffer"),bu=de(),Rx=sa(),Px={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof pa.Buffer=="function")return pa.Buffer.from(e,"base64");if(typeof atob=="function"){let r=atob(e.replace(/[\n\r]/g,"")),i=new Uint8Array(r.length);for(let n=0;n<r.length;++n)i[n]=r.charCodeAt(n);return i}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:r},i,n,a){if(!r)return"";let o=r,s;if(typeof pa.Buffer=="function")s=o instanceof pa.Buffer?o.toString("base64"):pa.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=bu.Scalar.BLOCK_LITERAL),t!==bu.Scalar.QUOTE_DOUBLE){let c=Math.max(i.options.lineWidth-i.indent.length,i.options.minContentWidth),l=Math.ceil(s.length/c),u=new Array(l);for(let d=0,p=0;d<l;++d,p+=c)u[d]=s.substr(p,c);s=u.join(t===bu.Scalar.BLOCK_LITERAL?`
56
+ `:" ")}return Rx.stringifyString({comment:e,type:t,value:s},i,n,a)}};Vm.binary=Px});var Ps=R(Rs=>{"use strict";var Cs=W(),Su=Er(),_x=de(),Ax=Rr();function Wm(e,t){if(Cs.isSeq(e))for(let r=0;r<e.items.length;++r){let i=e.items[r];if(!Cs.isPair(i)){if(Cs.isMap(i)){i.items.length>1&&t("Each pair must have its own sequence indicator");let n=i.items[0]||new Su.Pair(new _x.Scalar(null));if(i.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${i.commentBefore}
57
57
  ${n.key.commentBefore}`:i.commentBefore),i.comment){let a=n.value??n.key;a.comment=a.comment?`${i.comment}
58
- ${a.comment}`:i.comment}i=n}e.items[r]=Es.isPair(i)?i:new Nu.Pair(i)}}else t("Expected a sequence for this tag");return e}function qm(e,t,r){let{replacer:i}=r,n=new yx.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof i=="function"&&(o=i.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(Nu.createPair(s,c,r))}return n}var Nx={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Lm,createNode:qm};xs.createPairs=qm;xs.pairs=Nx;xs.resolvePairs=Lm});var Su=R(ku=>{"use strict";var Mm=W(),bu=Nr(),pa=Cr(),bx=Rr(),Vm=Cs(),ci=class e extends bx.YAMLSeq{constructor(){super(),this.add=pa.YAMLMap.prototype.add.bind(this),this.delete=pa.YAMLMap.prototype.delete.bind(this),this.get=pa.YAMLMap.prototype.get.bind(this),this.has=pa.YAMLMap.prototype.has.bind(this),this.set=pa.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,r){if(!r)return super.toJSON(t);let i=new Map;r?.onCreate&&r.onCreate(i);for(let n of this.items){let a,o;if(Mm.isPair(n)?(a=bu.toJS(n.key,"",r),o=bu.toJS(n.value,a,r)):a=bu.toJS(n,"",r),i.has(a))throw new Error("Ordered maps must not include duplicate keys");i.set(a,o)}return i}static from(t,r,i){let n=Vm.createPairs(t,r,i),a=new this;return a.items=n.items,a}};ci.tag="tag:yaml.org,2002:omap";var kx={collection:"seq",identify:e=>e instanceof Map,nodeClass:ci,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=Vm.resolvePairs(e,t),i=[];for(let{key:n}of r.items)Mm.isScalar(n)&&(i.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new ci,r)},createNode:(e,t,r)=>ci.from(e,t,r)};ku.YAMLOMap=ci;ku.omap=kx});var Um=R(Eu=>{"use strict";var Wm=de();function zm({value:e,source:t},r){return t&&(e?Gm:Jm).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var Gm={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 Wm.Scalar(!0),stringify:zm},Jm={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 Wm.Scalar(!1),stringify:zm};Eu.falseTag=Jm;Eu.trueTag=Gm});var Km=R(Rs=>{"use strict";var Sx=de(),xu=Wi(),Ex={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:xu.stringifyNumber},xx={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():xu.stringifyNumber(e)}},Cx={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 Sx.Scalar(parseFloat(e.replace(/_/g,""))),r=e.indexOf(".");if(r!==-1){let i=e.substring(r+1).replace(/_/g,"");i[i.length-1]==="0"&&(t.minFractionDigits=i.length)}return t},stringify:xu.stringifyNumber};Rs.float=Cx;Rs.floatExp=xx;Rs.floatNaN=Ex});var Xm=R(ha=>{"use strict";var Ym=Wi(),fa=e=>typeof e=="bigint"||Number.isInteger(e);function Ps(e,t,r,{intAsBigInt:i}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),i){switch(r){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return n==="-"?BigInt(-1)*o:o}let a=parseInt(e,r);return n==="-"?-1*a:a}function Cu(e,t,r){let{value:i}=e;if(fa(i)){let n=i.toString(t);return i<0?"-"+r+n.substr(1):r+n}return Ym.stringifyNumber(e)}var Rx={identify:fa,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>Ps(e,2,2,r),stringify:e=>Cu(e,2,"0b")},Px={identify:fa,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>Ps(e,1,8,r),stringify:e=>Cu(e,8,"0")},_x={identify:fa,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>Ps(e,0,10,r),stringify:Ym.stringifyNumber},Ax={identify:fa,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>Ps(e,2,16,r),stringify:e=>Cu(e,16,"0x")};ha.int=_x;ha.intBin=Rx;ha.intHex=Ax;ha.intOct=Px});var Pu=R(Ru=>{"use strict";var Is=W(),_s=Er(),As=Cr(),li=class e extends As.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;Is.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new _s.Pair(t.key,null):r=new _s.Pair(t,null),As.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let i=As.findPair(this.items,t);return!r&&Is.isPair(i)?Is.isScalar(i.key)?i.key.value:i.key:i}set(t,r){if(typeof r!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof r}`);let i=As.findPair(this.items,t);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new _s.Pair(t))}toJSON(t,r){return super.toJSON(t,r,Set)}toString(t,r,i){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),r,i);throw new Error("Set items must all have null values")}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r))for(let o of r)typeof n=="function"&&(o=n.call(r,o,o)),a.items.push(_s.createPair(o,null,i));return a}};li.tag="tag:yaml.org,2002:set";var Ix={collection:"map",identify:e=>e instanceof Set,nodeClass:li,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>li.from(e,t,r),resolve(e,t){if(Is.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new li,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Ru.YAMLSet=li;Ru.set=Ix});var Au=R(Ts=>{"use strict";var Tx=Wi();function _u(e,t){let r=e[0],i=r==="-"||r==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=i.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return r==="-"?n(-1)*a:a}function Qm(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return Tx.stringifyNumber(e);let i="";t<0&&(i="-",t*=r(-1));let n=r(60),a=[t%n];return t<60?a.unshift(0):(t=(t-a[0])/n,a.unshift(t%n),t>=60&&(t=(t-a[0])/n,a.unshift(t))),i+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var jx={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:r})=>_u(e,r),stringify:Qm},$x={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=>_u(e,!1),stringify:Qm},Zm={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(Zm.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,i,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(r,i-1,n,a||0,o||0,s||0,c),u=t[8];if(u&&u!=="Z"){let d=_u(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$/,"")??""};Ts.floatTime=$x;Ts.intTime=jx;Ts.timestamp=Zm});var rv=R(tv=>{"use strict";var Ox=Mi(),Hx=ys(),Dx=Vi(),Bx=ua(),Fx=yu(),ev=Um(),Iu=Km(),js=Xm(),Lx=ds(),qx=Su(),Mx=Cs(),Vx=Pu(),Tu=Au(),Wx=[Ox.map,Dx.seq,Bx.string,Hx.nullTag,ev.trueTag,ev.falseTag,js.intBin,js.intOct,js.int,js.intHex,Iu.floatNaN,Iu.floatExp,Iu.float,Fx.binary,Lx.merge,qx.omap,Mx.pairs,Vx.set,Tu.intTime,Tu.floatTime,Tu.timestamp];tv.schema=Wx});var pv=R(Ou=>{"use strict";var ov=Mi(),zx=ys(),sv=Vi(),Gx=ua(),Jx=du(),ju=fu(),$u=mu(),Ux=Om(),Kx=Bm(),cv=yu(),ma=ds(),lv=Su(),uv=Cs(),iv=rv(),dv=Pu(),$s=Au(),nv=new Map([["core",Ux.schema],["failsafe",[ov.map,sv.seq,Gx.string]],["json",Kx.schema],["yaml11",iv.schema],["yaml-1.1",iv.schema]]),av={binary:cv.binary,bool:Jx.boolTag,float:ju.float,floatExp:ju.floatExp,floatNaN:ju.floatNaN,floatTime:$s.floatTime,int:$u.int,intHex:$u.intHex,intOct:$u.intOct,intTime:$s.intTime,map:ov.map,merge:ma.merge,null:zx.nullTag,omap:lv.omap,pairs:uv.pairs,seq:sv.seq,set:dv.set,timestamp:$s.timestamp},Yx={"tag:yaml.org,2002:binary":cv.binary,"tag:yaml.org,2002:merge":ma.merge,"tag:yaml.org,2002:omap":lv.omap,"tag:yaml.org,2002:pairs":uv.pairs,"tag:yaml.org,2002:set":dv.set,"tag:yaml.org,2002:timestamp":$s.timestamp};function Xx(e,t,r){let i=nv.get(t);if(i&&!e)return r&&!i.includes(ma.merge)?i.concat(ma.merge):i.slice();let n=i;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(nv.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${a} or define customTags array`)}if(Array.isArray(e))for(let a of e)n=n.concat(a);else typeof e=="function"&&(n=e(n.slice()));return r&&(n=n.concat(ma.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?av[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(av).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},[])}Ou.coreKnownTags=Yx;Ou.getTags=Xx});var Bu=R(fv=>{"use strict";var Hu=W(),Qx=Mi(),Zx=Vi(),eC=ua(),Os=pv(),tC=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Du=class e{constructor({compat:t,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Os.getTags(t,"compat"):t?Os.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Os.coreKnownTags:{},this.tags=Os.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,Hu.MAP,{value:Qx.map}),Object.defineProperty(this,Hu.SCALAR,{value:eC.string}),Object.defineProperty(this,Hu.SEQ,{value:Zx.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?tC:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};fv.Schema=Du});var mv=R(hv=>{"use strict";var rC=W(),Fu=sa(),va=ia();function iC(e,t){let r=[],i=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(r.push(c),i=!0):e.directives.docStart&&(i=!0)}i&&r.push("---");let n=Fu.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=a(e.commentBefore);r.unshift(va.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(rC.isNode(e.contents)){if(e.contents.spaceBefore&&i&&r.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);r.push(va.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Fu.stringify(e.contents,n,()=>s=null,c);s&&(l+=va.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(Fu.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
59
- `)?(r.push("..."),r.push(va.indentComment(c,""))):r.push(`... ${c}`)}else r.push("...");else{let c=e.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&r[r.length-1]!==""&&r.push(""),r.push(va.indentComment(a(c),"")))}return r.join(`
58
+ ${a.comment}`:i.comment}i=n}e.items[r]=Cs.isPair(i)?i:new Su.Pair(i)}}else t("Expected a sequence for this tag");return e}function zm(e,t,r){let{replacer:i}=r,n=new Ax.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof i=="function"&&(o=i.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(Su.createPair(s,c,r))}return n}var Ix={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Wm,createNode:zm};Rs.createPairs=zm;Rs.pairs=Ix;Rs.resolvePairs=Wm});var Cu=R(xu=>{"use strict";var Gm=W(),Eu=Nr(),fa=Cr(),Tx=Rr(),Jm=Ps(),ci=class e extends Tx.YAMLSeq{constructor(){super(),this.add=fa.YAMLMap.prototype.add.bind(this),this.delete=fa.YAMLMap.prototype.delete.bind(this),this.get=fa.YAMLMap.prototype.get.bind(this),this.has=fa.YAMLMap.prototype.has.bind(this),this.set=fa.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,r){if(!r)return super.toJSON(t);let i=new Map;r?.onCreate&&r.onCreate(i);for(let n of this.items){let a,o;if(Gm.isPair(n)?(a=Eu.toJS(n.key,"",r),o=Eu.toJS(n.value,a,r)):a=Eu.toJS(n,"",r),i.has(a))throw new Error("Ordered maps must not include duplicate keys");i.set(a,o)}return i}static from(t,r,i){let n=Jm.createPairs(t,r,i),a=new this;return a.items=n.items,a}};ci.tag="tag:yaml.org,2002:omap";var jx={collection:"seq",identify:e=>e instanceof Map,nodeClass:ci,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=Jm.resolvePairs(e,t),i=[];for(let{key:n}of r.items)Gm.isScalar(n)&&(i.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new ci,r)},createNode:(e,t,r)=>ci.from(e,t,r)};xu.YAMLOMap=ci;xu.omap=jx});var Qm=R(Ru=>{"use strict";var Um=de();function Km({value:e,source:t},r){return t&&(e?Ym:Xm).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var Ym={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 Um.Scalar(!0),stringify:Km},Xm={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 Um.Scalar(!1),stringify:Km};Ru.falseTag=Xm;Ru.trueTag=Ym});var Zm=R(_s=>{"use strict";var $x=de(),Pu=zi(),Ox={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:Pu.stringifyNumber},Hx={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():Pu.stringifyNumber(e)}},Dx={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 $x.Scalar(parseFloat(e.replace(/_/g,""))),r=e.indexOf(".");if(r!==-1){let i=e.substring(r+1).replace(/_/g,"");i[i.length-1]==="0"&&(t.minFractionDigits=i.length)}return t},stringify:Pu.stringifyNumber};_s.float=Dx;_s.floatExp=Hx;_s.floatNaN=Ox});var tv=R(ma=>{"use strict";var ev=zi(),ha=e=>typeof e=="bigint"||Number.isInteger(e);function As(e,t,r,{intAsBigInt:i}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),i){switch(r){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return n==="-"?BigInt(-1)*o:o}let a=parseInt(e,r);return n==="-"?-1*a:a}function _u(e,t,r){let{value:i}=e;if(ha(i)){let n=i.toString(t);return i<0?"-"+r+n.substr(1):r+n}return ev.stringifyNumber(e)}var Bx={identify:ha,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>As(e,2,2,r),stringify:e=>_u(e,2,"0b")},Fx={identify:ha,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>As(e,1,8,r),stringify:e=>_u(e,8,"0")},Lx={identify:ha,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>As(e,0,10,r),stringify:ev.stringifyNumber},qx={identify:ha,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>As(e,2,16,r),stringify:e=>_u(e,16,"0x")};ma.int=Lx;ma.intBin=Bx;ma.intHex=qx;ma.intOct=Fx});var Iu=R(Au=>{"use strict";var js=W(),Is=Er(),Ts=Cr(),li=class e extends Ts.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;js.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new Is.Pair(t.key,null):r=new Is.Pair(t,null),Ts.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let i=Ts.findPair(this.items,t);return!r&&js.isPair(i)?js.isScalar(i.key)?i.key.value:i.key:i}set(t,r){if(typeof r!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof r}`);let i=Ts.findPair(this.items,t);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new Is.Pair(t))}toJSON(t,r){return super.toJSON(t,r,Set)}toString(t,r,i){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),r,i);throw new Error("Set items must all have null values")}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r))for(let o of r)typeof n=="function"&&(o=n.call(r,o,o)),a.items.push(Is.createPair(o,null,i));return a}};li.tag="tag:yaml.org,2002:set";var Mx={collection:"map",identify:e=>e instanceof Set,nodeClass:li,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>li.from(e,t,r),resolve(e,t){if(js.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new li,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Au.YAMLSet=li;Au.set=Mx});var ju=R($s=>{"use strict";var Vx=zi();function Tu(e,t){let r=e[0],i=r==="-"||r==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=i.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return r==="-"?n(-1)*a:a}function rv(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return Vx.stringifyNumber(e);let i="";t<0&&(i="-",t*=r(-1));let n=r(60),a=[t%n];return t<60?a.unshift(0):(t=(t-a[0])/n,a.unshift(t%n),t>=60&&(t=(t-a[0])/n,a.unshift(t))),i+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Wx={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:r})=>Tu(e,r),stringify:rv},zx={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=>Tu(e,!1),stringify:rv},iv={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(iv.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,i,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(r,i-1,n,a||0,o||0,s||0,c),u=t[8];if(u&&u!=="Z"){let d=Tu(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$/,"")??""};$s.floatTime=zx;$s.intTime=Wx;$s.timestamp=iv});var ov=R(av=>{"use strict";var Gx=Vi(),Jx=bs(),Ux=Wi(),Kx=da(),Yx=ku(),nv=Qm(),$u=Zm(),Os=tv(),Xx=fs(),Qx=Cu(),Zx=Ps(),eC=Iu(),Ou=ju(),tC=[Gx.map,Ux.seq,Kx.string,Jx.nullTag,nv.trueTag,nv.falseTag,Os.intBin,Os.intOct,Os.int,Os.intHex,$u.floatNaN,$u.floatExp,$u.float,Yx.binary,Xx.merge,Qx.omap,Zx.pairs,eC.set,Ou.intTime,Ou.floatTime,Ou.timestamp];av.schema=tC});var vv=R(Bu=>{"use strict";var uv=Vi(),rC=bs(),dv=Wi(),iC=da(),nC=hu(),Hu=vu(),Du=wu(),aC=Fm(),oC=Mm(),pv=ku(),va=fs(),fv=Cu(),hv=Ps(),sv=ov(),mv=Iu(),Hs=ju(),cv=new Map([["core",aC.schema],["failsafe",[uv.map,dv.seq,iC.string]],["json",oC.schema],["yaml11",sv.schema],["yaml-1.1",sv.schema]]),lv={binary:pv.binary,bool:nC.boolTag,float:Hu.float,floatExp:Hu.floatExp,floatNaN:Hu.floatNaN,floatTime:Hs.floatTime,int:Du.int,intHex:Du.intHex,intOct:Du.intOct,intTime:Hs.intTime,map:uv.map,merge:va.merge,null:rC.nullTag,omap:fv.omap,pairs:hv.pairs,seq:dv.seq,set:mv.set,timestamp:Hs.timestamp},sC={"tag:yaml.org,2002:binary":pv.binary,"tag:yaml.org,2002:merge":va.merge,"tag:yaml.org,2002:omap":fv.omap,"tag:yaml.org,2002:pairs":hv.pairs,"tag:yaml.org,2002:set":mv.set,"tag:yaml.org,2002:timestamp":Hs.timestamp};function cC(e,t,r){let i=cv.get(t);if(i&&!e)return r&&!i.includes(va.merge)?i.concat(va.merge):i.slice();let n=i;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(cv.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${a} or define customTags array`)}if(Array.isArray(e))for(let a of e)n=n.concat(a);else typeof e=="function"&&(n=e(n.slice()));return r&&(n=n.concat(va.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?lv[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(lv).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},[])}Bu.coreKnownTags=sC;Bu.getTags=cC});var qu=R(gv=>{"use strict";var Fu=W(),lC=Vi(),uC=Wi(),dC=da(),Ds=vv(),pC=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Lu=class e{constructor({compat:t,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Ds.getTags(t,"compat"):t?Ds.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Ds.coreKnownTags:{},this.tags=Ds.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,Fu.MAP,{value:lC.map}),Object.defineProperty(this,Fu.SCALAR,{value:dC.string}),Object.defineProperty(this,Fu.SEQ,{value:uC.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?pC:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};gv.Schema=Lu});var yv=R(wv=>{"use strict";var fC=W(),Mu=ca(),ga=na();function hC(e,t){let r=[],i=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(r.push(c),i=!0):e.directives.docStart&&(i=!0)}i&&r.push("---");let n=Mu.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=a(e.commentBefore);r.unshift(ga.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(fC.isNode(e.contents)){if(e.contents.spaceBefore&&i&&r.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);r.push(ga.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Mu.stringify(e.contents,n,()=>s=null,c);s&&(l+=ga.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(Mu.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
59
+ `)?(r.push("..."),r.push(ga.indentComment(c,""))):r.push(`... ${c}`)}else r.push("...");else{let c=e.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&r[r.length-1]!==""&&r.push(""),r.push(ga.indentComment(a(c),"")))}return r.join(`
60
60
  `)+`
61
- `}hv.stringifyDocument=iC});var ga=R(vv=>{"use strict";var nC=ta(),zi=ts(),Xe=W(),aC=Er(),oC=Nr(),sC=Bu(),cC=mv(),Lu=Xo(),lC=Wl(),uC=ra(),qu=Vl(),Mu=class e{constructor(t,r,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Xe.NODE_TYPE,{value:Xe.DOC});let n=null;typeof r=="function"||Array.isArray(r)?n=r:i===void 0&&r&&(i=r,r=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},i);this.options=a;let{version:o}=a;i?._directives?(this.directives=i._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new qu.Directives({version:o}),this.setSchema(o,i),this.contents=t===void 0?null:this.createNode(t,n,i)}clone(){let t=Object.create(e.prototype,{[Xe.NODE_TYPE]:{value:Xe.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=Xe.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){Gi(this.contents)&&this.contents.add(t)}addIn(t,r){Gi(this.contents)&&this.contents.addIn(t,r)}createAlias(t,r){if(!t.anchor){let i=Lu.anchorNames(this);t.anchor=!r||i.has(r)?Lu.findNewAnchor(r||"a",i):r}return new nC.Alias(t.anchor)}createNode(t,r,i){let n;if(typeof r=="function")t=r.call({"":t},"",t),n=r;else if(Array.isArray(r)){let v=b=>typeof b=="number"||b instanceof String||b instanceof Number,g=r.filter(v).map(String);g.length>0&&(r=r.concat(g)),n=r}else i===void 0&&r&&(i=r,r=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:u}=i??{},{onAnchor:d,setAnchors:p,sourceObjects:f}=Lu.createNodeAnchors(this,o||"a"),m={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:f},h=uC.createNode(t,u,m);return s&&Xe.isCollection(h)&&(h.flow=!0),p(),h}createPair(t,r,i={}){let n=this.createNode(t,null,i),a=this.createNode(r,null,i);return new aC.Pair(n,a)}delete(t){return Gi(this.contents)?this.contents.delete(t):!1}deleteIn(t){return zi.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Gi(this.contents)?this.contents.deleteIn(t):!1}get(t,r){return Xe.isCollection(this.contents)?this.contents.get(t,r):void 0}getIn(t,r){return zi.isEmptyPath(t)?!r&&Xe.isScalar(this.contents)?this.contents.value:this.contents:Xe.isCollection(this.contents)?this.contents.getIn(t,r):void 0}has(t){return Xe.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return zi.isEmptyPath(t)?this.contents!==void 0:Xe.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,r){this.contents==null?this.contents=zi.collectionFromPath(this.schema,[t],r):Gi(this.contents)&&this.contents.set(t,r)}setIn(t,r){zi.isEmptyPath(t)?this.contents=r:this.contents==null?this.contents=zi.collectionFromPath(this.schema,Array.from(t),r):Gi(this.contents)&&this.contents.setIn(t,r)}setSchema(t,r={}){typeof t=="number"&&(t=String(t));let i;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new qu.Directives({version:"1.1"}),i={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new qu.Directives({version:t}),i={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,i=null;break;default:{let n=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${n}`)}}if(r.schema instanceof Object)this.schema=r.schema;else if(i)this.schema=new sC.Schema(Object.assign(i,r));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:r,mapAsMap:i,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=oC.toJS(this.contents,r??"",s);if(typeof a=="function")for(let{count:l,res:u}of s.anchors.values())a(u,l);return typeof o=="function"?lC.applyReviver(o,{"":c},"",c):c}toJSON(t,r){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:r})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let r=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${r}`)}return cC.stringifyDocument(this,t)}};function Gi(e){if(Xe.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}vv.Document=Mu});var Na=R(ya=>{"use strict";var wa=class extends Error{constructor(t,r,i,n){super(),this.name=t,this.code=i,this.message=n,this.pos=r}},Vu=class extends wa{constructor(t,r,i){super("YAMLParseError",t,r,i)}},Wu=class extends wa{constructor(t,r,i){super("YAMLWarning",t,r,i)}},dC=(e,t)=>r=>{if(r.pos[0]===-1)return;r.linePos=r.pos.map(s=>t.linePos(s));let{line:i,col:n}=r.linePos[0];r.message+=` at line ${i}, column ${n}`;let a=n-1,o=e.substring(t.lineStarts[i-1],t.lineStarts[i]).replace(/[\n\r]+$/,"");if(a>=60&&o.length>80){let s=Math.min(a-39,o.length-79);o="…"+o.substring(s),a-=s-1}if(o.length>80&&(o=o.substring(0,79)+"…"),i>1&&/^ *$/.test(o.substring(0,a))){let s=e.substring(t.lineStarts[i-2],t.lineStarts[i-1]);s.length>80&&(s=s.substring(0,79)+`…
61
+ `}wv.stringifyDocument=hC});var wa=R(Nv=>{"use strict";var mC=ra(),Gi=is(),Xe=W(),vC=Er(),gC=Nr(),wC=qu(),yC=yv(),Vu=Zo(),NC=Jl(),bC=ia(),Wu=Gl(),zu=class e{constructor(t,r,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Xe.NODE_TYPE,{value:Xe.DOC});let n=null;typeof r=="function"||Array.isArray(r)?n=r:i===void 0&&r&&(i=r,r=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},i);this.options=a;let{version:o}=a;i?._directives?(this.directives=i._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new Wu.Directives({version:o}),this.setSchema(o,i),this.contents=t===void 0?null:this.createNode(t,n,i)}clone(){let t=Object.create(e.prototype,{[Xe.NODE_TYPE]:{value:Xe.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=Xe.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){Ji(this.contents)&&this.contents.add(t)}addIn(t,r){Ji(this.contents)&&this.contents.addIn(t,r)}createAlias(t,r){if(!t.anchor){let i=Vu.anchorNames(this);t.anchor=!r||i.has(r)?Vu.findNewAnchor(r||"a",i):r}return new mC.Alias(t.anchor)}createNode(t,r,i){let n;if(typeof r=="function")t=r.call({"":t},"",t),n=r;else if(Array.isArray(r)){let v=b=>typeof b=="number"||b instanceof String||b instanceof Number,g=r.filter(v).map(String);g.length>0&&(r=r.concat(g)),n=r}else i===void 0&&r&&(i=r,r=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:u}=i??{},{onAnchor:d,setAnchors:p,sourceObjects:f}=Vu.createNodeAnchors(this,o||"a"),m={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:f},h=bC.createNode(t,u,m);return s&&Xe.isCollection(h)&&(h.flow=!0),p(),h}createPair(t,r,i={}){let n=this.createNode(t,null,i),a=this.createNode(r,null,i);return new vC.Pair(n,a)}delete(t){return Ji(this.contents)?this.contents.delete(t):!1}deleteIn(t){return Gi.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Ji(this.contents)?this.contents.deleteIn(t):!1}get(t,r){return Xe.isCollection(this.contents)?this.contents.get(t,r):void 0}getIn(t,r){return Gi.isEmptyPath(t)?!r&&Xe.isScalar(this.contents)?this.contents.value:this.contents:Xe.isCollection(this.contents)?this.contents.getIn(t,r):void 0}has(t){return Xe.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return Gi.isEmptyPath(t)?this.contents!==void 0:Xe.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,r){this.contents==null?this.contents=Gi.collectionFromPath(this.schema,[t],r):Ji(this.contents)&&this.contents.set(t,r)}setIn(t,r){Gi.isEmptyPath(t)?this.contents=r:this.contents==null?this.contents=Gi.collectionFromPath(this.schema,Array.from(t),r):Ji(this.contents)&&this.contents.setIn(t,r)}setSchema(t,r={}){typeof t=="number"&&(t=String(t));let i;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Wu.Directives({version:"1.1"}),i={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new Wu.Directives({version:t}),i={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,i=null;break;default:{let n=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${n}`)}}if(r.schema instanceof Object)this.schema=r.schema;else if(i)this.schema=new wC.Schema(Object.assign(i,r));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:r,mapAsMap:i,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=gC.toJS(this.contents,r??"",s);if(typeof a=="function")for(let{count:l,res:u}of s.anchors.values())a(u,l);return typeof o=="function"?NC.applyReviver(o,{"":c},"",c):c}toJSON(t,r){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:r})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let r=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${r}`)}return yC.stringifyDocument(this,t)}};function Ji(e){if(Xe.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Nv.Document=zu});var ba=R(Na=>{"use strict";var ya=class extends Error{constructor(t,r,i,n){super(),this.name=t,this.code=i,this.message=n,this.pos=r}},Gu=class extends ya{constructor(t,r,i){super("YAMLParseError",t,r,i)}},Ju=class extends ya{constructor(t,r,i){super("YAMLWarning",t,r,i)}},kC=(e,t)=>r=>{if(r.pos[0]===-1)return;r.linePos=r.pos.map(s=>t.linePos(s));let{line:i,col:n}=r.linePos[0];r.message+=` at line ${i}, column ${n}`;let a=n-1,o=e.substring(t.lineStarts[i-1],t.lineStarts[i]).replace(/[\n\r]+$/,"");if(a>=60&&o.length>80){let s=Math.min(a-39,o.length-79);o="…"+o.substring(s),a-=s-1}if(o.length>80&&(o=o.substring(0,79)+"…"),i>1&&/^ *$/.test(o.substring(0,a))){let s=e.substring(t.lineStarts[i-2],t.lineStarts[i-1]);s.length>80&&(s=s.substring(0,79)+`…
62
62
  `),o=s+o}if(/[^ ]/.test(o)){let s=1,c=r.linePos[1];c?.line===i&&c.col>n&&(s=Math.max(1,Math.min(c.col-n,80-a)));let l=" ".repeat(a)+"^".repeat(s);r.message+=`:
63
63
 
64
64
  ${o}
65
65
  ${l}
66
- `}};ya.YAMLError=wa;ya.YAMLParseError=Vu;ya.YAMLWarning=Wu;ya.prettifyError=dC});var ba=R(gv=>{"use strict";function pC(e,{flow:t,indicator:r,next:i,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d="",p="",f=!1,m=!1,h=null,v=null,g=null,b=null,k=null,N=null,x=null;for(let E of e)switch(m&&(E.type!=="space"&&E.type!=="newline"&&E.type!=="comma"&&a(E.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),h&&(l&&E.type!=="comment"&&E.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),E.type){case"space":!t&&(r!=="doc-start"||i?.type!=="flow-collection")&&E.source.includes(" ")&&(h=E),u=!0;break;case"comment":{u||a(E,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let y=E.source.substring(1)||" ";d?d+=p+y:d=y,p="",l=!1;break}case"newline":l?d?d+=E.source:(!N||r!=="seq-item-ind")&&(c=!0):p+=E.source,l=!0,f=!0,(v||g)&&(b=E),u=!0;break;case"anchor":v&&a(E,"MULTIPLE_ANCHORS","A node can have at most one anchor"),E.source.endsWith(":")&&a(E.offset+E.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),v=E,x??(x=E.offset),l=!1,u=!1,m=!0;break;case"tag":{g&&a(E,"MULTIPLE_TAGS","A node can have at most one tag"),g=E,x??(x=E.offset),l=!1,u=!1,m=!0;break}case r:(v||g)&&a(E,"BAD_PROP_ORDER",`Anchors and tags must be after the ${E.source} indicator`),N&&a(E,"UNEXPECTED_TOKEN",`Unexpected ${E.source} in ${t??"collection"}`),N=E,l=r==="seq-item-ind"||r==="explicit-key-ind",u=!1;break;case"comma":if(t){k&&a(E,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),k=E,l=!1,u=!1;break}default:a(E,"UNEXPECTED_TOKEN",`Unexpected ${E.type} token`),l=!1,u=!1}let w=e[e.length-1],S=w?w.offset+w.source.length:n;return m&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&a(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:k,found:N,spaceBefore:c,comment:d,hasNewline:f,anchor:v,tag:g,newlineAfterProp:b,end:S,start:x??S}}gv.resolveProps=pC});var Hs=R(wv=>{"use strict";function zu(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
67
- `))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let r of t.start)if(r.type==="newline")return!0;if(t.sep){for(let r of t.sep)if(r.type==="newline")return!0}if(zu(t.key)||zu(t.value))return!0}return!1;default:return!0}}wv.containsNewline=zu});var Gu=R(yv=>{"use strict";var fC=Hs();function hC(e,t,r){if(t?.type==="flow-collection"){let i=t.end[0];i.indent===e&&(i.source==="]"||i.source==="}")&&fC.containsNewline(t)&&r(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}yv.flowIndentCheck=hC});var Ju=R(bv=>{"use strict";var Nv=W();function mC(e,t,r){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let n=typeof i=="function"?i:(a,o)=>a===o||Nv.isScalar(a)&&Nv.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,r))}bv.mapIncludes=mC});var Rv=R(Cv=>{"use strict";var kv=Er(),vC=Cr(),Sv=ba(),gC=Hs(),Ev=Gu(),wC=Ju(),xv="All mapping items must start at the same column";function yC({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??vC.YAMLMap,s=new o(r.schema);r.atRoot&&(r.atRoot=!1);let c=i.offset,l=null;for(let u of i.items){let{start:d,key:p,sep:f,value:m}=u,h=Sv.resolveProps(d,{indicator:"explicit-key-ind",next:p??f?.[0],offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0}),v=!h.found;if(v){if(p&&(p.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in p&&p.indent!==i.indent&&n(c,"BAD_INDENT",xv)),!h.anchor&&!h.tag&&!f){l=h.end,h.comment&&(s.comment?s.comment+=`
68
- `+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||gC.containsNewline(p))&&n(p??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==i.indent&&n(c,"BAD_INDENT",xv);r.atKey=!0;let g=h.end,b=p?e(r,p,h,n):t(r,g,d,null,h,n);r.schema.compat&&Ev.flowIndentCheck(i.indent,p,n),r.atKey=!1,wC.mapIncludes(r,s.items,b)&&n(g,"DUPLICATE_KEY","Map keys must be unique");let k=Sv.resolveProps(f??[],{indicator:"map-value-ind",next:m,offset:b.range[2],onError:n,parentIndent:i.indent,startOnNewline:!p||p.type==="block-scalar"});if(c=k.end,k.found){v&&(m?.type==="block-map"&&!k.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&h.start<k.found.offset-1024&&n(b.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let N=m?e(r,m,k,n):t(r,c,f,null,k,n);r.schema.compat&&Ev.flowIndentCheck(i.indent,m,n),c=N.range[2];let x=new kv.Pair(b,N);r.options.keepSourceTokens&&(x.srcToken=u),s.items.push(x)}else{v&&n(b.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),k.comment&&(b.comment?b.comment+=`
69
- `+k.comment:b.comment=k.comment);let N=new kv.Pair(b);r.options.keepSourceTokens&&(N.srcToken=u),s.items.push(N)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[i.offset,c,l??c],s}Cv.resolveBlockMap=yC});var _v=R(Pv=>{"use strict";var NC=Rr(),bC=ba(),kC=Gu();function SC({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??NC.YAMLSeq,s=new o(r.schema);r.atRoot&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let c=i.offset,l=null;for(let{start:u,value:d}of i.items){let p=bC.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0});if(!p.found)if(p.anchor||p.tag||d)d?.type==="block-seq"?n(p.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=p.end,p.comment&&(s.comment=p.comment);continue}let f=d?e(r,d,p,n):t(r,p.end,u,null,p,n);r.schema.compat&&kC.flowIndentCheck(i.indent,d,n),c=f.range[2],s.items.push(f)}return s.range=[i.offset,c,l??c],s}Pv.resolveBlockSeq=SC});var Ji=R(Av=>{"use strict";function EC(e,t,r,i){let n="";if(e){let a=!1,o="";for(let s of e){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{r&&!a&&i(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";n?n+=o+u:n=u,o="";break}case"newline":n&&(o+=c),a=!0;break;default:i(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:n,offset:t}}Av.resolveEnd=EC});var $v=R(jv=>{"use strict";var xC=W(),CC=Er(),Iv=Cr(),RC=Rr(),PC=Ji(),Tv=ba(),_C=Hs(),AC=Ju(),Uu="Block collections are not allowed within flow collections",Ku=e=>e&&(e.type==="block-map"||e.type==="block-seq");function IC({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=i.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Iv.YAMLMap:RC.YAMLSeq),l=new c(r.schema);l.flow=!0;let u=r.atRoot;u&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let d=i.offset+i.start.source.length;for(let v=0;v<i.items.length;++v){let g=i.items[v],{start:b,key:k,sep:N,value:x}=g,w=Tv.resolveProps(b,{flow:s,indicator:"explicit-key-ind",next:k??N?.[0],offset:d,onError:n,parentIndent:i.indent,startOnNewline:!1});if(!w.found){if(!w.anchor&&!w.tag&&!N&&!x){v===0&&w.comma?n(w.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):v<i.items.length-1&&n(w.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),w.comment&&(l.comment?l.comment+=`
70
- `+w.comment:l.comment=w.comment),d=w.end;continue}!o&&r.options.strict&&_C.containsNewline(k)&&n(k,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(v===0)w.comma&&n(w.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(w.comma||n(w.start,"MISSING_CHAR",`Missing , between ${s} items`),w.comment){let S="";e:for(let E of b)switch(E.type){case"comma":case"space":break;case"comment":S=E.source.substring(1);break e;default:break e}if(S){let E=l.items[l.items.length-1];xC.isPair(E)&&(E=E.value??E.key),E.comment?E.comment+=`
71
- `+S:E.comment=S,w.comment=w.comment.substring(S.length+1)}}if(!o&&!N&&!w.found){let S=x?e(r,x,w,n):t(r,w.end,N,null,w,n);l.items.push(S),d=S.range[2],Ku(x)&&n(S.range,"BLOCK_IN_FLOW",Uu)}else{r.atKey=!0;let S=w.end,E=k?e(r,k,w,n):t(r,S,b,null,w,n);Ku(k)&&n(E.range,"BLOCK_IN_FLOW",Uu),r.atKey=!1;let y=Tv.resolveProps(N??[],{flow:s,indicator:"map-value-ind",next:x,offset:E.range[2],onError:n,parentIndent:i.indent,startOnNewline:!1});if(y.found){if(!o&&!w.found&&r.options.strict){if(N)for(let j of N){if(j===y.found)break;if(j.type==="newline"){n(j,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}w.start<y.found.offset-1024&&n(y.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else x&&("source"in x&&x.source?.[0]===":"?n(x,"MISSING_CHAR",`Missing space after : in ${s}`):n(y.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let C=x?e(r,x,y,n):y.found?t(r,y.end,N,null,y,n):null;C?Ku(x)&&n(C.range,"BLOCK_IN_FLOW",Uu):y.comment&&(E.comment?E.comment+=`
72
- `+y.comment:E.comment=y.comment);let O=new CC.Pair(E,C);if(r.options.keepSourceTokens&&(O.srcToken=g),o){let j=l;AC.mapIncludes(r,j.items,E)&&n(S,"DUPLICATE_KEY","Map keys must be unique"),j.items.push(O)}else{let j=new Iv.YAMLMap(r.schema);j.flow=!0,j.items.push(O);let Q=(C??E).range;j.range=[E.range[0],Q[1],Q[2]],l.items.push(j)}d=C?C.range[2]:y.end}}let p=o?"}":"]",[f,...m]=i.end,h=d;if(f?.source===p)h=f.offset+f.source.length;else{let v=s[0].toUpperCase()+s.substring(1),g=u?`${v} must end with a ${p}`:`${v} in block collection must be sufficiently indented and end with a ${p}`;n(d,u?"MISSING_CHAR":"BAD_INDENT",g),f&&f.source.length!==1&&m.unshift(f)}if(m.length>0){let v=PC.resolveEnd(m,h,r.options.strict,n);v.comment&&(l.comment?l.comment+=`
73
- `+v.comment:l.comment=v.comment),l.range=[i.offset,h,v.offset]}else l.range=[i.offset,h,h];return l}jv.resolveFlowCollection=IC});var Hv=R(Ov=>{"use strict";var TC=W(),jC=de(),$C=Cr(),OC=Rr(),HC=Rv(),DC=_v(),BC=$v();function Yu(e,t,r,i,n,a){let o=r.type==="block-map"?HC.resolveBlockMap(e,t,r,i,a):r.type==="block-seq"?DC.resolveBlockSeq(e,t,r,i,a):BC.resolveFlowCollection(e,t,r,i,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function FC(e,t,r,i,n){let a=i.tag,o=a?t.directives.tagName(a.source,p=>n(a,"TAG_RESOLVE_FAILED",p)):null;if(r.type==="block-seq"){let{anchor:p,newlineAfterProp:f}=i,m=p&&a?p.offset>a.offset?p:a:p??a;m&&(!f||f.offset<m.offset)&&n(m,"MISSING_CHAR","Missing newline after block sequence props")}let s=r.type==="block-map"?"map":r.type==="block-seq"?"seq":r.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===$C.YAMLMap.tagName&&s==="map"||o===OC.YAMLSeq.tagName&&s==="seq")return Yu(e,t,r,n,o);let c=t.schema.tags.find(p=>p.tag===o&&p.collection===s);if(!c){let p=t.schema.knownTags[o];if(p?.collection===s)t.schema.tags.push(Object.assign({},p,{default:!1})),c=p;else return p?n(a,"BAD_COLLECTION_TYPE",`${p.tag} used for ${s} collection, but expects ${p.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Yu(e,t,r,n,o)}let l=Yu(e,t,r,n,o,c),u=c.resolve?.(l,p=>n(a,"TAG_RESOLVE_FAILED",p),t.options)??l,d=TC.isNode(u)?u:new jC.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}Ov.composeCollection=FC});var Qu=R(Dv=>{"use strict";var Xu=de();function LC(e,t,r){let i=t.offset,n=qC(t,e.options.strict,r);if(!n)return{value:"",type:null,comment:"",range:[i,i,i]};let a=n.mode===">"?Xu.Scalar.BLOCK_FOLDED:Xu.Scalar.BLOCK_LITERAL,o=t.source?MC(t.source):[],s=o.length;for(let h=o.length-1;h>=0;--h){let v=o[h][1];if(v===""||v==="\r")s=h;else break}if(s===0){let h=n.chomp==="+"&&o.length>0?`
66
+ `}};Na.YAMLError=ya;Na.YAMLParseError=Gu;Na.YAMLWarning=Ju;Na.prettifyError=kC});var ka=R(bv=>{"use strict";function SC(e,{flow:t,indicator:r,next:i,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d="",p="",f=!1,m=!1,h=null,v=null,g=null,b=null,k=null,N=null,x=null;for(let E of e)switch(m&&(E.type!=="space"&&E.type!=="newline"&&E.type!=="comma"&&a(E.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),h&&(l&&E.type!=="comment"&&E.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),E.type){case"space":!t&&(r!=="doc-start"||i?.type!=="flow-collection")&&E.source.includes(" ")&&(h=E),u=!0;break;case"comment":{u||a(E,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let y=E.source.substring(1)||" ";d?d+=p+y:d=y,p="",l=!1;break}case"newline":l?d?d+=E.source:(!N||r!=="seq-item-ind")&&(c=!0):p+=E.source,l=!0,f=!0,(v||g)&&(b=E),u=!0;break;case"anchor":v&&a(E,"MULTIPLE_ANCHORS","A node can have at most one anchor"),E.source.endsWith(":")&&a(E.offset+E.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),v=E,x??(x=E.offset),l=!1,u=!1,m=!0;break;case"tag":{g&&a(E,"MULTIPLE_TAGS","A node can have at most one tag"),g=E,x??(x=E.offset),l=!1,u=!1,m=!0;break}case r:(v||g)&&a(E,"BAD_PROP_ORDER",`Anchors and tags must be after the ${E.source} indicator`),N&&a(E,"UNEXPECTED_TOKEN",`Unexpected ${E.source} in ${t??"collection"}`),N=E,l=r==="seq-item-ind"||r==="explicit-key-ind",u=!1;break;case"comma":if(t){k&&a(E,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),k=E,l=!1,u=!1;break}default:a(E,"UNEXPECTED_TOKEN",`Unexpected ${E.type} token`),l=!1,u=!1}let w=e[e.length-1],S=w?w.offset+w.source.length:n;return m&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&a(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:k,found:N,spaceBefore:c,comment:d,hasNewline:f,anchor:v,tag:g,newlineAfterProp:b,end:S,start:x??S}}bv.resolveProps=SC});var Bs=R(kv=>{"use strict";function Uu(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
67
+ `))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let r of t.start)if(r.type==="newline")return!0;if(t.sep){for(let r of t.sep)if(r.type==="newline")return!0}if(Uu(t.key)||Uu(t.value))return!0}return!1;default:return!0}}kv.containsNewline=Uu});var Ku=R(Sv=>{"use strict";var EC=Bs();function xC(e,t,r){if(t?.type==="flow-collection"){let i=t.end[0];i.indent===e&&(i.source==="]"||i.source==="}")&&EC.containsNewline(t)&&r(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Sv.flowIndentCheck=xC});var Yu=R(xv=>{"use strict";var Ev=W();function CC(e,t,r){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let n=typeof i=="function"?i:(a,o)=>a===o||Ev.isScalar(a)&&Ev.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,r))}xv.mapIncludes=CC});var Iv=R(Av=>{"use strict";var Cv=Er(),RC=Cr(),Rv=ka(),PC=Bs(),Pv=Ku(),_C=Yu(),_v="All mapping items must start at the same column";function AC({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??RC.YAMLMap,s=new o(r.schema);r.atRoot&&(r.atRoot=!1);let c=i.offset,l=null;for(let u of i.items){let{start:d,key:p,sep:f,value:m}=u,h=Rv.resolveProps(d,{indicator:"explicit-key-ind",next:p??f?.[0],offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0}),v=!h.found;if(v){if(p&&(p.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in p&&p.indent!==i.indent&&n(c,"BAD_INDENT",_v)),!h.anchor&&!h.tag&&!f){l=h.end,h.comment&&(s.comment?s.comment+=`
68
+ `+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||PC.containsNewline(p))&&n(p??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==i.indent&&n(c,"BAD_INDENT",_v);r.atKey=!0;let g=h.end,b=p?e(r,p,h,n):t(r,g,d,null,h,n);r.schema.compat&&Pv.flowIndentCheck(i.indent,p,n),r.atKey=!1,_C.mapIncludes(r,s.items,b)&&n(g,"DUPLICATE_KEY","Map keys must be unique");let k=Rv.resolveProps(f??[],{indicator:"map-value-ind",next:m,offset:b.range[2],onError:n,parentIndent:i.indent,startOnNewline:!p||p.type==="block-scalar"});if(c=k.end,k.found){v&&(m?.type==="block-map"&&!k.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&h.start<k.found.offset-1024&&n(b.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let N=m?e(r,m,k,n):t(r,c,f,null,k,n);r.schema.compat&&Pv.flowIndentCheck(i.indent,m,n),c=N.range[2];let x=new Cv.Pair(b,N);r.options.keepSourceTokens&&(x.srcToken=u),s.items.push(x)}else{v&&n(b.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),k.comment&&(b.comment?b.comment+=`
69
+ `+k.comment:b.comment=k.comment);let N=new Cv.Pair(b);r.options.keepSourceTokens&&(N.srcToken=u),s.items.push(N)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[i.offset,c,l??c],s}Av.resolveBlockMap=AC});var jv=R(Tv=>{"use strict";var IC=Rr(),TC=ka(),jC=Ku();function $C({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??IC.YAMLSeq,s=new o(r.schema);r.atRoot&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let c=i.offset,l=null;for(let{start:u,value:d}of i.items){let p=TC.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0});if(!p.found)if(p.anchor||p.tag||d)d?.type==="block-seq"?n(p.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=p.end,p.comment&&(s.comment=p.comment);continue}let f=d?e(r,d,p,n):t(r,p.end,u,null,p,n);r.schema.compat&&jC.flowIndentCheck(i.indent,d,n),c=f.range[2],s.items.push(f)}return s.range=[i.offset,c,l??c],s}Tv.resolveBlockSeq=$C});var Ui=R($v=>{"use strict";function OC(e,t,r,i){let n="";if(e){let a=!1,o="";for(let s of e){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{r&&!a&&i(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";n?n+=o+u:n=u,o="";break}case"newline":n&&(o+=c),a=!0;break;default:i(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:n,offset:t}}$v.resolveEnd=OC});var Bv=R(Dv=>{"use strict";var HC=W(),DC=Er(),Ov=Cr(),BC=Rr(),FC=Ui(),Hv=ka(),LC=Bs(),qC=Yu(),Xu="Block collections are not allowed within flow collections",Qu=e=>e&&(e.type==="block-map"||e.type==="block-seq");function MC({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=i.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Ov.YAMLMap:BC.YAMLSeq),l=new c(r.schema);l.flow=!0;let u=r.atRoot;u&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let d=i.offset+i.start.source.length;for(let v=0;v<i.items.length;++v){let g=i.items[v],{start:b,key:k,sep:N,value:x}=g,w=Hv.resolveProps(b,{flow:s,indicator:"explicit-key-ind",next:k??N?.[0],offset:d,onError:n,parentIndent:i.indent,startOnNewline:!1});if(!w.found){if(!w.anchor&&!w.tag&&!N&&!x){v===0&&w.comma?n(w.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):v<i.items.length-1&&n(w.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),w.comment&&(l.comment?l.comment+=`
70
+ `+w.comment:l.comment=w.comment),d=w.end;continue}!o&&r.options.strict&&LC.containsNewline(k)&&n(k,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(v===0)w.comma&&n(w.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(w.comma||n(w.start,"MISSING_CHAR",`Missing , between ${s} items`),w.comment){let S="";e:for(let E of b)switch(E.type){case"comma":case"space":break;case"comment":S=E.source.substring(1);break e;default:break e}if(S){let E=l.items[l.items.length-1];HC.isPair(E)&&(E=E.value??E.key),E.comment?E.comment+=`
71
+ `+S:E.comment=S,w.comment=w.comment.substring(S.length+1)}}if(!o&&!N&&!w.found){let S=x?e(r,x,w,n):t(r,w.end,N,null,w,n);l.items.push(S),d=S.range[2],Qu(x)&&n(S.range,"BLOCK_IN_FLOW",Xu)}else{r.atKey=!0;let S=w.end,E=k?e(r,k,w,n):t(r,S,b,null,w,n);Qu(k)&&n(E.range,"BLOCK_IN_FLOW",Xu),r.atKey=!1;let y=Hv.resolveProps(N??[],{flow:s,indicator:"map-value-ind",next:x,offset:E.range[2],onError:n,parentIndent:i.indent,startOnNewline:!1});if(y.found){if(!o&&!w.found&&r.options.strict){if(N)for(let j of N){if(j===y.found)break;if(j.type==="newline"){n(j,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}w.start<y.found.offset-1024&&n(y.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else x&&("source"in x&&x.source?.[0]===":"?n(x,"MISSING_CHAR",`Missing space after : in ${s}`):n(y.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let C=x?e(r,x,y,n):y.found?t(r,y.end,N,null,y,n):null;C?Qu(x)&&n(C.range,"BLOCK_IN_FLOW",Xu):y.comment&&(E.comment?E.comment+=`
72
+ `+y.comment:E.comment=y.comment);let O=new DC.Pair(E,C);if(r.options.keepSourceTokens&&(O.srcToken=g),o){let j=l;qC.mapIncludes(r,j.items,E)&&n(S,"DUPLICATE_KEY","Map keys must be unique"),j.items.push(O)}else{let j=new Ov.YAMLMap(r.schema);j.flow=!0,j.items.push(O);let Q=(C??E).range;j.range=[E.range[0],Q[1],Q[2]],l.items.push(j)}d=C?C.range[2]:y.end}}let p=o?"}":"]",[f,...m]=i.end,h=d;if(f?.source===p)h=f.offset+f.source.length;else{let v=s[0].toUpperCase()+s.substring(1),g=u?`${v} must end with a ${p}`:`${v} in block collection must be sufficiently indented and end with a ${p}`;n(d,u?"MISSING_CHAR":"BAD_INDENT",g),f&&f.source.length!==1&&m.unshift(f)}if(m.length>0){let v=FC.resolveEnd(m,h,r.options.strict,n);v.comment&&(l.comment?l.comment+=`
73
+ `+v.comment:l.comment=v.comment),l.range=[i.offset,h,v.offset]}else l.range=[i.offset,h,h];return l}Dv.resolveFlowCollection=MC});var Lv=R(Fv=>{"use strict";var VC=W(),WC=de(),zC=Cr(),GC=Rr(),JC=Iv(),UC=jv(),KC=Bv();function Zu(e,t,r,i,n,a){let o=r.type==="block-map"?JC.resolveBlockMap(e,t,r,i,a):r.type==="block-seq"?UC.resolveBlockSeq(e,t,r,i,a):KC.resolveFlowCollection(e,t,r,i,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function YC(e,t,r,i,n){let a=i.tag,o=a?t.directives.tagName(a.source,p=>n(a,"TAG_RESOLVE_FAILED",p)):null;if(r.type==="block-seq"){let{anchor:p,newlineAfterProp:f}=i,m=p&&a?p.offset>a.offset?p:a:p??a;m&&(!f||f.offset<m.offset)&&n(m,"MISSING_CHAR","Missing newline after block sequence props")}let s=r.type==="block-map"?"map":r.type==="block-seq"?"seq":r.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===zC.YAMLMap.tagName&&s==="map"||o===GC.YAMLSeq.tagName&&s==="seq")return Zu(e,t,r,n,o);let c=t.schema.tags.find(p=>p.tag===o&&p.collection===s);if(!c){let p=t.schema.knownTags[o];if(p?.collection===s)t.schema.tags.push(Object.assign({},p,{default:!1})),c=p;else return p?n(a,"BAD_COLLECTION_TYPE",`${p.tag} used for ${s} collection, but expects ${p.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Zu(e,t,r,n,o)}let l=Zu(e,t,r,n,o,c),u=c.resolve?.(l,p=>n(a,"TAG_RESOLVE_FAILED",p),t.options)??l,d=VC.isNode(u)?u:new WC.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}Fv.composeCollection=YC});var td=R(qv=>{"use strict";var ed=de();function XC(e,t,r){let i=t.offset,n=QC(t,e.options.strict,r);if(!n)return{value:"",type:null,comment:"",range:[i,i,i]};let a=n.mode===">"?ed.Scalar.BLOCK_FOLDED:ed.Scalar.BLOCK_LITERAL,o=t.source?ZC(t.source):[],s=o.length;for(let h=o.length-1;h>=0;--h){let v=o[h][1];if(v===""||v==="\r")s=h;else break}if(s===0){let h=n.chomp==="+"&&o.length>0?`
74
74
  `.repeat(Math.max(1,o.length-1)):"",v=i+n.length;return t.source&&(v+=t.source.length),{value:h,type:a,comment:n.comment,range:[i,v,v]}}let c=t.indent+n.indent,l=t.offset+n.length,u=0;for(let h=0;h<s;++h){let[v,g]=o[h];if(g===""||g==="\r")n.indent===0&&v.length>c&&(c=v.length);else{v.length<c&&r(l+v.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(c=v.length),u=h,c===0&&!e.atRoot&&r(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=v.length+g.length+1}for(let h=o.length-1;h>=s;--h)o[h][0].length>c&&(s=h+1);let d="",p="",f=!1;for(let h=0;h<u;++h)d+=o[h][0].slice(c)+`
75
- `;for(let h=u;h<s;++h){let[v,g]=o[h];l+=v.length+g.length+1;let b=g[g.length-1]==="\r";if(b&&(g=g.slice(0,-1)),g&&v.length<c){let N=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;r(l-g.length-(b?2:1),"BAD_INDENT",N),v=""}a===Xu.Scalar.BLOCK_LITERAL?(d+=p+v.slice(c)+g,p=`
75
+ `;for(let h=u;h<s;++h){let[v,g]=o[h];l+=v.length+g.length+1;let b=g[g.length-1]==="\r";if(b&&(g=g.slice(0,-1)),g&&v.length<c){let N=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;r(l-g.length-(b?2:1),"BAD_INDENT",N),v=""}a===ed.Scalar.BLOCK_LITERAL?(d+=p+v.slice(c)+g,p=`
76
76
  `):v.length>c||g[0]===" "?(p===" "?p=`
77
77
  `:!f&&p===`
78
78
  `&&(p=`
@@ -85,65 +85,69 @@ ${l}
85
85
  `+o[h][0].slice(c);d[d.length-1]!==`
86
86
  `&&(d+=`
87
87
  `);break;default:d+=`
88
- `}let m=i+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[i,m,m]}}function qC({offset:e,props:t},r,i){if(t[0].type!=="block-scalar-header")return i(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",c=-1;for(let p=1;p<n.length;++p){let f=n[p];if(!s&&(f==="-"||f==="+"))s=f;else{let m=Number(f);!o&&m?o=m:c===-1&&(c=e+p)}}c!==-1&&i(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,u="",d=n.length;for(let p=1;p<t.length;++p){let f=t[p];switch(f.type){case"space":l=!0;case"newline":d+=f.source.length;break;case"comment":r&&!l&&i(f,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=f.source.length,u=f.source.substring(1);break;case"error":i(f,"UNEXPECTED_TOKEN",f.message),d+=f.source.length;break;default:{let m=`Unexpected token in block scalar header: ${f.type}`;i(f,"UNEXPECTED_TOKEN",m);let h=f.source;h&&typeof h=="string"&&(d+=h.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function MC(e){let t=e.split(/\n( *)/),r=t[0],i=r.match(/^( *)/),a=[i?.[1]?[i[1],r.slice(i[1].length)]:["",r]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}Dv.resolveBlockScalar=LC});var ed=R(Fv=>{"use strict";var Zu=de(),VC=Ji();function WC(e,t,r){let{offset:i,type:n,source:a,end:o}=e,s,c,l=(p,f,m)=>r(i+p,f,m);switch(n){case"scalar":s=Zu.Scalar.PLAIN,c=zC(a,l);break;case"single-quoted-scalar":s=Zu.Scalar.QUOTE_SINGLE,c=GC(a,l);break;case"double-quoted-scalar":s=Zu.Scalar.QUOTE_DOUBLE,c=JC(a,l);break;default:return r(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[i,i+a.length,i+a.length]}}let u=i+a.length,d=VC.resolveEnd(o,u,t,r);return{value:c,type:s,comment:d.comment,range:[i,u,d.offset]}}function zC(e,t){let r="";switch(e[0]){case" ":r="a tab character";break;case",":r="flow indicator character ,";break;case"%":r="directive indicator character %";break;case"|":case">":{r=`block scalar indicator ${e[0]}`;break}case"@":case"`":{r=`reserved character ${e[0]}`;break}}return r&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${r}`),Bv(e)}function GC(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Bv(e.slice(1,-1)).replace(/''/g,"'")}function Bv(e){let t,r;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
88
+ `}let m=i+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[i,m,m]}}function QC({offset:e,props:t},r,i){if(t[0].type!=="block-scalar-header")return i(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",c=-1;for(let p=1;p<n.length;++p){let f=n[p];if(!s&&(f==="-"||f==="+"))s=f;else{let m=Number(f);!o&&m?o=m:c===-1&&(c=e+p)}}c!==-1&&i(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,u="",d=n.length;for(let p=1;p<t.length;++p){let f=t[p];switch(f.type){case"space":l=!0;case"newline":d+=f.source.length;break;case"comment":r&&!l&&i(f,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=f.source.length,u=f.source.substring(1);break;case"error":i(f,"UNEXPECTED_TOKEN",f.message),d+=f.source.length;break;default:{let m=`Unexpected token in block scalar header: ${f.type}`;i(f,"UNEXPECTED_TOKEN",m);let h=f.source;h&&typeof h=="string"&&(d+=h.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function ZC(e){let t=e.split(/\n( *)/),r=t[0],i=r.match(/^( *)/),a=[i?.[1]?[i[1],r.slice(i[1].length)]:["",r]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}qv.resolveBlockScalar=XC});var id=R(Vv=>{"use strict";var rd=de(),eR=Ui();function tR(e,t,r){let{offset:i,type:n,source:a,end:o}=e,s,c,l=(p,f,m)=>r(i+p,f,m);switch(n){case"scalar":s=rd.Scalar.PLAIN,c=rR(a,l);break;case"single-quoted-scalar":s=rd.Scalar.QUOTE_SINGLE,c=iR(a,l);break;case"double-quoted-scalar":s=rd.Scalar.QUOTE_DOUBLE,c=nR(a,l);break;default:return r(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[i,i+a.length,i+a.length]}}let u=i+a.length,d=eR.resolveEnd(o,u,t,r);return{value:c,type:s,comment:d.comment,range:[i,u,d.offset]}}function rR(e,t){let r="";switch(e[0]){case" ":r="a tab character";break;case",":r="flow indicator character ,";break;case"%":r="directive indicator character %";break;case"|":case">":{r=`block scalar indicator ${e[0]}`;break}case"@":case"`":{r=`reserved character ${e[0]}`;break}}return r&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${r}`),Mv(e)}function iR(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Mv(e.slice(1,-1)).replace(/''/g,"'")}function Mv(e){let t,r;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
89
89
  `,"sy"),r=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
90
90
  `,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,r=/[ \t]*(.*?)[ \t]*\r?\n/sy}let i=t.exec(e);if(!i)return e;let n=i[1],a=" ",o=t.lastIndex;for(r.lastIndex=o;i=r.exec(e);)i[1]===""?a===`
91
91
  `?n+=a:a=`
92
- `:(n+=a+i[1],a=" "),o=r.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,i=s.exec(e),n+a+(i?.[1]??"")}function JC(e,t){let r="";for(let i=1;i<e.length-1;++i){let n=e[i];if(!(n==="\r"&&e[i+1]===`
92
+ `:(n+=a+i[1],a=" "),o=r.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,i=s.exec(e),n+a+(i?.[1]??"")}function nR(e,t){let r="";for(let i=1;i<e.length-1;++i){let n=e[i];if(!(n==="\r"&&e[i+1]===`
93
93
  `))if(n===`
94
- `){let{fold:a,offset:o}=UC(e,i);r+=a,i=o}else if(n==="\\"){let a=e[++i],o=KC[a];if(o)r+=o;else if(a===`
94
+ `){let{fold:a,offset:o}=aR(e,i);r+=a,i=o}else if(n==="\\"){let a=e[++i],o=oR[a];if(o)r+=o;else if(a===`
95
95
  `)for(a=e[i+1];a===" "||a===" ";)a=e[++i+1];else if(a==="\r"&&e[i+1]===`
96
- `)for(a=e[++i+1];a===" "||a===" ";)a=e[++i+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;r+=YC(e,i+1,s,t),i+=s}else{let s=e.substr(i-1,2);t(i-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),r+=s}}else if(n===" "||n===" "){let a=i,o=e[i+1];for(;o===" "||o===" ";)o=e[++i+1];o!==`
96
+ `)for(a=e[++i+1];a===" "||a===" ";)a=e[++i+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;r+=sR(e,i+1,s,t),i+=s}else{let s=e.substr(i-1,2);t(i-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),r+=s}}else if(n===" "||n===" "){let a=i,o=e[i+1];for(;o===" "||o===" ";)o=e[++i+1];o!==`
97
97
  `&&!(o==="\r"&&e[i+2]===`
98
- `)&&(r+=i>a?e.slice(a,i+1):n)}else r+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),r}function UC(e,t){let r="",i=e[t+1];for(;(i===" "||i===" "||i===`
98
+ `)&&(r+=i>a?e.slice(a,i+1):n)}else r+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),r}function aR(e,t){let r="",i=e[t+1];for(;(i===" "||i===" "||i===`
99
99
  `||i==="\r")&&!(i==="\r"&&e[t+2]!==`
100
100
  `);)i===`
101
101
  `&&(r+=`
102
- `),t+=1,i=e[t+1];return r||(r=" "),{fold:r,offset:t}}var KC={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
103
- `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function YC(e,t,r,i){let n=e.substr(t,r),o=n.length===r&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,r+2);return i(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}Fv.resolveFlowScalar=WC});var Mv=R(qv=>{"use strict";var ui=W(),Lv=de(),XC=Qu(),QC=ed();function ZC(e,t,r,i){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?XC.resolveBlockScalar(e,t,i):QC.resolveFlowScalar(t,e.options.strict,i),c=r?e.directives.tagName(r.source,d=>i(r,"TAG_RESOLVE_FAILED",d)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[ui.SCALAR]:c?l=eR(e.schema,n,c,r,i):t.type==="scalar"?l=tR(e,n,t,i):l=e.schema[ui.SCALAR];let u;try{let d=l.resolve(n,p=>i(r??t,"TAG_RESOLVE_FAILED",p),e.options);u=ui.isScalar(d)?d:new Lv.Scalar(d)}catch(d){let p=d instanceof Error?d.message:String(d);i(r??t,"TAG_RESOLVE_FAILED",p),u=new Lv.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 eR(e,t,r,i,n){if(r==="!")return e[ui.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===r)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(t))return s;let o=e.knownTags[r];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${r}`,r!=="tag:yaml.org,2002:str"),e[ui.SCALAR])}function tR({atKey:e,directives:t,schema:r},i,n,a){let o=r.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(i))||r[ui.SCALAR];if(r.compat){let s=r.compat.find(c=>c.default&&c.test?.test(i))??r[ui.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}qv.composeScalar=ZC});var Wv=R(Vv=>{"use strict";function rR(e,t,r){if(t){r??(r=t.length);for(let i=r-1;i>=0;--i){let n=t[i];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}for(n=t[++i];n?.type==="space";)e+=n.source.length,n=t[++i];break}}return e}Vv.emptyScalarPosition=rR});var Jv=R(rd=>{"use strict";var iR=ta(),nR=W(),aR=Hv(),zv=Mv(),oR=Ji(),sR=Wv(),cR={composeNode:Gv,composeEmptyNode:td};function Gv(e,t,r,i){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=r,l,u=!0;switch(t.type){case"alias":l=lR(e,t,i),(s||c)&&i(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=zv.composeScalar(e,t,c,i),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=aR.composeCollection(cR,e,t,r,i),s&&(l.anchor=s.source.substring(1))}catch(d){let p=d instanceof Error?d.message:String(d);i(t,"RESOURCE_EXHAUSTION",p)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;i(t,"UNEXPECTED_TOKEN",d),u=!1}}return l??(l=td(e,t.offset,void 0,null,r,i)),s&&l.anchor===""&&i(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&e.options.stringKeys&&(!nR.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&i(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function td(e,t,r,i,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:sR.emptyScalarPosition(t,r,i),indent:-1,source:""},d=zv.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 lR({options:e},{offset:t,source:r,end:i},n){let a=new iR.Alias(r.substring(1));a.source===""&&n(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(t+r.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+r.length,s=oR.resolveEnd(i,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}rd.composeEmptyNode=td;rd.composeNode=Gv});var Yv=R(Kv=>{"use strict";var uR=ga(),Uv=Jv(),dR=Ji(),pR=ba();function fR(e,t,{offset:r,start:i,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new uR.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=pR.resolveProps(i,{indicator:"doc-start",next:n??a?.[0],offset:r,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?Uv.composeNode(l,n,u,o):Uv.composeEmptyNode(l,u.end,i,null,u,o);let d=c.contents.range[2],p=dR.resolveEnd(a,d,!1,o);return p.comment&&(c.comment=p.comment),c.range=[r,d,p.offset],c}Kv.composeDoc=fR});var nd=R(Zv=>{"use strict";var hR=zo("process"),mR=Vl(),vR=ga(),ka=Na(),Xv=W(),gR=Yv(),wR=Ji();function Sa(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:r}=e;return[t,t+(typeof r=="string"?r.length:1)]}function Qv(e){let t="",r=!1,i=!1;for(let n=0;n<e.length;++n){let a=e[n];switch(a[0]){case"#":t+=(t===""?"":i?`
102
+ `),t+=1,i=e[t+1];return r||(r=" "),{fold:r,offset:t}}var oR={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
103
+ `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function sR(e,t,r,i){let n=e.substr(t,r),o=n.length===r&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,r+2);return i(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}Vv.resolveFlowScalar=tR});var Gv=R(zv=>{"use strict";var ui=W(),Wv=de(),cR=td(),lR=id();function uR(e,t,r,i){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?cR.resolveBlockScalar(e,t,i):lR.resolveFlowScalar(t,e.options.strict,i),c=r?e.directives.tagName(r.source,d=>i(r,"TAG_RESOLVE_FAILED",d)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[ui.SCALAR]:c?l=dR(e.schema,n,c,r,i):t.type==="scalar"?l=pR(e,n,t,i):l=e.schema[ui.SCALAR];let u;try{let d=l.resolve(n,p=>i(r??t,"TAG_RESOLVE_FAILED",p),e.options);u=ui.isScalar(d)?d:new Wv.Scalar(d)}catch(d){let p=d instanceof Error?d.message:String(d);i(r??t,"TAG_RESOLVE_FAILED",p),u=new Wv.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 dR(e,t,r,i,n){if(r==="!")return e[ui.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===r)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(t))return s;let o=e.knownTags[r];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${r}`,r!=="tag:yaml.org,2002:str"),e[ui.SCALAR])}function pR({atKey:e,directives:t,schema:r},i,n,a){let o=r.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(i))||r[ui.SCALAR];if(r.compat){let s=r.compat.find(c=>c.default&&c.test?.test(i))??r[ui.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}zv.composeScalar=uR});var Uv=R(Jv=>{"use strict";function fR(e,t,r){if(t){r??(r=t.length);for(let i=r-1;i>=0;--i){let n=t[i];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}for(n=t[++i];n?.type==="space";)e+=n.source.length,n=t[++i];break}}return e}Jv.emptyScalarPosition=fR});var Xv=R(ad=>{"use strict";var hR=ra(),mR=W(),vR=Lv(),Kv=Gv(),gR=Ui(),wR=Uv(),yR={composeNode:Yv,composeEmptyNode:nd};function Yv(e,t,r,i){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=r,l,u=!0;switch(t.type){case"alias":l=NR(e,t,i),(s||c)&&i(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=Kv.composeScalar(e,t,c,i),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=vR.composeCollection(yR,e,t,r,i),s&&(l.anchor=s.source.substring(1))}catch(d){let p=d instanceof Error?d.message:String(d);i(t,"RESOURCE_EXHAUSTION",p)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;i(t,"UNEXPECTED_TOKEN",d),u=!1}}return l??(l=nd(e,t.offset,void 0,null,r,i)),s&&l.anchor===""&&i(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&e.options.stringKeys&&(!mR.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&i(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function nd(e,t,r,i,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:wR.emptyScalarPosition(t,r,i),indent:-1,source:""},d=Kv.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 NR({options:e},{offset:t,source:r,end:i},n){let a=new hR.Alias(r.substring(1));a.source===""&&n(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(t+r.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+r.length,s=gR.resolveEnd(i,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}ad.composeEmptyNode=nd;ad.composeNode=Yv});var eg=R(Zv=>{"use strict";var bR=wa(),Qv=Xv(),kR=Ui(),SR=ka();function ER(e,t,{offset:r,start:i,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new bR.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=SR.resolveProps(i,{indicator:"doc-start",next:n??a?.[0],offset:r,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?Qv.composeNode(l,n,u,o):Qv.composeEmptyNode(l,u.end,i,null,u,o);let d=c.contents.range[2],p=kR.resolveEnd(a,d,!1,o);return p.comment&&(c.comment=p.comment),c.range=[r,d,p.offset],c}Zv.composeDoc=ER});var sd=R(ig=>{"use strict";var xR=Jo("process"),CR=Gl(),RR=wa(),Sa=ba(),tg=W(),PR=eg(),_R=Ui();function Ea(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:r}=e;return[t,t+(typeof r=="string"?r.length:1)]}function rg(e){let t="",r=!1,i=!1;for(let n=0;n<e.length;++n){let a=e[n];switch(a[0]){case"#":t+=(t===""?"":i?`
104
104
 
105
105
  `:`
106
- `)+(a.substring(1)||" "),r=!0,i=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),r=!1;break;default:r||(i=!0),r=!1}}return{comment:t,afterEmptyLine:i}}var id=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,i,n,a)=>{let o=Sa(r);a?this.warnings.push(new ka.YAMLWarning(o,i,n)):this.errors.push(new ka.YAMLParseError(o,i,n))},this.directives=new mR.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,r){let{comment:i,afterEmptyLine:n}=Qv(this.prelude);if(i){let a=t.contents;if(r)t.comment=t.comment?`${t.comment}
107
- ${i}`:i;else if(n||t.directives.docStart||!a)t.commentBefore=i;else if(Xv.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];Xv.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${i}
106
+ `)+(a.substring(1)||" "),r=!0,i=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),r=!1;break;default:r||(i=!0),r=!1}}return{comment:t,afterEmptyLine:i}}var od=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,i,n,a)=>{let o=Ea(r);a?this.warnings.push(new Sa.YAMLWarning(o,i,n)):this.errors.push(new Sa.YAMLParseError(o,i,n))},this.directives=new CR.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,r){let{comment:i,afterEmptyLine:n}=rg(this.prelude);if(i){let a=t.contents;if(r)t.comment=t.comment?`${t.comment}
107
+ ${i}`:i;else if(n||t.directives.docStart||!a)t.commentBefore=i;else if(tg.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];tg.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${i}
108
108
  ${s}`:i}else{let o=a.commentBefore;a.commentBefore=o?`${i}
109
- ${o}`:i}}if(r){for(let a=0;a<this.errors.length;++a)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Qv(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,r=!1,i=-1){for(let n of t)yield*this.next(n);yield*this.end(r,i)}*next(t){switch(hR.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(r,i,n)=>{let a=Sa(t);a[0]+=r,this.onError(a,"BAD_DIRECTIVE",i,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let r=gR.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!r.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(r,!1),this.doc&&(yield this.doc),this.doc=r,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let r=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,i=new ka.YAMLParseError(Sa(t),"UNEXPECTED_TOKEN",r);this.atDirectives||!this.doc?this.errors.push(i):this.doc.errors.push(i);break}case"doc-end":{if(!this.doc){let i="Unexpected doc-end without preceding document";this.errors.push(new ka.YAMLParseError(Sa(t),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let r=wR.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),r.comment){let i=this.doc.comment;this.doc.comment=i?`${i}
110
- ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new ka.YAMLParseError(Sa(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,r=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let i=Object.assign({_directives:this.directives},this.options),n=new vR.Document(void 0,i);this.atDirectives&&this.onError(r,"MISSING_CHAR","Missing directives-end indicator line"),n.range=[0,r,r],this.decorate(n,!1),yield n}}};Zv.Composer=id});var rg=R(Ds=>{"use strict";var yR=Qu(),NR=ed(),bR=Na(),eg=oa();function kR(e,t=!0,r){if(e){let i=(n,a,o)=>{let s=typeof n=="number"?n:Array.isArray(n)?n[0]:n.offset;if(r)r(s,a,o);else throw new bR.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return NR.resolveFlowScalar(e,t,i);case"block-scalar":return yR.resolveBlockScalar({options:{strict:t}},e,i)}}return null}function SR(e,t){let{implicitKey:r=!1,indent:i,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=eg.stringifyString({type:o,value:e},{implicitKey:r,indent:i>0?" ".repeat(i):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:i,source:`
109
+ ${o}`:i}}if(r){for(let a=0;a<this.errors.length;++a)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:rg(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,r=!1,i=-1){for(let n of t)yield*this.next(n);yield*this.end(r,i)}*next(t){switch(xR.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(r,i,n)=>{let a=Ea(t);a[0]+=r,this.onError(a,"BAD_DIRECTIVE",i,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let r=PR.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!r.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(r,!1),this.doc&&(yield this.doc),this.doc=r,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let r=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,i=new Sa.YAMLParseError(Ea(t),"UNEXPECTED_TOKEN",r);this.atDirectives||!this.doc?this.errors.push(i):this.doc.errors.push(i);break}case"doc-end":{if(!this.doc){let i="Unexpected doc-end without preceding document";this.errors.push(new Sa.YAMLParseError(Ea(t),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let r=_R.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),r.comment){let i=this.doc.comment;this.doc.comment=i?`${i}
110
+ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new Sa.YAMLParseError(Ea(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,r=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let i=Object.assign({_directives:this.directives},this.options),n=new RR.Document(void 0,i);this.atDirectives&&this.onError(r,"MISSING_CHAR","Missing directives-end indicator line"),n.range=[0,r,r],this.decorate(n,!1),yield n}}};ig.Composer=od});var og=R(Fs=>{"use strict";var AR=td(),IR=id(),TR=ba(),ng=sa();function jR(e,t=!0,r){if(e){let i=(n,a,o)=>{let s=typeof n=="number"?n:Array.isArray(n)?n[0]:n.offset;if(r)r(s,a,o);else throw new TR.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return IR.resolveFlowScalar(e,t,i);case"block-scalar":return AR.resolveBlockScalar({options:{strict:t}},e,i)}}return null}function $R(e,t){let{implicitKey:r=!1,indent:i,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=ng.stringifyString({type:o,value:e},{implicitKey:r,indent:i>0?" ".repeat(i):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:i,source:`
111
111
  `}];switch(s[0]){case"|":case">":{let l=s.indexOf(`
112
112
  `),u=s.substring(0,l),d=s.substring(l+1)+`
113
- `,p=[{type:"block-scalar-header",offset:a,indent:i,source:u}];return tg(p,c)||p.push({type:"newline",offset:-1,indent:i,source:`
114
- `}),{type:"block-scalar",offset:a,indent:i,props:p,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:i,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:i,source:s,end:c};default:return{type:"scalar",offset:a,indent:i,source:s,end:c}}}function ER(e,t,r={}){let{afterKey:i=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=r,s="indent"in e?e.indent:null;if(i&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=eg.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">":xR(e,c);break;case'"':ad(e,c,"double-quoted-scalar");break;case"'":ad(e,c,"single-quoted-scalar");break;default:ad(e,c,"scalar")}}function xR(e,t){let r=t.indexOf(`
113
+ `,p=[{type:"block-scalar-header",offset:a,indent:i,source:u}];return ag(p,c)||p.push({type:"newline",offset:-1,indent:i,source:`
114
+ `}),{type:"block-scalar",offset:a,indent:i,props:p,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:i,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:i,source:s,end:c};default:return{type:"scalar",offset:a,indent:i,source:s,end:c}}}function OR(e,t,r={}){let{afterKey:i=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=r,s="indent"in e?e.indent:null;if(i&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=ng.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">":HR(e,c);break;case'"':cd(e,c,"double-quoted-scalar");break;case"'":cd(e,c,"single-quoted-scalar");break;default:cd(e,c,"scalar")}}function HR(e,t){let r=t.indexOf(`
115
115
  `),i=t.substring(0,r),n=t.substring(r+1)+`
116
- `;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=i,e.source=n}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:i}];tg(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
117
- `});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 tg(e,t){if(t)for(let r of t)switch(r.type){case"space":case"comment":e.push(r);break;case"newline":return e.push(r),!0}return!1}function ad(e,t,r){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=r,e.source=t;break;case"block-scalar":{let i=e.props.slice(1),n=t.length;e.props[0].type==="block-scalar-header"&&(n-=e.props[0].source.length);for(let a of i)a.offset+=n;delete e.props,Object.assign(e,{type:r,source:t,end:i});break}case"block-map":case"block-seq":{let n={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
118
- `};delete e.items,Object.assign(e,{type:r,source:t,end:[n]});break}default:{let i="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:r,indent:i,source:t,end:n})}}}Ds.createScalarToken=SR;Ds.resolveAsScalar=kR;Ds.setScalarValue=ER});var ng=R(ig=>{"use strict";var CR=e=>"type"in e?Fs(e):Bs(e);function Fs(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=Fs(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=Bs(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=Bs(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=Bs(e);if(e.end)for(let r of e.end)t+=r.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let r of e.end)t+=r.source;return t}}}function Bs({start:e,key:t,sep:r,value:i}){let n="";for(let a of e)n+=a.source;if(t&&(n+=Fs(t)),r)for(let a of r)n+=a.source;return i&&(n+=Fs(i)),n}ig.stringify=CR});var cg=R(sg=>{"use strict";var od=Symbol("break visit"),RR=Symbol("skip children"),ag=Symbol("remove item");function di(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),og(Object.freeze([]),e,t)}di.BREAK=od;di.SKIP=RR;di.REMOVE=ag;di.itemAtPath=(e,t)=>{let r=e;for(let[i,n]of t){let a=r?.[i];if(a&&"items"in a)r=a.items[n];else return}return r};di.parentCollection=(e,t)=>{let r=di.itemAtPath(e,t.slice(0,-1)),i=t[t.length-1][0],n=r?.[i];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function og(e,t,r){let i=r(t,e);if(typeof i=="symbol")return i;for(let n of["key","value"]){let a=t[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=og(Object.freeze(e.concat([[n,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===od)return od;s===ag&&(a.items.splice(o,1),o-=1)}}typeof i=="function"&&n==="key"&&(i=i(t,e))}}return typeof i=="function"?i(t,e):i}sg.visit=di});var Ls=R(Fe=>{"use strict";var sd=rg(),PR=ng(),_R=cg(),cd="\uFEFF",ld="",ud="",dd="",AR=e=>!!e&&"items"in e,IR=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function TR(e){switch(e){case cd:return"<BOM>";case ld:return"<DOC>";case ud:return"<FLOW_END>";case dd:return"<SCALAR>";default:return JSON.stringify(e)}}function jR(e){switch(e){case cd:return"byte-order-mark";case ld:return"doc-mode";case ud:return"flow-error-end";case dd:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
116
+ `;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=i,e.source=n}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:i}];ag(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
117
+ `});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 ag(e,t){if(t)for(let r of t)switch(r.type){case"space":case"comment":e.push(r);break;case"newline":return e.push(r),!0}return!1}function cd(e,t,r){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=r,e.source=t;break;case"block-scalar":{let i=e.props.slice(1),n=t.length;e.props[0].type==="block-scalar-header"&&(n-=e.props[0].source.length);for(let a of i)a.offset+=n;delete e.props,Object.assign(e,{type:r,source:t,end:i});break}case"block-map":case"block-seq":{let n={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
118
+ `};delete e.items,Object.assign(e,{type:r,source:t,end:[n]});break}default:{let i="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:r,indent:i,source:t,end:n})}}}Fs.createScalarToken=$R;Fs.resolveAsScalar=jR;Fs.setScalarValue=OR});var cg=R(sg=>{"use strict";var DR=e=>"type"in e?qs(e):Ls(e);function qs(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=qs(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=Ls(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=Ls(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=Ls(e);if(e.end)for(let r of e.end)t+=r.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let r of e.end)t+=r.source;return t}}}function Ls({start:e,key:t,sep:r,value:i}){let n="";for(let a of e)n+=a.source;if(t&&(n+=qs(t)),r)for(let a of r)n+=a.source;return i&&(n+=qs(i)),n}sg.stringify=DR});var pg=R(dg=>{"use strict";var ld=Symbol("break visit"),BR=Symbol("skip children"),lg=Symbol("remove item");function di(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),ug(Object.freeze([]),e,t)}di.BREAK=ld;di.SKIP=BR;di.REMOVE=lg;di.itemAtPath=(e,t)=>{let r=e;for(let[i,n]of t){let a=r?.[i];if(a&&"items"in a)r=a.items[n];else return}return r};di.parentCollection=(e,t)=>{let r=di.itemAtPath(e,t.slice(0,-1)),i=t[t.length-1][0],n=r?.[i];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function ug(e,t,r){let i=r(t,e);if(typeof i=="symbol")return i;for(let n of["key","value"]){let a=t[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=ug(Object.freeze(e.concat([[n,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===ld)return ld;s===lg&&(a.items.splice(o,1),o-=1)}}typeof i=="function"&&n==="key"&&(i=i(t,e))}}return typeof i=="function"?i(t,e):i}dg.visit=di});var Ms=R(Fe=>{"use strict";var ud=og(),FR=cg(),LR=pg(),dd="\uFEFF",pd="",fd="",hd="",qR=e=>!!e&&"items"in e,MR=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function VR(e){switch(e){case dd:return"<BOM>";case pd:return"<DOC>";case fd:return"<FLOW_END>";case hd:return"<SCALAR>";default:return JSON.stringify(e)}}function WR(e){switch(e){case dd:return"byte-order-mark";case pd:return"doc-mode";case fd:return"flow-error-end";case hd:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
119
119
  `:case`\r
120
- `: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}Fe.createScalarToken=sd.createScalarToken;Fe.resolveAsScalar=sd.resolveAsScalar;Fe.setScalarValue=sd.setScalarValue;Fe.stringify=PR.stringify;Fe.visit=_R.visit;Fe.BOM=cd;Fe.DOCUMENT=ld;Fe.FLOW_END=ud;Fe.SCALAR=dd;Fe.isCollection=AR;Fe.isScalar=IR;Fe.prettyToken=TR;Fe.tokenType=jR});var hd=R(ug=>{"use strict";var Ea=Ls();function ft(e){switch(e){case void 0:case" ":case`
121
- `:case"\r":case" ":return!0;default:return!1}}var lg=new Set("0123456789ABCDEFabcdef"),$R=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),qs=new Set(",[]{}"),OR=new Set(` ,[]{}
122
- \r `),pd=e=>!e||OR.has(e),fd=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,r=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!r;let i=this.next??"stream";for(;i&&(r||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let t=this.pos,r=this.buffer[t];for(;r===" "||r===" ";)r=this.buffer[++t];return!r||r==="#"||r===`
120
+ `: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}Fe.createScalarToken=ud.createScalarToken;Fe.resolveAsScalar=ud.resolveAsScalar;Fe.setScalarValue=ud.setScalarValue;Fe.stringify=FR.stringify;Fe.visit=LR.visit;Fe.BOM=dd;Fe.DOCUMENT=pd;Fe.FLOW_END=fd;Fe.SCALAR=hd;Fe.isCollection=qR;Fe.isScalar=MR;Fe.prettyToken=VR;Fe.tokenType=WR});var gd=R(hg=>{"use strict";var xa=Ms();function ft(e){switch(e){case void 0:case" ":case`
121
+ `:case"\r":case" ":return!0;default:return!1}}var fg=new Set("0123456789ABCDEFabcdef"),zR=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Vs=new Set(",[]{}"),GR=new Set(` ,[]{}
122
+ \r `),md=e=>!e||GR.has(e),vd=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,r=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!r;let i=this.next??"stream";for(;i&&(r||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let t=this.pos,r=this.buffer[t];for(;r===" "||r===" ";)r=this.buffer[++t];return!r||r==="#"||r===`
123
123
  `?!0:r==="\r"?this.buffer[t+1]===`
124
124
  `:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let r=this.buffer[t];if(this.indentNext>0){let i=0;for(;r===" ";)r=this.buffer[++i+t];if(r==="\r"){let n=this.buffer[i+t+1];if(n===`
125
125
  `||!n&&!this.atEnd)return t+i+1}return r===`
126
126
  `||i>=this.indentNext||!r&&!this.atEnd?t+i:-1}if(r==="-"||r==="."){let i=this.buffer.substr(t,3);if((i==="---"||i==="...")&&ft(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
127
- `,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]===Ea.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let r=t.length,i=t.indexOf("#");for(;i!==-1;){let a=t[i-1];if(a===" "||a===" "){r=i-1;break}else i=t.indexOf("#",i+1)}for(;;){let a=t[r-1];if(a===" "||a===" ")r-=1;else break}let n=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let r=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-r),yield*this.pushNewline(),"stream"}return yield Ea.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let r=this.peek(3);if((r==="---"||r==="...")&&ft(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,r==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!ft(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,r]=this.peek(2);if(!r&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&ft(r)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let r=yield*this.pushIndicators();switch(t[r]){case"#":yield*this.pushCount(t.length-r);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(pd),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return r+=yield*this.parseBlockScalarHeader(),r+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-r),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,r,i=-1;do t=yield*this.pushNewline(),t>0?(r=yield*this.pushSpaces(!1),this.indentValue=i=r):r=0,r+=yield*this.pushSpaces(!0);while(t+r>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((i!==-1&&i<this.indentNext&&n[0]!=="#"||i===0&&(n.startsWith("---")||n.startsWith("..."))&&ft(n[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield Ea.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(pd),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||ft(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),r=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;r!==-1&&this.buffer[r+1]==="'";)r=this.buffer.indexOf("'",r+2);else for(;r!==-1;){let a=0;for(;this.buffer[r-1-a]==="\\";)a+=1;if(a%2===0)break;r=this.buffer.indexOf('"',r+1)}let i=this.buffer.substring(0,r),n=i.indexOf(`
127
+ `,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]===xa.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let r=t.length,i=t.indexOf("#");for(;i!==-1;){let a=t[i-1];if(a===" "||a===" "){r=i-1;break}else i=t.indexOf("#",i+1)}for(;;){let a=t[r-1];if(a===" "||a===" ")r-=1;else break}let n=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let r=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-r),yield*this.pushNewline(),"stream"}return yield xa.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let r=this.peek(3);if((r==="---"||r==="...")&&ft(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,r==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!ft(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,r]=this.peek(2);if(!r&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&ft(r)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let r=yield*this.pushIndicators();switch(t[r]){case"#":yield*this.pushCount(t.length-r);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(md),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return r+=yield*this.parseBlockScalarHeader(),r+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-r),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,r,i=-1;do t=yield*this.pushNewline(),t>0?(r=yield*this.pushSpaces(!1),this.indentValue=i=r):r=0,r+=yield*this.pushSpaces(!0);while(t+r>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((i!==-1&&i<this.indentNext&&n[0]!=="#"||i===0&&(n.startsWith("---")||n.startsWith("..."))&&ft(n[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield xa.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(md),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||ft(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),r=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;r!==-1&&this.buffer[r+1]==="'";)r=this.buffer.indexOf("'",r+2);else for(;r!==-1;){let a=0;for(;this.buffer[r-1-a]==="\\";)a+=1;if(a%2===0)break;r=this.buffer.indexOf('"',r+1)}let i=this.buffer.substring(0,r),n=i.indexOf(`
128
128
  `,this.pos);if(n!==-1){for(;n!==-1;){let a=this.continueScalar(n+1);if(a===-1)break;n=i.indexOf(`
129
129
  `,a)}n!==-1&&(r=n-(i[n-1]==="\r"?2:1))}if(r===-1){if(!this.atEnd)return this.setNext("quoted-scalar");r=this.buffer.length}return yield*this.pushToIndex(r+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let r=this.buffer[++t];if(r==="+")this.blockScalarKeep=!0;else if(r>"0"&&r<="9")this.blockScalarIndent=Number(r)-1;else if(r!=="-")break}return yield*this.pushUntil(r=>ft(r)||r==="#")}*parseBlockScalar(){let t=this.pos-1,r=0,i;e:for(let a=this.pos;i=this.buffer[a];++a)switch(i){case" ":r+=1;break;case`
130
130
  `:t=a,r=0;break;case"\r":{let o=this.buffer[a+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
131
131
  `)break}default:break e}if(!i&&!this.atEnd)return this.setNext("block-scalar");if(r>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=r:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let a=this.continueScalar(t+1);if(a===-1)break;t=this.buffer.indexOf(`
132
132
  `,a)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let n=t+1;for(i=this.buffer[n];i===" ";)i=this.buffer[++n];if(i===" "){for(;i===" "||i===" "||i==="\r"||i===`
133
133
  `;)i=this.buffer[++n];t=n-1}else if(!this.blockScalarKeep)do{let a=t-1,o=this.buffer[a];o==="\r"&&(o=this.buffer[--a]);let s=a;for(;o===" ";)o=this.buffer[--a];if(o===`
134
- `&&a>=this.pos&&a+1+r>s)t=a;else break}while(!0);return yield Ea.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,r=this.pos-1,i=this.pos-1,n;for(;n=this.buffer[++i];)if(n===":"){let a=this.buffer[i+1];if(ft(a)||t&&qs.has(a))break;r=i}else if(ft(n)){let a=this.buffer[i+1];if(n==="\r"&&(a===`
134
+ `&&a>=this.pos&&a+1+r>s)t=a;else break}while(!0);return yield xa.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,r=this.pos-1,i=this.pos-1,n;for(;n=this.buffer[++i];)if(n===":"){let a=this.buffer[i+1];if(ft(a)||t&&Vs.has(a))break;r=i}else if(ft(n)){let a=this.buffer[i+1];if(n==="\r"&&(a===`
135
135
  `?(i+=1,n=`
136
- `,a=this.buffer[i+1]):r=i),a==="#"||t&&qs.has(a))break;if(n===`
137
- `){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&qs.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield Ea.SCALAR,yield*this.pushToIndex(r+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,r){let i=this.buffer.slice(this.pos,t);return i?(yield i,this.pos+=i.length,i.length):(r&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(pd),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(ft(i)||r&&qs.has(i)){r?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,r=this.buffer[t];for(;!ft(r)&&r!==">";)r=this.buffer[++t];return yield*this.pushToIndex(r===">"?t+1:t,!1)}else{let t=this.pos+1,r=this.buffer[t];for(;r;)if($R.has(r))r=this.buffer[++t];else if(r==="%"&&lg.has(this.buffer[t+1])&&lg.has(this.buffer[t+2]))r=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
136
+ `,a=this.buffer[i+1]):r=i),a==="#"||t&&Vs.has(a))break;if(n===`
137
+ `){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&Vs.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield xa.SCALAR,yield*this.pushToIndex(r+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,r){let i=this.buffer.slice(this.pos,t);return i?(yield i,this.pos+=i.length,i.length):(r&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(md),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(ft(i)||r&&Vs.has(i)){r?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,r=this.buffer[t];for(;!ft(r)&&r!==">";)r=this.buffer[++t];return yield*this.pushToIndex(r===">"?t+1:t,!1)}else{let t=this.pos+1,r=this.buffer[t];for(;r;)if(zR.has(r))r=this.buffer[++t];else if(r==="%"&&fg.has(this.buffer[t+1])&&fg.has(this.buffer[t+2]))r=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
138
138
  `?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
139
- `?yield*this.pushCount(2):0}*pushSpaces(t){let r=this.pos-1,i;do i=this.buffer[++r];while(i===" "||t&&i===" ");let n=r-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=r),n}*pushUntil(t){let r=this.pos,i=this.buffer[r];for(;!t(i);)i=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};ug.Lexer=fd});var vd=R(dg=>{"use strict";var md=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let r=0,i=this.lineStarts.length;for(;r<i;){let a=r+i>>1;this.lineStarts[a]<t?r=a+1:i=a}if(this.lineStarts[r]===t)return{line:r+1,col:1};if(r===0)return{line:0,col:t};let n=this.lineStarts[r-1];return{line:r,col:t-n+1}}}};dg.LineCounter=md});var wd=R(vg=>{"use strict";var HR=zo("process"),pg=Ls(),DR=hd();function Pr(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function fg(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 mg(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 Ms(e){switch(e.type){case"document":return e.start;case"block-map":{let t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function Ui(e){if(e.length===0)return[];let t=e.length;e:for(;--t>=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function Vs(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let r=0;r<t.length;++r)e.push(t[r])}function hg(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Pr(t.start,"explicit-key-ind")&&!Pr(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,mg(t.value)?t.value.end?Vs(t.value.end,t.sep):t.value.end=t.sep:Vs(t.start,t.sep),delete t.sep)}var gd=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 DR.Lexer,this.onNewLine=t}*parse(t,r=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let i of this.lexer.lex(t,r))yield*this.next(i);r||(yield*this.end())}*next(t){if(this.source=t,HR.env.LOG_TOKENS&&console.log("|",pg.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=pg.tokenType(t);if(r)if(r==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=r,yield*this.step(),r){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let i=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:i,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let r=t??this.stack.pop();if(!r)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield r;else{let i=this.peek(1);switch(r.type==="block-scalar"?r.indent="indent"in i?i.indent:0:r.type==="flow-collection"&&i.type==="document"&&(r.indent=0),r.type==="flow-collection"&&hg(r),i.type){case"document":i.value=r;break;case"block-scalar":i.props.push(r);break;case"block-map":{let n=i.items[i.items.length-1];if(n.value){i.items.push({start:[],key:r,sep:[]}),this.onKeyLine=!0;return}else if(n.sep)n.value=r;else{Object.assign(n,{key:r,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case"block-seq":{let n=i.items[i.items.length-1];n.value?i.items.push({start:[],value:r}):n.value=r;break}case"flow-collection":{let n=i.items[i.items.length-1];!n||n.value?i.items.push({start:[],key:r,sep:[]}):n.sep?n.value=r:Object.assign(n,{key:r,sep:[]});return}default:yield*this.pop(),yield*this.pop(r)}if((i.type==="document"||i.type==="block-map"||i.type==="block-seq")&&(r.type==="block-map"||r.type==="block-seq")){let n=r.items[r.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&fg(n.start)===-1&&(r.indent===0||n.start.every(a=>a.type!=="comment"||a.indent<r.indent))&&(i.type==="document"?i.end=n.start:i.items.push({start:n.start}),r.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{fg(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let r=Ms(this.peek(2)),i=Ui(r),n;t.end?(n=t.end,n.push(this.sourceToken),delete t.end):n=[this.sourceToken];let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:i,key:t,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let r=this.source.indexOf(`
139
+ `?yield*this.pushCount(2):0}*pushSpaces(t){let r=this.pos-1,i;do i=this.buffer[++r];while(i===" "||t&&i===" ");let n=r-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=r),n}*pushUntil(t){let r=this.pos,i=this.buffer[r];for(;!t(i);)i=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};hg.Lexer=vd});var yd=R(mg=>{"use strict";var wd=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let r=0,i=this.lineStarts.length;for(;r<i;){let a=r+i>>1;this.lineStarts[a]<t?r=a+1:i=a}if(this.lineStarts[r]===t)return{line:r+1,col:1};if(r===0)return{line:0,col:t};let n=this.lineStarts[r-1];return{line:r,col:t-n+1}}}};mg.LineCounter=wd});var bd=R(Ng=>{"use strict";var JR=Jo("process"),vg=Ms(),UR=gd();function Pr(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function gg(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 yg(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 Ws(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 Ki(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 zs(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let r=0;r<t.length;++r)e.push(t[r])}function wg(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Pr(t.start,"explicit-key-ind")&&!Pr(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,yg(t.value)?t.value.end?zs(t.value.end,t.sep):t.value.end=t.sep:zs(t.start,t.sep),delete t.sep)}var Nd=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 UR.Lexer,this.onNewLine=t}*parse(t,r=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let i of this.lexer.lex(t,r))yield*this.next(i);r||(yield*this.end())}*next(t){if(this.source=t,JR.env.LOG_TOKENS&&console.log("|",vg.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=vg.tokenType(t);if(r)if(r==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=r,yield*this.step(),r){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let i=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:i,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let r=t??this.stack.pop();if(!r)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield r;else{let i=this.peek(1);switch(r.type==="block-scalar"?r.indent="indent"in i?i.indent:0:r.type==="flow-collection"&&i.type==="document"&&(r.indent=0),r.type==="flow-collection"&&wg(r),i.type){case"document":i.value=r;break;case"block-scalar":i.props.push(r);break;case"block-map":{let n=i.items[i.items.length-1];if(n.value){i.items.push({start:[],key:r,sep:[]}),this.onKeyLine=!0;return}else if(n.sep)n.value=r;else{Object.assign(n,{key:r,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case"block-seq":{let n=i.items[i.items.length-1];n.value?i.items.push({start:[],value:r}):n.value=r;break}case"flow-collection":{let n=i.items[i.items.length-1];!n||n.value?i.items.push({start:[],key:r,sep:[]}):n.sep?n.value=r:Object.assign(n,{key:r,sep:[]});return}default:yield*this.pop(),yield*this.pop(r)}if((i.type==="document"||i.type==="block-map"||i.type==="block-seq")&&(r.type==="block-map"||r.type==="block-seq")){let n=r.items[r.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&gg(n.start)===-1&&(r.indent===0||n.start.every(a=>a.type!=="comment"||a.indent<r.indent))&&(i.type==="document"?i.end=n.start:i.items.push({start:n.start}),r.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{gg(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let r=Ws(this.peek(2)),i=Ki(r),n;t.end?(n=t.end,n.push(this.sourceToken),delete t.end):n=[this.sourceToken];let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:i,key:t,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let r=this.source.indexOf(`
140
140
  `)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
141
- `,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else if(r.sep)r.sep.push(this.sourceToken);else{if(this.atIndentedComment(r.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){Vs(n,r.start),n.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let i=!this.onKeyLine&&this.indent===t.indent,n=i&&(r.sep||r.explicitKey)&&this.type!=="seq-item-ind",a=[];if(n&&r.sep&&!r.value){let o=[];for(let s=0;s<r.sep.length;++s){let c=r.sep[s];switch(c.type){case"newline":o.push(s);break;case"space":break;case"comment":c.indent>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=r.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":n||r.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"explicit-key-ind":!r.sep&&!r.explicitKey?(r.start.push(this.sourceToken),r.explicitKey=!0):n||r.value?(a.push(this.sourceToken),t.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(r.explicitKey)if(r.sep)if(r.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Pr(r.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]});else if(mg(r.key)&&!Pr(r.sep,"newline")){let o=Ui(r.start),s=r.key,c=r.sep;c.push(this.sourceToken),delete r.key,delete r.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?r.sep=r.sep.concat(a,this.sourceToken):r.sep.push(this.sourceToken);else if(Pr(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=Ui(r.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else r.sep?r.value||n?t.items.push({start:a,key:null,sep:[this.sourceToken]}):Pr(r.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);n||r.value?(t.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):r.sep?this.stack.push(o):(Object.assign(r,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!r.explicitKey&&r.sep&&!Pr(r.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else i&&t.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(r.value){let i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(r.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){Vs(n,r.start),n.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return;case"anchor":case"tag":if(r.value||this.indent<=t.indent)break;r.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;r.value||Pr(r.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return}if(this.indent>t.indent){let i=this.startBlockValue(t);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let r=t.items[t.items.length-1];if(this.type==="flow-error-end"){let i;do yield*this.pop(),i=this.peek(1);while(i?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!r||r.sep?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return;case"map-value-ind":!r||r.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!r||r.value?t.items.push({start:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let n=this.flowScalar(this.type);!r||r.value?t.items.push({start:[],key:n,sep:[]}):r.sep?this.stack.push(n):Object.assign(r,{key:n,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let i=this.startBlockValue(t);i?this.stack.push(i):(yield*this.pop(),yield*this.step())}else{let i=this.peek(2);if(i.type==="block-map"&&(this.type==="map-value-ind"&&i.indent===t.indent||this.type==="newline"&&!i.items[i.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&i.type!=="flow-collection"){let n=Ms(i),a=Ui(n);hg(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let r=this.source.indexOf(`
141
+ `,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else if(r.sep)r.sep.push(this.sourceToken);else{if(this.atIndentedComment(r.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){zs(n,r.start),n.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let i=!this.onKeyLine&&this.indent===t.indent,n=i&&(r.sep||r.explicitKey)&&this.type!=="seq-item-ind",a=[];if(n&&r.sep&&!r.value){let o=[];for(let s=0;s<r.sep.length;++s){let c=r.sep[s];switch(c.type){case"newline":o.push(s);break;case"space":break;case"comment":c.indent>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=r.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":n||r.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"explicit-key-ind":!r.sep&&!r.explicitKey?(r.start.push(this.sourceToken),r.explicitKey=!0):n||r.value?(a.push(this.sourceToken),t.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(r.explicitKey)if(r.sep)if(r.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Pr(r.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]});else if(yg(r.key)&&!Pr(r.sep,"newline")){let o=Ki(r.start),s=r.key,c=r.sep;c.push(this.sourceToken),delete r.key,delete r.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?r.sep=r.sep.concat(a,this.sourceToken):r.sep.push(this.sourceToken);else if(Pr(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=Ki(r.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else r.sep?r.value||n?t.items.push({start:a,key:null,sep:[this.sourceToken]}):Pr(r.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);n||r.value?(t.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):r.sep?this.stack.push(o):(Object.assign(r,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!r.explicitKey&&r.sep&&!Pr(r.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else i&&t.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(r.value){let i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(r.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){zs(n,r.start),n.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return;case"anchor":case"tag":if(r.value||this.indent<=t.indent)break;r.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;r.value||Pr(r.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return}if(this.indent>t.indent){let i=this.startBlockValue(t);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let r=t.items[t.items.length-1];if(this.type==="flow-error-end"){let i;do yield*this.pop(),i=this.peek(1);while(i?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!r||r.sep?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return;case"map-value-ind":!r||r.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!r||r.value?t.items.push({start:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let n=this.flowScalar(this.type);!r||r.value?t.items.push({start:[],key:n,sep:[]}):r.sep?this.stack.push(n):Object.assign(r,{key:n,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let i=this.startBlockValue(t);i?this.stack.push(i):(yield*this.pop(),yield*this.step())}else{let i=this.peek(2);if(i.type==="block-map"&&(this.type==="map-value-ind"&&i.indent===t.indent||this.type==="newline"&&!i.items[i.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&i.type!=="flow-collection"){let n=Ws(i),a=Ki(n);wg(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let r=this.source.indexOf(`
142
142
  `)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
143
- `,r)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=Ms(t),i=Ui(r);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let r=Ms(t),i=Ui(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,r){return this.type!=="comment"||this.indent<=r?!1:t.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};vg.Parser=gd});var bg=R(Ca=>{"use strict";var gg=nd(),BR=ga(),xa=Na(),FR=ru(),LR=W(),qR=vd(),wg=wd();function yg(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new qR.LineCounter||null,prettyErrors:t}}function MR(e,t={}){let{lineCounter:r,prettyErrors:i}=yg(t),n=new wg.Parser(r?.addNewLine),a=new gg.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach(xa.prettifyError(e,r)),s.warnings.forEach(xa.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Ng(e,t={}){let{lineCounter:r,prettyErrors:i}=yg(t),n=new wg.Parser(r?.addNewLine),a=new gg.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 xa.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(xa.prettifyError(e,r)),o.warnings.forEach(xa.prettifyError(e,r))),o}function VR(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=Ng(e,r);if(!n)return null;if(n.warnings.forEach(a=>FR.warn(n.options.logLevel,a)),n.errors.length>0){if(n.options.logLevel!=="silent")throw n.errors[0];n.errors=[]}return n.toJS(Object.assign({reviver:i},r))}function WR(e,t,r){let i=null;if(typeof t=="function"||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r=="string"&&(r=r.length),typeof r=="number"){let n=Math.round(r);r=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=r??t??{};if(!n)return}return LR.isDocument(e)&&!i?e.toString(r):new BR.Document(e,i,r).toString(r)}Ca.parse=VR;Ca.parseAllDocuments=MR;Ca.parseDocument=Ng;Ca.stringify=WR});var It=R(J=>{"use strict";var zR=nd(),GR=ga(),JR=Bu(),yd=Na(),UR=ta(),_r=W(),KR=Er(),YR=de(),XR=Cr(),QR=Rr(),ZR=Ls(),eP=hd(),tP=vd(),rP=wd(),Ws=bg(),kg=Xn();J.Composer=zR.Composer;J.Document=GR.Document;J.Schema=JR.Schema;J.YAMLError=yd.YAMLError;J.YAMLParseError=yd.YAMLParseError;J.YAMLWarning=yd.YAMLWarning;J.Alias=UR.Alias;J.isAlias=_r.isAlias;J.isCollection=_r.isCollection;J.isDocument=_r.isDocument;J.isMap=_r.isMap;J.isNode=_r.isNode;J.isPair=_r.isPair;J.isScalar=_r.isScalar;J.isSeq=_r.isSeq;J.Pair=KR.Pair;J.Scalar=YR.Scalar;J.YAMLMap=XR.YAMLMap;J.YAMLSeq=QR.YAMLSeq;J.CST=ZR;J.Lexer=eP.Lexer;J.LineCounter=tP.LineCounter;J.Parser=rP.Parser;J.parse=Ws.parse;J.parseAllDocuments=Ws.parseAllDocuments;J.parseDocument=Ws.parseDocument;J.stringify=Ws.stringify;J.visit=kg.visit;J.visitAsync=kg.visitAsync});import Nd from"path";function aP(e){return e.toLowerCase().startsWith(".env")}function Tt(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>aP(i))?"environment-file":r.some(i=>nP.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>iP.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}function bd(e,t){let r=Tt(t);if(r)return r;let i=Nd.resolve(e.projectRoot,...t.split("/")),n=Nd.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||i===Nd.resolve(e.configFile)?"native-runtime":null}var iP,nP,Ra=I(()=>{"use strict";iP=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),nP=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});function Ar(e){return e!==0&&e!==0n&&e!=="0"}function Qe(e,t){return Ar(e.dev)&&Ar(t.dev)&&Ar(e.ino)&&Ar(t.ino)}function G(e,t){let r=Ar(e.dev)&&Ar(t.dev);if(r&&e.dev!==t.dev)return!1;let i=Ar(e.ino)&&Ar(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var Pa=I(()=>{"use strict"});var jt=I(()=>{"use strict";Pa()});import{createHash as oP}from"node:crypto";import{promises as ht}from"node:fs";import Ze from"node:path";import{TextDecoder as sP}from"node:util";function kd(e,t){let r=Ze.relative(e,t);return r===""||!Ze.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ze.sep}`)}function cP(e){let t=Ze.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})||Ze.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let r=e.toLowerCase(),i=Tt(e);if(i||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${i??"native-runtime"}): ${e}`);return e}function lP(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function uP(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function zs(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Qe(r,i)?G(r,i):G(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Sg(e){let t=await ht.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await ht.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function dP(e,t){let r=Ze.resolve(e),i=Ze.resolve(t);if(!kd(r,i))throw new Error("Native artifact path is outside its root");let n=[await Sg(r)],a=r;for(let o of Ze.relative(r,i).split(Ze.sep).filter(Boolean)){a=Ze.join(a,o);let s=await Sg(a);if(!kd(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function Eg(e){for(let t of e){let r=await ht.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!uP(t,r)||await ht.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function ne(e){let t=cP(e.ref),r=e.maxBytes===null?null:lP(e.maxBytes??Sd),i=Ze.resolve(e.root,...t.split("/")),n=await dP(e.root,Ze.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await ht.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(r!==null&&a.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);let o=await ht.realpath(i);if(!kd(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await ht.open(i,"r");try{let[c,l,u]=await Promise.all([s.stat(),ht.lstat(i),ht.realpath(i)]);if(await Eg(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!zs(a,c)||!zs(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],p=0,f=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let k=r===null?f.length:r+1-p,N=await s.read(f,0,Math.min(f.length,k),null);if(N.bytesRead===0)break;if(p+=N.bytesRead,r!==null&&p>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);d.push(Buffer.from(f.subarray(0,N.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([s.stat(),ht.lstat(i),ht.realpath(i)]);if(await Eg(n),!h.isFile()||h.isSymbolicLink()||v!==o||!zs(c,m)||!zs(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(d,p),b;try{b=new sP("utf-8",{fatal:!0}).decode(g)}catch(k){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:k})}return{ref:t,size:p,hash:e.includeHash===!1?null:oP("sha256").update(g).digest("hex"),text:b}}finally{await s.close()}}var Sd,et=I(()=>{"use strict";Ra();jt();Sd=1024*1024});import{promises as xd}from"node:fs";async function Cd(e,t){let r;for(let i=0;i<=Ed.length;i+=1)try{return await e()}catch(n){r=n;let a=n.code;if(i===Ed.length||!pP.has(a??""))throw n;await new Promise(o=>setTimeout(o,Ed[i]))}throw r}async function Rd(e,t){await Cd(()=>xd.rename(e,t),`rename ${t}`)}async function Pd(e){await Cd(()=>xd.unlink(e),`unlink ${e}`)}async function _d(e,t){await Cd(()=>xd.link(e,t),`link ${t}`)}var pP,Ed,Ad=I(()=>{"use strict";pP=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),Ed=[50,100,200]});import{randomUUID as fP}from"crypto";import{promises as Ae}from"fs";import mt from"path";function Gs(e,t){let r=mt.relative(e,t);return r===""||!mt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${mt.sep}`)}function hP(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Js(e,t){return G({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function mP(e,t){return Js(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function xg(e){let t=await Ae.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 Ae.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Ki(e){for(let t of e){let r=await Ae.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!hP(t,r)||await Ae.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function vP(e,t,r){let[i,n]=await Promise.all([Ae.lstat(e),Ae.realpath(e),r?Ki(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!Js(i,t)||r&&!Gs(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function gP(e,t){let r=mt.resolve(e),i=mt.resolve(t);if(!Gs(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await xg(r)],a=mt.relative(r,i).split(mt.sep).filter(Boolean),o=r;for(let s of a){await Ki(n),o=mt.join(o,s);try{await Ae.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await xg(o);if(!Gs(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Ki(n),n}async function wP(e){let t;try{t=await Ae.open(e,"r"),await t.sync()}catch(r){let i=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw r}finally{await t?.close()}}async function yP(e,t,r={}){let i=mt.dirname(e),n=r.containedRoot?await gP(r.containedRoot,i):null;n||await Ae.mkdir(i,{recursive:!0});let a=mt.join(i,`.${mt.basename(e)}.${fP()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await Ae.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([Ae.lstat(a),Ae.realpath(a)]);if(await Ki(n),!l.isFile()||l.isSymbolicLink()||!Js(s,l)||!Gs(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(),!Js(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Native atomic write temporary file was not written");if(c=await vP(a,c,n),await r.beforeCommit?.(),n){await Ki(n);let l=await Ae.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!mP(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await _d(a,e),await Pd(a)):await Rd(a,e),await wP(i)}catch(l){if(await o?.close(),!n)await Ae.rm(a,{force:!0});else try{await Ki(n),await Ae.rm(a,{force:!0})}catch{}throw l}}async function $t(e,t,r={}){await yP(e,t,r)}async function Ie(e,t,r={}){await $t(e,JSON.stringify(t,null,2)+`
144
- `,r)}var ae=I(()=>{"use strict";Ad();jt()});function kP(e,t){return Id[e][t]}function Us(e){return Cg.get(e.trim().toLocaleLowerCase("en-US"))??null}function Rg(e){return Td.get(e.trim().toLocaleLowerCase("en-US"))??null}function Ks(e,t={}){let r=["outcome","scope","nonGoals","acceptanceExamples"];return t.compact||r.push("constraints","decisions","openQuestions","verificationExpectations"),r.map(i=>`# ${kP(e,i)}
145
- `).join(`
146
- `)}var Id,NP,bP,Cg,Td,pi=I(()=>{"use strict";Id={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:"验证预期"}},NP={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:"结论"}},bP={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:"结论"}},Cg=new Map,Td=new Map;for(let e of Object.keys(Id)){for(let[t,r]of Object.entries(Id[e]))Cg.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(NP[e]))Td.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(bP[e]))Td.set(r.toLocaleLowerCase("en-US"),t)}});import Ir from"path";function PP(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||Ir.posix.isAbsolute(r)||Ir.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be a project-relative path`);if(r===".")return[];let i=r.replaceAll("\\","/").split("/");if(i.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(i.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return i}function Yi(e){let t=PP(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Og(e,t="docs"){let r=e??t;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function Qs(e,t,r=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim().replaceAll("\\","/");if(i.length===0||Ir.posix.isAbsolute(i)||Ir.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be relative to its declared path base`);let n=i.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!r&&/[*?]/u.test(i))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function Zt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Hg(e,t,r){let i=e??t;if(i!=="en"&&i!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return i}function Zs(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>Ys)throw new Error(`${t} exceeds ${Ys} characters`);let r=0;for(let i=0;i<e.length;i+=1)e[i]==="?"?r+=1:e[i]==="*"&&(r+=1,e[i+1]==="*"&&(i+=1));if(r>Xs)throw new Error(`${t} contains more than ${Xs} wildcard tokens`);return e}function Tg(e,t,r){if(e===void 0)return[...r];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(i=>Zs(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function _a(e,t,r){let i=e??t;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${r} must be a positive integer`);return i}function jg(e,t,r){let i=_a(e,t,r);if(i>Math.floor(Number.MAX_SAFE_INTEGER/(1024*1024)))throw new Error(`${r} is too large to convert to bytes safely`);return i}function _P(e){if(e===void 0)return{...tt,include:[...tt.include],exclude:[...tt.exclude]};let t=Zt(e,"native.snapshot");return{include:Tg(t.include,"native.snapshot.include",tt.include),exclude:Tg(t.exclude,"native.snapshot.exclude",tt.exclude),max_files:_a(t.max_files,tt.max_files,"native.snapshot.max_files"),max_total_bytes:_a(t.max_total_bytes,tt.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:_a(t.max_duration_ms,tt.max_duration_ms,"native.snapshot.max_duration_ms"),max_selection_records:_a(t.max_selection_records,tt.max_selection_records,"native.snapshot.max_selection_records")}}function AP(e){if(e===void 0)return;let t=Zt(e,"native.pending_root_move"),r=t.id,i=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof r!="string"||!/^[a-f0-9-]{8,}$/u.test(r))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=Zt(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:r,fromArtifactRoot:Yi(i),toArtifactRoot:Yi(n),stage:a,...o?{cleanup:o}:{}}}function IP(e){if(e===void 0)return;let t=Zt(e,"native.finish");if(t.pull_request===void 0)return{};let r=Zt(t.pull_request,"native.finish.pull_request");if(r.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(r.command)||r.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(r.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let i=r.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(Ir.posix.isAbsolute(i[0])||Ir.win32.isAbsolute(i[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=r.timeout_ms??EP;if(!Number.isSafeInteger(n)||n<1||n>Ig)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Ig}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function TP(e,t={}){let r=Zt(e,"native"),i=r.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let n=r.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=r.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=r.max_verify_failures??$g;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=r.document_writes??"allow";if(s!=="allow"&&s!=="revert")throw new Error("native.document_writes must be allow or revert");let c=AP(r.pending_root_move),l=IP(r.finish);return{artifact_root:Yi(i),language:Hg(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,...s==="revert"?{document_writes:s}:{},snapshot:_P(r.snapshot),...l?{finish:l}:{},...c?{pending_root_move:c}:{}}}function jP(e){let t=Zt(e,"classic"),r=t.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let i=t.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");let a=t.document_evidence??"neutral";if(a!=="neutral"&&a!=="strict")throw new Error("classic.document_evidence must be neutral or strict");return{artifact_layout:Og(t.artifact_layout),language:Hg(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n,...a==="strict"?{document_evidence:a}:{}}}function $P(e){let r=Zt(e,"hook").allow_paths??[];if(!Array.isArray(r))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(r.map((i,n)=>Qs(i,`hook.allow_paths[${n}]`)))]}}function OP(e){if(e===void 0)return{...jd};let t=Zt(e,"memory"),r=t.learning??jd.learning,i=t.retrieval??jd.retrieval;if(typeof r!="boolean")throw new Error("memory.learning must be true or false");if(typeof i!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:r,retrieval:i}}function Od(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function HP(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||r.includes("\\")||r.includes("\0")||Ir.posix.isAbsolute(r)||Ir.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!r.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(r.length>Pg)throw new Error(`${t} exceeds ${Pg} characters`);let i=0;for(let n=0;n<r.length;n+=1)r[n]==="?"?i+=1:r[n]==="*"&&(i+=1,r[n+1]==="*"&&(n+=1));if(i>_g)throw new Error(`${t} contains more than ${_g} wildcard tokens`);return r}function DP(e){let t=Od(e,"knowledge.local"),r=t.include??[];if(!Array.isArray(r))throw new Error("knowledge.local.include must be an array");let i={include:[...new Set(r.map((n,a)=>HP(n,`knowledge.local.include[${a}]`)))],max_file_mb:jg(t.max_file_mb,Ag.max_file_mb,"knowledge.local.max_file_mb"),max_total_mb:jg(t.max_total_mb,Ag.max_total_mb,"knowledge.local.max_total_mb")};if(i.max_file_mb>i.max_total_mb)throw new Error("knowledge.local.max_file_mb must not exceed max_total_mb");return i}function BP(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let r=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),i=r==="localhost"||r==="127.0.0.1"||r==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&i))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function FP(e){let t=Od(e,"knowledge.remote"),r=BP(t.endpoint),i=t.token_env;if(i!==void 0&&(typeof i!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(i)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:r,...i===void 0?{}:{token_env:i},...n===void 0?{}:{scope:n},timeout_ms:a}}function LP(e){if(e===void 0)return{...SP};let t=Od(e,"knowledge"),r=t.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let i=t.local===void 0?void 0:DP(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:FP(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:r,...i?{local:i}:{},remote:n}}function qP(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function MP(e,t,r,i,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let u=e.workflows??[e.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(p=>p!=="native"&&p!=="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:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function Ia(e,t={}){let r=(0,$d.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${r.errors[0].message}`);let i=r.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=i,a=qP(n.ambient_resume),o=n.hook===void 0?void 0:$P(n.hook),s=OP(n.memory),c=LP(n.knowledge),l=n.native===void 0?void 0:TP(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:jP(n.classic),d=MP(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}:{}}}var $d,Aa,Ys,Xs,Pg,_g,$g,jd,Ag,SP,EP,Ig,xP,CP,RP,tt,Tr=I(()=>{"use strict";$d=Kt(It(),1),Aa=Number.MAX_SAFE_INTEGER,Ys=1024,Xs=64,Pg=1024,_g=64,$g=5,jd={learning:!0,retrieval:!0},Ag={include:[],max_file_mb:1,max_total_mb:32},SP={provider:"local"},EP=12e4,Ig=6e5,xP=[".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/**"],CP=["**/.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"],RP=[...xP,...CP].sort((e,t)=>e.localeCompare(t,"en")),tt={include:["**/*"],exclude:[...RP],max_files:1e4,max_total_bytes:1024*1024*1024,max_duration_ms:6e4,max_selection_records:2e4}});import{constants as ec,promises as fi}from"fs";function Hd(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Dg(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function Ta(e){return{dev:e.dev,ino:e.ino,birthtime:Hd(e)}}function tc(e,t){let r=Ta(e),i=Ta(t);return Qe(r,i)?G(r,i):G(r,i)&&Hd(e)===Hd(t)&&Dg(e)===Dg(t)&&e.size===t.size}async function Xi(e,t,r={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let i=r.label??"file",n=r.bigint===!0,a=await fi.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Ot("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Ot("too-large",`${i} exceeds ${t} bytes`);let o=await fi.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:Ta(a)});let s=process.platform==="win32"?ec.O_RDONLY:ec.O_RDONLY|ec.O_NOFOLLOW|ec.O_NONBLOCK,c;try{c=await fi.open(e,s)}catch(l){throw l.code==="ELOOP"?new Ot("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),fi.lstat(e,{bigint:n}),fi.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!tc(a,l)||!tc(a,u))throw new Ot("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:Ta(l)}),await r.hooks?.afterOpen?.();let p=[],f=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let b=t+1-f,{bytesRead:k}=await c.read(m,0,Math.min(m.length,b),null);if(k===0)break;if(f+=k,f>t)throw new Ot("too-large",`${i} exceeds ${t} bytes`);p.push(Buffer.from(m.subarray(0,k)))}await r.hooks?.beforeFinalCheck?.();let[h,v,g]=await Promise.all([c.stat({bigint:n}),fi.lstat(e,{bigint:n}),fi.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||g!==o||!tc(a,h)||!tc(a,v))throw new Ot("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:g,identity:Ta(h)}),{bytes:Buffer.concat(p,f),stat:h,realPath:g}}finally{await c.close()}}var Ot,ja=I(()=>{"use strict";Pa();Ot=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as rc}from"fs";import jr from"path";function VP(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Dd(e,t){let r=jr.relative(e,t);return r===""||!jr.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${jr.sep}`)}async function Bg(e,t){let r=jr.resolve(e),i=await rc.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return rc.realpath(r)}async function Fg(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=jr.join(n,r[a]);let o;try{o=await rc.lstat(n)}catch(u){if(VP(u))return{exists:!1,kind:"missing"};throw u}let s=jr.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${i.label} crosses a symbolic link or junction at ${s}`);let c=a===r.length-1;if(!c&&!o.isDirectory())throw new Error(`${i.label} ancestor ${s} must be a real directory`);if(c&&(i.expected==="file"&&!o.isFile()||i.expected==="directory"&&!o.isDirectory()||i.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${i.label} must be a real ${i.expected}`);let l=await rc.realpath(n);if(!Dd(t,l))throw new Error(`${i.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function Qi(e,t,r){let i=Qs(t,r.label),n=jr.resolve(e),a=await Bg(n,r.label),o=i.split("/"),s=jr.resolve(n,...o);if(!Dd(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await Fg(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function Ht(e,t,r,i){let n=await Qi(e,t,{label:i.label,expected:"file"});if(!n.exists){let o=new Error(`${i.label} does not exist`);throw o.code="ENOENT",o}let a=await Bg(n.projectRoot,i.label);return Xi(n.target,r,{...i,verify:async(o,s)=>{if(!Dd(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Fg(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var er=I(()=>{"use strict";ja();Tr()});import{createHash as WP}from"crypto";function zP(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function ic(e,t={}){return(await nc(e,t)).document}async function GP(e){try{return(await Ht(e,$a,Aa,{label:$a})).bytes}catch(t){if(zP(t))return null;throw t}}function JP(e){return e?{exists:!0,sha256:WP("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function nc(e,t={}){let r=await GP(e);return{document:r?Ia(r.toString("utf8"),t):null,identity:JP(r)}}async function Bd(e){return(await ic(e))?.config??null}var $a,Zi=I(()=>{"use strict";Tr();er();$a=".comet/config.yaml"});var en=I(()=>{"use strict";Ad();Pa()});var oL,Fd=I(()=>{"use strict";en();Zi();er();oL=16*1024});var Md=I(()=>{"use strict";en();Tr();Zi();er();Fd()});import{existsSync as qg,promises as $r}from"fs";import B from"path";import QP from"os";async function Vd(e){try{return await $r.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function e_(e){try{let t=await $r.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function rn(e,t){let r=B.relative(e,t);return r===""||!B.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${B.sep}`)}async function tn(e){let t=[],r=e;for(;!await Vd(r);){let n=B.dirname(r);if(n===r)break;t.push(B.basename(r)),r=n}let i=await $r.realpath(r);return B.resolve(i,...t.reverse())}async function Wd(e){try{return(await $r.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Gd(e){let t=B.resolve(e);try{(await $r.stat(t)).isDirectory()||(t=B.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=B.resolve(QP.homedir());for(;;){if(!(t===i&&r!==i)){let o=B.join(t,...zd.split("/")),s=t===r||await e_(o);if(await Vd(o)&&s)return t}if(await Vd(B.join(t,".git")))return t;let a=B.dirname(t);if(a===t)return r;t=a}}function Jd(e){return Yi(e)}async function t_(e,t){let r=Jd(t),i=B.resolve(e,...r.split("/")),n=await $r.realpath(e),a=await tn(i);if(!rn(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function tr(e,t){let r=Jd(t),i=await t_(e,r),n=B.join(i,"comet");if(await Wd(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([tn(i),tn(n)]);if(!rn(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=B.resolve(e),c=B.join(s,".comet","runtime","native");if(await Wd(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([$r.realpath(s),tn(c)]);if(!rn(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:B.join(e,...zd.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:B.join(n,"specs"),changesDir:B.join(n,"changes"),archiveDir:B.join(n,"archive"),runtimeDir:c,changesRuntimeDir:B.join(c,"changes"),locksDir:B.join(c,"locks"),transactionsDir:B.join(c,"transactions")}}function Ud(e){if(!ZP.test(e))throw new Error(`Invalid Native change name: ${e}`)}function vt(e,t){Ud(t);let r=B.join(e.changesRuntimeDir,t);if(!q(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function Vg(e,t){Ud(t);let r=B.join(e.changesDir,t,"runtime");if(!q(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function Y(e,t){let r=vt(e,t);if(qg(r))return r;let i=Vg(e,t);return qg(i)?i:r}function Ha(e,t){Ud(t);let r=B.join(e.changesDir,t),i=Y(e,t);return{artifactRoot:e.artifactRoot,nativeRoot:e.nativeRoot,changeDir:r,briefPath:B.join(r,"brief.md"),childrenPath:B.join(r,"children.yaml"),specsDir:B.join(r,"specs"),verificationPath:B.join(r,"verification.md"),statePath:B.join(r,"comet-state.yaml"),runtimeDir:i,runtimeStatePath:B.join(i,"state.json")}}async function Mg(e){try{let t=await $r.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function Kd(e,t){let r=vt(e,t),i=Vg(e,t),[n,a]=await Promise.all([Mg(r),Mg(i)]);return n==="invalid"?{status:"invalid",layout:"project-local",path:r,message:"Native Runtime path must be a real directory"}:a==="invalid"?{status:"invalid",layout:"legacy",path:i,message:"Legacy Native Runtime path must be a real directory"}:n==="directory"&&a==="directory"?{status:"invalid",layout:"project-local",path:r,message:"Both project-local and legacy Native Runtime directories exist"}:n==="directory"?{status:"available",layout:"project-local",path:r}:a==="directory"?{status:"available",layout:"legacy",path:i}:{status:"missing",layout:"missing",path:r}}function Or(e,t){if(!t.startsWith("runtime/")||B.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let r=B.resolve(e,...t.slice(8).split("/"));if(!q(e,r))throw new Error(`Native Runtime ref escaped: ${t}`);return r}function we(e,t){let r=B.resolve(t);if(q(e.runtimeDir,r))return e.runtimeDir;if(q(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function q(e,t){return rn(B.resolve(e),B.resolve(t))}async function K(e,t){let r=B.resolve(e),i=B.resolve(t);if(!rn(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await Wd(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([tn(r),tn(i)]);if(!rn(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}var zd,ZP,U=I(()=>{"use strict";Tr();zd=".comet/config.yaml",ZP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});async function Te(e){let t=(await ic(e))?.config??null;return t?.native?t:null}var Yd,ac,Je=I(()=>{"use strict";Tr();Zi();Md();ae();U();Yd=tt,ac=Zs});import{createHash as i_,randomUUID as PL}from"node:crypto";var n_,AL,zg=I(()=>{"use strict";Di();n_=`using System;
143
+ `,r)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=Ws(t),i=Ki(r);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let r=Ws(t),i=Ki(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,r){return this.type!=="comment"||this.indent<=r?!1:t.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Ng.Parser=Nd});var xg=R(Ra=>{"use strict";var bg=sd(),KR=wa(),Ca=ba(),YR=au(),XR=W(),QR=yd(),kg=bd();function Sg(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new QR.LineCounter||null,prettyErrors:t}}function ZR(e,t={}){let{lineCounter:r,prettyErrors:i}=Sg(t),n=new kg.Parser(r?.addNewLine),a=new bg.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach(Ca.prettifyError(e,r)),s.warnings.forEach(Ca.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Eg(e,t={}){let{lineCounter:r,prettyErrors:i}=Sg(t),n=new kg.Parser(r?.addNewLine),a=new bg.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 Ca.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(Ca.prettifyError(e,r)),o.warnings.forEach(Ca.prettifyError(e,r))),o}function eP(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=Eg(e,r);if(!n)return null;if(n.warnings.forEach(a=>YR.warn(n.options.logLevel,a)),n.errors.length>0){if(n.options.logLevel!=="silent")throw n.errors[0];n.errors=[]}return n.toJS(Object.assign({reviver:i},r))}function tP(e,t,r){let i=null;if(typeof t=="function"||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r=="string"&&(r=r.length),typeof r=="number"){let n=Math.round(r);r=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=r??t??{};if(!n)return}return XR.isDocument(e)&&!i?e.toString(r):new KR.Document(e,i,r).toString(r)}Ra.parse=eP;Ra.parseAllDocuments=ZR;Ra.parseDocument=Eg;Ra.stringify=tP});var It=R(J=>{"use strict";var rP=sd(),iP=wa(),nP=qu(),kd=ba(),aP=ra(),_r=W(),oP=Er(),sP=de(),cP=Cr(),lP=Rr(),uP=Ms(),dP=gd(),pP=yd(),fP=bd(),Gs=xg(),Cg=Qn();J.Composer=rP.Composer;J.Document=iP.Document;J.Schema=nP.Schema;J.YAMLError=kd.YAMLError;J.YAMLParseError=kd.YAMLParseError;J.YAMLWarning=kd.YAMLWarning;J.Alias=aP.Alias;J.isAlias=_r.isAlias;J.isCollection=_r.isCollection;J.isDocument=_r.isDocument;J.isMap=_r.isMap;J.isNode=_r.isNode;J.isPair=_r.isPair;J.isScalar=_r.isScalar;J.isSeq=_r.isSeq;J.Pair=oP.Pair;J.Scalar=sP.Scalar;J.YAMLMap=cP.YAMLMap;J.YAMLSeq=lP.YAMLSeq;J.CST=uP;J.Lexer=dP.Lexer;J.LineCounter=pP.LineCounter;J.Parser=fP.Parser;J.parse=Gs.parse;J.parseAllDocuments=Gs.parseAllDocuments;J.parseDocument=Gs.parseDocument;J.stringify=Gs.stringify;J.visit=Cg.visit;J.visitAsync=Cg.visitAsync});import Sd from"path";function vP(e){return e.toLowerCase().startsWith(".env")}function Tt(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>vP(i))?"environment-file":r.some(i=>mP.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>hP.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}function Ed(e,t){let r=Tt(t);if(r)return r;let i=Sd.resolve(e.projectRoot,...t.split("/")),n=Sd.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||i===Sd.resolve(e.configFile)?"native-runtime":null}var hP,mP,Pa=I(()=>{"use strict";hP=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),mP=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});function Ar(e){return e!==0&&e!==0n&&e!=="0"}function Qe(e,t){return Ar(e.dev)&&Ar(t.dev)&&Ar(e.ino)&&Ar(t.ino)}function G(e,t){let r=Ar(e.dev)&&Ar(t.dev);if(r&&e.dev!==t.dev)return!1;let i=Ar(e.ino)&&Ar(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var _a=I(()=>{"use strict"});var jt=I(()=>{"use strict";_a()});import{createHash as gP}from"node:crypto";import{promises as ht}from"node:fs";import Ze from"node:path";import{TextDecoder as wP}from"node:util";function xd(e,t){let r=Ze.relative(e,t);return r===""||!Ze.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ze.sep}`)}function yP(e){let t=Ze.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})||Ze.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let r=e.toLowerCase(),i=Tt(e);if(i||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${i??"native-runtime"}): ${e}`);return e}function NP(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function bP(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Js(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Qe(r,i)?G(r,i):G(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Rg(e){let t=await ht.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await ht.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function kP(e,t){let r=Ze.resolve(e),i=Ze.resolve(t);if(!xd(r,i))throw new Error("Native artifact path is outside its root");let n=[await Rg(r)],a=r;for(let o of Ze.relative(r,i).split(Ze.sep).filter(Boolean)){a=Ze.join(a,o);let s=await Rg(a);if(!xd(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function Pg(e){for(let t of e){let r=await ht.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!bP(t,r)||await ht.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function ne(e){let t=yP(e.ref),r=e.maxBytes===null?null:NP(e.maxBytes??Cd),i=Ze.resolve(e.root,...t.split("/")),n=await kP(e.root,Ze.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await ht.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(r!==null&&a.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);let o=await ht.realpath(i);if(!xd(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await ht.open(i,"r");try{let[c,l,u]=await Promise.all([s.stat(),ht.lstat(i),ht.realpath(i)]);if(await Pg(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!Js(a,c)||!Js(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],p=0,f=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let k=r===null?f.length:r+1-p,N=await s.read(f,0,Math.min(f.length,k),null);if(N.bytesRead===0)break;if(p+=N.bytesRead,r!==null&&p>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);d.push(Buffer.from(f.subarray(0,N.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([s.stat(),ht.lstat(i),ht.realpath(i)]);if(await Pg(n),!h.isFile()||h.isSymbolicLink()||v!==o||!Js(c,m)||!Js(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(d,p),b;try{b=new wP("utf-8",{fatal:!0}).decode(g)}catch(k){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:k})}return{ref:t,size:p,hash:e.includeHash===!1?null:gP("sha256").update(g).digest("hex"),text:b}}finally{await s.close()}}var Cd,et=I(()=>{"use strict";Pa();jt();Cd=1024*1024});import{promises as Pd}from"node:fs";async function _d(e,t){let r;for(let i=0;i<=Rd.length;i+=1)try{return await e()}catch(n){r=n;let a=n.code;if(i===Rd.length||!SP.has(a??""))throw n;await new Promise(o=>setTimeout(o,Rd[i]))}throw r}async function Ad(e,t){await _d(()=>Pd.rename(e,t),`rename ${t}`)}async function Id(e){await _d(()=>Pd.unlink(e),`unlink ${e}`)}async function Td(e,t){await _d(()=>Pd.link(e,t),`link ${t}`)}var SP,Rd,jd=I(()=>{"use strict";SP=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),Rd=[50,100,200]});import{randomUUID as EP}from"crypto";import{promises as Ae}from"fs";import mt from"path";function Us(e,t){let r=mt.relative(e,t);return r===""||!mt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${mt.sep}`)}function xP(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Ks(e,t){return G({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function CP(e,t){return Ks(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function _g(e){let t=await Ae.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 Ae.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Yi(e){for(let t of e){let r=await Ae.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!xP(t,r)||await Ae.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function RP(e,t,r){let[i,n]=await Promise.all([Ae.lstat(e),Ae.realpath(e),r?Yi(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!Ks(i,t)||r&&!Us(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function PP(e,t){let r=mt.resolve(e),i=mt.resolve(t);if(!Us(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await _g(r)],a=mt.relative(r,i).split(mt.sep).filter(Boolean),o=r;for(let s of a){await Yi(n),o=mt.join(o,s);try{await Ae.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await _g(o);if(!Us(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Yi(n),n}async function _P(e){let t;try{t=await Ae.open(e,"r"),await t.sync()}catch(r){let i=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw r}finally{await t?.close()}}async function AP(e,t,r={}){let i=mt.dirname(e),n=r.containedRoot?await PP(r.containedRoot,i):null;n||await Ae.mkdir(i,{recursive:!0});let a=mt.join(i,`.${mt.basename(e)}.${EP()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await Ae.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([Ae.lstat(a),Ae.realpath(a)]);if(await Yi(n),!l.isFile()||l.isSymbolicLink()||!Ks(s,l)||!Us(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(),!Ks(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Native atomic write temporary file was not written");if(c=await RP(a,c,n),await r.beforeCommit?.(),n){await Yi(n);let l=await Ae.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!CP(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await Td(a,e),await Id(a)):await Ad(a,e),await _P(i)}catch(l){if(await o?.close(),!n)await Ae.rm(a,{force:!0});else try{await Yi(n),await Ae.rm(a,{force:!0})}catch{}throw l}}async function $t(e,t,r={}){await AP(e,t,r)}async function Ie(e,t,r={}){await $t(e,JSON.stringify(t,null,2)+`
144
+ `,r)}var ae=I(()=>{"use strict";jd();jt()});function Ag(e,t){return $d[e][t]}function Ys(e){return Ig.get(e.trim().toLocaleLowerCase("en-US"))??null}function $g(e){return Od.get(e.trim().toLocaleLowerCase("en-US"))??null}function jP(e){return pi[e].section}function $P(e,t){return pi[e].subsections[t]}function Og(e){return`${pi.en.subsections[e]}/${pi["zh-CN"].subsections[e]}`}function Hg(e){return Tg.has(e.trim().toLocaleLowerCase("en-US"))}function Dg(e){return jg.get(e.trim().toLocaleLowerCase("en-US"))??null}function Xs(e,t={}){let r=["outcome","scope","nonGoals","acceptanceExamples"];return t.compact||r.push("constraints","decisions","openQuestions","verificationExpectations"),r.map(i=>{if(i!=="scope")return`# ${Ag(e,i)}
145
+ `;let n=[`# ${Ag(e,i)}
146
+ `];n.push(`## ${jP(e)}
147
+ `);for(let a of Hd)n.push(`### ${$P(e,a)}
148
+ `);return n.join(`
149
+ `)}).join(`
150
+ `)}var Hd,$d,IP,TP,Ig,Od,Tg,jg,pi,fi=I(()=>{"use strict";Hd=["created","modified","deleted","notCreated"],$d={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:"验证预期"}},IP={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:"结论"}},TP={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:"结论"}},Ig=new Map,Od=new Map,Tg=new Set,jg=new Map,pi={en:{section:"Directory structure",subsections:{created:"Created",modified:"Modified",deleted:"Deleted",notCreated:"Not created"}},"zh-CN":{section:"目录结构",subsections:{created:"新建",modified:"修改",deleted:"删除",notCreated:"明确不建"}}};for(let e of Object.keys($d)){for(let[t,r]of Object.entries($d[e]))Ig.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(IP[e]))Od.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(TP[e]))Od.set(r.toLocaleLowerCase("en-US"),t)}for(let e of Object.keys(pi)){Tg.add(pi[e].section.toLocaleLowerCase("en-US"));for(let[t,r]of Object.entries(pi[e].subsections))jg.set(r.toLocaleLowerCase("en-US"),t)}});import Ir from"path";function LP(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||Ir.posix.isAbsolute(r)||Ir.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be a project-relative path`);if(r===".")return[];let i=r.replaceAll("\\","/").split("/");if(i.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(i.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return i}function Xi(e){let t=LP(e,"native.artifact_root");return t.length===0?".":t.join("/")}function zg(e,t="docs"){let r=e??t;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function ec(e,t,r=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim().replaceAll("\\","/");if(i.length===0||Ir.posix.isAbsolute(i)||Ir.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be relative to its declared path base`);let n=i.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!r&&/[*?]/u.test(i))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function Zt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Gg(e,t,r){let i=e??t;if(i!=="en"&&i!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return i}function tc(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>Qs)throw new Error(`${t} exceeds ${Qs} characters`);let r=0;for(let i=0;i<e.length;i+=1)e[i]==="?"?r+=1:e[i]==="*"&&(r+=1,e[i+1]==="*"&&(i+=1));if(r>Zs)throw new Error(`${t} contains more than ${Zs} wildcard tokens`);return e}function Mg(e,t,r){if(e===void 0)return[...r];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(i=>tc(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function Aa(e,t,r){let i=e??t;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${r} must be a positive integer`);return i}function Vg(e,t,r){let i=Aa(e,t,r);if(i>Math.floor(Number.MAX_SAFE_INTEGER/(1024*1024)))throw new Error(`${r} is too large to convert to bytes safely`);return i}function qP(e){if(e===void 0)return{...tt,include:[...tt.include],exclude:[...tt.exclude]};let t=Zt(e,"native.snapshot");return{include:Mg(t.include,"native.snapshot.include",tt.include),exclude:Mg(t.exclude,"native.snapshot.exclude",tt.exclude),max_files:Aa(t.max_files,tt.max_files,"native.snapshot.max_files"),max_total_bytes:Aa(t.max_total_bytes,tt.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Aa(t.max_duration_ms,tt.max_duration_ms,"native.snapshot.max_duration_ms"),max_selection_records:Aa(t.max_selection_records,tt.max_selection_records,"native.snapshot.max_selection_records")}}function MP(e){if(e===void 0)return;let t=Zt(e,"native.pending_root_move"),r=t.id,i=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof r!="string"||!/^[a-f0-9-]{8,}$/u.test(r))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=Zt(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:r,fromArtifactRoot:Xi(i),toArtifactRoot:Xi(n),stage:a,...o?{cleanup:o}:{}}}function VP(e){if(e===void 0)return;let t=Zt(e,"native.finish");if(t.pull_request===void 0)return{};let r=Zt(t.pull_request,"native.finish.pull_request");if(r.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(r.command)||r.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(r.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let i=r.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(Ir.posix.isAbsolute(i[0])||Ir.win32.isAbsolute(i[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=r.timeout_ms??HP;if(!Number.isSafeInteger(n)||n<1||n>qg)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${qg}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function WP(e,t={}){let r=Zt(e,"native"),i=r.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let n=r.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=r.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=r.max_verify_failures??Wg;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=r.document_writes??"allow";if(s!=="allow"&&s!=="revert")throw new Error("native.document_writes must be allow or revert");let c=MP(r.pending_root_move),l=VP(r.finish);return{artifact_root:Xi(i),language:Gg(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,...s==="revert"?{document_writes:s}:{},snapshot:qP(r.snapshot),...l?{finish:l}:{},...c?{pending_root_move:c}:{}}}function zP(e){let t=Zt(e,"classic"),r=t.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let i=t.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");let a=t.document_evidence??"neutral";if(a!=="neutral"&&a!=="strict")throw new Error("classic.document_evidence must be neutral or strict");return{artifact_layout:zg(t.artifact_layout),language:Gg(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n,...a==="strict"?{document_evidence:a}:{}}}function GP(e){let r=Zt(e,"hook").allow_paths??[];if(!Array.isArray(r))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(r.map((i,n)=>ec(i,`hook.allow_paths[${n}]`)))]}}function JP(e){if(e===void 0)return{...Dd};let t=Zt(e,"memory"),r=t.learning??Dd.learning,i=t.retrieval??Dd.retrieval;if(typeof r!="boolean")throw new Error("memory.learning must be true or false");if(typeof i!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:r,retrieval:i}}function Fd(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function UP(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||r.includes("\\")||r.includes("\0")||Ir.posix.isAbsolute(r)||Ir.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!r.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(r.length>Bg)throw new Error(`${t} exceeds ${Bg} characters`);let i=0;for(let n=0;n<r.length;n+=1)r[n]==="?"?i+=1:r[n]==="*"&&(i+=1,r[n+1]==="*"&&(n+=1));if(i>Fg)throw new Error(`${t} contains more than ${Fg} wildcard tokens`);return r}function KP(e){let t=Fd(e,"knowledge.local"),r=t.include??[];if(!Array.isArray(r))throw new Error("knowledge.local.include must be an array");let i={include:[...new Set(r.map((n,a)=>UP(n,`knowledge.local.include[${a}]`)))],max_file_mb:Vg(t.max_file_mb,Lg.max_file_mb,"knowledge.local.max_file_mb"),max_total_mb:Vg(t.max_total_mb,Lg.max_total_mb,"knowledge.local.max_total_mb")};if(i.max_file_mb>i.max_total_mb)throw new Error("knowledge.local.max_file_mb must not exceed max_total_mb");return i}function YP(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let r=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),i=r==="localhost"||r==="127.0.0.1"||r==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&i))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function XP(e){let t=Fd(e,"knowledge.remote"),r=YP(t.endpoint),i=t.token_env;if(i!==void 0&&(typeof i!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(i)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:r,...i===void 0?{}:{token_env:i},...n===void 0?{}:{scope:n},timeout_ms:a}}function QP(e){if(e===void 0)return{...OP};let t=Fd(e,"knowledge"),r=t.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let i=t.local===void 0?void 0:KP(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:XP(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:r,...i?{local:i}:{},remote:n}}function ZP(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function e_(e,t,r,i,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let u=e.workflows??[e.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(p=>p!=="native"&&p!=="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:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function Ta(e,t={}){let r=(0,Bd.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${r.errors[0].message}`);let i=r.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=i,a=ZP(n.ambient_resume),o=n.hook===void 0?void 0:GP(n.hook),s=JP(n.memory),c=QP(n.knowledge),l=n.native===void 0?void 0:WP(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:zP(n.classic),d=e_(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}:{}}}var Bd,Ia,Qs,Zs,Bg,Fg,Wg,Dd,Lg,OP,HP,qg,DP,BP,FP,tt,Tr=I(()=>{"use strict";Bd=Kt(It(),1),Ia=Number.MAX_SAFE_INTEGER,Qs=1024,Zs=64,Bg=1024,Fg=64,Wg=5,Dd={learning:!0,retrieval:!0},Lg={include:[],max_file_mb:1,max_total_mb:32},OP={provider:"local"},HP=12e4,qg=6e5,DP=[".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/**"],BP=["**/.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"],FP=[...DP,...BP].sort((e,t)=>e.localeCompare(t,"en")),tt={include:["**/*"],exclude:[...FP],max_files:1e4,max_total_bytes:1024*1024*1024,max_duration_ms:6e4,max_selection_records:2e4}});import{constants as rc,promises as hi}from"fs";function Ld(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Jg(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function ja(e){return{dev:e.dev,ino:e.ino,birthtime:Ld(e)}}function ic(e,t){let r=ja(e),i=ja(t);return Qe(r,i)?G(r,i):G(r,i)&&Ld(e)===Ld(t)&&Jg(e)===Jg(t)&&e.size===t.size}async function Qi(e,t,r={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let i=r.label??"file",n=r.bigint===!0,a=await hi.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Ot("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Ot("too-large",`${i} exceeds ${t} bytes`);let o=await hi.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:ja(a)});let s=process.platform==="win32"?rc.O_RDONLY:rc.O_RDONLY|rc.O_NOFOLLOW|rc.O_NONBLOCK,c;try{c=await hi.open(e,s)}catch(l){throw l.code==="ELOOP"?new Ot("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),hi.lstat(e,{bigint:n}),hi.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!ic(a,l)||!ic(a,u))throw new Ot("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:ja(l)}),await r.hooks?.afterOpen?.();let p=[],f=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let b=t+1-f,{bytesRead:k}=await c.read(m,0,Math.min(m.length,b),null);if(k===0)break;if(f+=k,f>t)throw new Ot("too-large",`${i} exceeds ${t} bytes`);p.push(Buffer.from(m.subarray(0,k)))}await r.hooks?.beforeFinalCheck?.();let[h,v,g]=await Promise.all([c.stat({bigint:n}),hi.lstat(e,{bigint:n}),hi.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||g!==o||!ic(a,h)||!ic(a,v))throw new Ot("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:g,identity:ja(h)}),{bytes:Buffer.concat(p,f),stat:h,realPath:g}}finally{await c.close()}}var Ot,$a=I(()=>{"use strict";_a();Ot=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as nc}from"fs";import jr from"path";function t_(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function qd(e,t){let r=jr.relative(e,t);return r===""||!jr.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${jr.sep}`)}async function Ug(e,t){let r=jr.resolve(e),i=await nc.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return nc.realpath(r)}async function Kg(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=jr.join(n,r[a]);let o;try{o=await nc.lstat(n)}catch(u){if(t_(u))return{exists:!1,kind:"missing"};throw u}let s=jr.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${i.label} crosses a symbolic link or junction at ${s}`);let c=a===r.length-1;if(!c&&!o.isDirectory())throw new Error(`${i.label} ancestor ${s} must be a real directory`);if(c&&(i.expected==="file"&&!o.isFile()||i.expected==="directory"&&!o.isDirectory()||i.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${i.label} must be a real ${i.expected}`);let l=await nc.realpath(n);if(!qd(t,l))throw new Error(`${i.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function Zi(e,t,r){let i=ec(t,r.label),n=jr.resolve(e),a=await Ug(n,r.label),o=i.split("/"),s=jr.resolve(n,...o);if(!qd(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await Kg(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function Ht(e,t,r,i){let n=await Zi(e,t,{label:i.label,expected:"file"});if(!n.exists){let o=new Error(`${i.label} does not exist`);throw o.code="ENOENT",o}let a=await Ug(n.projectRoot,i.label);return Qi(n.target,r,{...i,verify:async(o,s)=>{if(!qd(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Kg(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var er=I(()=>{"use strict";$a();Tr()});import{createHash as r_}from"crypto";function i_(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function ac(e,t={}){return(await oc(e,t)).document}async function n_(e){try{return(await Ht(e,Oa,Ia,{label:Oa})).bytes}catch(t){if(i_(t))return null;throw t}}function a_(e){return e?{exists:!0,sha256:r_("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function oc(e,t={}){let r=await n_(e);return{document:r?Ta(r.toString("utf8"),t):null,identity:a_(r)}}async function Md(e){return(await ac(e))?.config??null}var Oa,en=I(()=>{"use strict";Tr();er();Oa=".comet/config.yaml"});var tn=I(()=>{"use strict";jd();_a()});var yL,Vd=I(()=>{"use strict";tn();en();er();yL=16*1024});var Gd=I(()=>{"use strict";tn();Tr();en();er();Vd()});import{existsSync as Xg,promises as $r}from"fs";import B from"path";import u_ from"os";async function Jd(e){try{return await $r.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function p_(e){try{let t=await $r.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function nn(e,t){let r=B.relative(e,t);return r===""||!B.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${B.sep}`)}async function rn(e){let t=[],r=e;for(;!await Jd(r);){let n=B.dirname(r);if(n===r)break;t.push(B.basename(r)),r=n}let i=await $r.realpath(r);return B.resolve(i,...t.reverse())}async function Ud(e){try{return(await $r.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Yd(e){let t=B.resolve(e);try{(await $r.stat(t)).isDirectory()||(t=B.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=B.resolve(u_.homedir());for(;;){if(!(t===i&&r!==i)){let o=B.join(t,...Kd.split("/")),s=t===r||await p_(o);if(await Jd(o)&&s)return t}if(await Jd(B.join(t,".git")))return t;let a=B.dirname(t);if(a===t)return r;t=a}}function Xd(e){return Xi(e)}async function f_(e,t){let r=Xd(t),i=B.resolve(e,...r.split("/")),n=await $r.realpath(e),a=await rn(i);if(!nn(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function tr(e,t){let r=Xd(t),i=await f_(e,r),n=B.join(i,"comet");if(await Ud(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([rn(i),rn(n)]);if(!nn(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=B.resolve(e),c=B.join(s,".comet","runtime","native");if(await Ud(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([$r.realpath(s),rn(c)]);if(!nn(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:B.join(e,...Kd.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:B.join(n,"specs"),changesDir:B.join(n,"changes"),archiveDir:B.join(n,"archive"),runtimeDir:c,changesRuntimeDir:B.join(c,"changes"),locksDir:B.join(c,"locks"),transactionsDir:B.join(c,"transactions")}}function Qd(e){if(!d_.test(e))throw new Error(`Invalid Native change name: ${e}`)}function vt(e,t){Qd(t);let r=B.join(e.changesRuntimeDir,t);if(!q(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function Zg(e,t){Qd(t);let r=B.join(e.changesDir,t,"runtime");if(!q(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function Y(e,t){let r=vt(e,t);if(Xg(r))return r;let i=Zg(e,t);return Xg(i)?i:r}function Da(e,t){Qd(t);let r=B.join(e.changesDir,t),i=Y(e,t);return{artifactRoot:e.artifactRoot,nativeRoot:e.nativeRoot,changeDir:r,briefPath:B.join(r,"brief.md"),childrenPath:B.join(r,"children.yaml"),specsDir:B.join(r,"specs"),verificationPath:B.join(r,"verification.md"),statePath:B.join(r,"comet-state.yaml"),runtimeDir:i,runtimeStatePath:B.join(i,"state.json")}}async function Qg(e){try{let t=await $r.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function Zd(e,t){let r=vt(e,t),i=Zg(e,t),[n,a]=await Promise.all([Qg(r),Qg(i)]);return n==="invalid"?{status:"invalid",layout:"project-local",path:r,message:"Native Runtime path must be a real directory"}:a==="invalid"?{status:"invalid",layout:"legacy",path:i,message:"Legacy Native Runtime path must be a real directory"}:n==="directory"&&a==="directory"?{status:"invalid",layout:"project-local",path:r,message:"Both project-local and legacy Native Runtime directories exist"}:n==="directory"?{status:"available",layout:"project-local",path:r}:a==="directory"?{status:"available",layout:"legacy",path:i}:{status:"missing",layout:"missing",path:r}}function Or(e,t){if(!t.startsWith("runtime/")||B.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let r=B.resolve(e,...t.slice(8).split("/"));if(!q(e,r))throw new Error(`Native Runtime ref escaped: ${t}`);return r}function we(e,t){let r=B.resolve(t);if(q(e.runtimeDir,r))return e.runtimeDir;if(q(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function q(e,t){return nn(B.resolve(e),B.resolve(t))}async function K(e,t){let r=B.resolve(e),i=B.resolve(t);if(!nn(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await Ud(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([rn(r),rn(i)]);if(!nn(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}var Kd,d_,U=I(()=>{"use strict";Tr();Kd=".comet/config.yaml",d_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});async function Te(e){let t=(await ac(e))?.config??null;return t?.native?t:null}var ep,sc,Je=I(()=>{"use strict";Tr();en();Gd();ae();U();ep=tt,sc=tc});import{createHash as m_,randomUUID as qL}from"node:crypto";var v_,VL,tw=I(()=>{"use strict";Bi();v_=`using System;
147
151
  using System.Runtime.InteropServices;
148
152
  class CometProcessIdentity {
149
153
  [DllImport("kernel32.dll")] static extern IntPtr OpenProcess(uint access, bool inherit, int pid);
@@ -156,37 +160,40 @@ class CometProcessIdentity {
156
160
  Console.WriteLine(DateTime.FromFileTimeUtc(creation).Ticks.ToString(System.Globalization.CultureInfo.InvariantCulture)); return 0;
157
161
  } finally { CloseHandle(handle); }
158
162
  }
159
- }`,AL=i_("sha256").update(n_).digest("hex")});var oc=I(()=>{"use strict";Di();zg()});import{AsyncLocalStorage as o_}from"async_hooks";var qL,ML,VL,Da=I(()=>{"use strict";ja();oc();U();jt();qL=16*1024,ML=900*1e3,VL=new o_});var Jg,Xd=I(()=>{"use strict";Jg=Kt(It(),1)});var rr,Hr,Dr,nn,an,Ba,Fa=I(()=>{"use strict";rr="comet.native.v3",Hr="comet.native.v2",Dr="comet.native.v1",nn="comet.native.transition.v3",an="comet.native.transition.v2",Ba="comet.native.transition.v1"});import s_ from"node:path";function qa(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Xg(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function sn(e){if(!Yg.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Qg(e){if(!Yg.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Zg(e,t){if(e.length===0||s_.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function m_(e,t){let r=qa(e,`spec_changes[${t}]`);if(Xg(r,u_,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(Qg(r.capability),r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`Invalid spec operation for ${r.capability}`);let i=r.source,n=r.base_hash;if(i!==void 0&&typeof i!="string")throw new Error(`Spec source for ${r.capability} must be a string`);if(typeof i=="string"&&Zg(i,`Spec source for ${r.capability}`),r.operation==="create"){if(!i)throw new Error(`Create spec ${r.capability} requires source`);if(n!==null)throw new Error(`Create spec ${r.capability} requires null base_hash`)}else if(r.operation==="replace"){if(!i)throw new Error(`Replace spec ${r.capability} requires source`);if(typeof n!="string"||!Zd.test(n))throw new Error(`Replace spec ${r.capability} requires a SHA-256 base_hash`)}else{if(i!==void 0)throw new Error(`Remove spec ${r.capability} forbids source`);if(typeof n!="string"||!Zd.test(n))throw new Error(`Remove spec ${r.capability} requires a SHA-256 base_hash`)}return{capability:r.capability,operation:r.operation,...typeof i=="string"?{source:i}:{},base_hash:n}}function v_(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 ep(e,t){if(Xg(e,t,Dt),typeof e.name!="string")throw new Error("Native change name is required");if(sn(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"||!d_.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 r=e.spec_changes.map(m_),i=r.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(i.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(i)].join(", ")}`);if(typeof e.verification_result!="string"||!f_.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"&&Zg(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!v_(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:r,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function hi(e){let t=qa(e,Dt);if(t.schema!==Dr)throw new Error(`Expected ${Dr}`);return{schema:Dr,...ep(t,c_)}}function La(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Qd(e,t,r){if(e===null)return null;let i=typeof e=="string"?h_.exec(e):null;if(!i||i[1]!==r)throw new Error(`${t} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return e}function g_(e){if(e==null)return null;if(typeof e!="string"||!Zd.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function w_(e){if(e===void 0)return"legacy-v1";if(e!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return e}function mi(e){let t=qa(e,Dt);if(t.schema!==Hr)throw new Error(`Expected ${Hr}`);if(La(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Hr} minimum_runtime_version must be 2`);return{schema:Hr,minimum_runtime_version:2,revision:La(t.revision,"Native v2 revision"),...ep(t,Kg)}}function Bt(e){let t=qa(e,Dt);if(t.schema!==rr){if(t.schema===Dr||t.schema===Hr){let o=t.schema===Dr?hi(t):mi(t);throw new on(o.name,o.schema)}throw new ir(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=La(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new ir(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=La(t.revision,"Native revision"),n=ep(t,l_),a=g_(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:rr,minimum_runtime_version:3,revision:i,verification_protocol:w_(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Qd(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Qd(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Qd(t.partial_allowance,"Native partial_allowance","allowances")}}function sc(e){let t=qa(e,Dt);if(t.schema===Dr){let n=hi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${rr}`}}if(t.schema===Hr){let n=mi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${rr}`}}if(t.schema!==rr){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 ir(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=La(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new ir(t.schema,r).message};let i=Bt(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}var Ug,c_,Kg,l_,u_,d_,p_,f_,Dt,Zd,Yg,h_,on,ir,cc=I(()=>{"use strict";Fa();Ug=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],c_=new Set(Ug),Kg=new Set([...Ug,"minimum_runtime_version","revision"]),l_=new Set([...Kg,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),u_=new Set(["capability","operation","source","base_hash"]),d_=new Set(["shape","build","verify","archive"]),p_=new Set(["implicit","confirmed"]),f_=new Set(["pending","pass","fail"]),Dt="comet-state.yaml",Zd=/^[a-f0-9]{64}$/u,Yg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,h_=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,on=class extends Error{constructor(r,i){super(`Native change ${r} uses ${i}; run comet native doctor ${r} --repair before mutating it`);this.change=r;this.schema=i;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},ir=class extends Error{constructor(r,i){super(r!==rr||i===null?`Unsupported Native change schema ${r} for runtime protocol ${3}`:`Native change ${r} requires runtime protocol ${i}; current protocol is ${3}`);this.schema=r;this.minimumRuntimeVersion=i;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"}});import ew from"node:path";function x_(e,t){return e<t?-1:e>t?1:0}function iw(e,t){if(Buffer.byteLength(e,"utf8")<=t)return{value:e,truncated:!1};let r="",i=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(i+a>t)break;r+=n,i+=a}return{value:r,truncated:!0}}function nw(e,t){let r=t.toString(36),i=T("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${r}.${i}`}function C_(e){if(!S_.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=E_.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 r=Number.parseInt(t[2],36);if(!Number.isSafeInteger(r)||r<=0||r>=e.total||r.toString(36)!==t[2])throw new Error("Native acceptance cursor offset is invalid");if(t[3]!==T("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:r}))throw new Error("Native acceptance cursor integrity check failed");return r}function R_(e,t){let r=iw(e.text,nr.maxTextBytes),i=e.context.slice(0,nr.maxContextItems).map(n=>iw(n,nr.maxContextItemBytes));return{id:e.id,kind:e.kind,source:e.source,context:i.map(n=>n.value),text:r.value,contextTruncated:e.context.length>i.length||i.some(n=>n.truncated),textTruncated:r.truncated,verificationStatus:t}}function ow(e){let t=C_({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),r=[],i=[...new Set(e.failedCheckIds??[])].sort(x_),n=i.slice(0,nr.maxFailedCheckIds),a=e.criteria.slice(t,t+nr.maxItems);for(let c of a){let l=[...r,R_(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(p=>p.verificationStatus==="failed").map(p=>p.id),missingAcceptanceIds:l.filter(p=>p.verificationStatus==="missing").map(p=>p.id),failedCheckIds:n,failedCheckIdsTruncated:i.length>n.length,nextCursor:u<e.criteria.length?nw(e.acceptanceHash,u):null,limits:{...nr}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>nr.maxSerializedBytes){if(r.length===0)throw new Error("Native acceptance criterion exceeds the page serialization budget");break}r.push(l.at(-1))}if(e.criteria.length>0&&r.length===0)throw new Error("Native acceptance page could not project its next criterion");let o=t+r.length,s={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:r,failedAcceptanceIds:r.filter(c=>c.verificationStatus==="failed").map(c=>c.id),missingAcceptanceIds:r.filter(c=>c.verificationStatus==="missing").map(c=>c.id),failedCheckIds:n,failedCheckIdsTruncated:i.length>n.length,nextCursor:o<e.criteria.length?nw(e.acceptanceHash,o):null,limits:{...nr}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>nr.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function rp(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 tp(e,t){let r=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!r)return t;let i=r[1][0];return t===null?{marker:i,length:r[1].length}:i===t.marker&&r[1].length>=t.length&&r[2].trim().length===0?null:t}function aw(e){return e.includes("-->")||e.includes("--!>")}function*cn(e){let t=null,r=!1,i=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
163
+ }`,VL=m_("sha256").update(v_).digest("hex")});var cc=I(()=>{"use strict";Bi();tw()});import{AsyncLocalStorage as w_}from"async_hooks";var eq,tq,rq,Ba=I(()=>{"use strict";$a();cc();U();jt();eq=16*1024,tq=900*1e3,rq=new w_});var iw,tp=I(()=>{"use strict";iw=Kt(It(),1)});var rr,Hr,Dr,an,on,Fa,La=I(()=>{"use strict";rr="comet.native.v3",Hr="comet.native.v2",Dr="comet.native.v1",an="comet.native.transition.v3",on="comet.native.transition.v2",Fa="comet.native.transition.v1"});import y_ from"node:path";function Ma(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function sw(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function cn(e){if(!ow.test(e))throw new Error(`Invalid Native change name: ${e}`)}function cw(e){if(!ow.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function lw(e,t){if(e.length===0||y_.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function R_(e,t){let r=Ma(e,`spec_changes[${t}]`);if(sw(r,k_,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(cw(r.capability),r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`Invalid spec operation for ${r.capability}`);let i=r.source,n=r.base_hash;if(i!==void 0&&typeof i!="string")throw new Error(`Spec source for ${r.capability} must be a string`);if(typeof i=="string"&&lw(i,`Spec source for ${r.capability}`),r.operation==="create"){if(!i)throw new Error(`Create spec ${r.capability} requires source`);if(n!==null)throw new Error(`Create spec ${r.capability} requires null base_hash`)}else if(r.operation==="replace"){if(!i)throw new Error(`Replace spec ${r.capability} requires source`);if(typeof n!="string"||!ip.test(n))throw new Error(`Replace spec ${r.capability} requires a SHA-256 base_hash`)}else{if(i!==void 0)throw new Error(`Remove spec ${r.capability} forbids source`);if(typeof n!="string"||!ip.test(n))throw new Error(`Remove spec ${r.capability} requires a SHA-256 base_hash`)}return{capability:r.capability,operation:r.operation,...typeof i=="string"?{source:i}:{},base_hash:n}}function 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 np(e,t){if(sw(e,t,Dt),typeof e.name!="string")throw new Error("Native change name is required");if(cn(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"||!S_.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&&!E_.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let r=e.spec_changes.map(R_),i=r.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(i.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(i)].join(", ")}`);if(typeof e.verification_result!="string"||!x_.has(e.verification_result))throw new Error("Native verification_result is invalid");if(e.verification_report!==null&&typeof e.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof e.verification_report=="string"&&lw(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:r,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function mi(e){let t=Ma(e,Dt);if(t.schema!==Dr)throw new Error(`Expected ${Dr}`);return{schema:Dr,...np(t,N_)}}function qa(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function rp(e,t,r){if(e===null)return null;let i=typeof e=="string"?C_.exec(e):null;if(!i||i[1]!==r)throw new Error(`${t} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return e}function __(e){if(e==null)return null;if(typeof e!="string"||!ip.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function A_(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 vi(e){let t=Ma(e,Dt);if(t.schema!==Hr)throw new Error(`Expected ${Hr}`);if(qa(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Hr} minimum_runtime_version must be 2`);return{schema:Hr,minimum_runtime_version:2,revision:qa(t.revision,"Native v2 revision"),...np(t,aw)}}function Bt(e){let t=Ma(e,Dt);if(t.schema!==rr){if(t.schema===Dr||t.schema===Hr){let o=t.schema===Dr?mi(t):vi(t);throw new sn(o.name,o.schema)}throw new ir(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=qa(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new ir(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=qa(t.revision,"Native revision"),n=np(t,b_),a=__(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:rr,minimum_runtime_version:3,revision:i,verification_protocol:A_(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:rp(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:rp(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:rp(t.partial_allowance,"Native partial_allowance","allowances")}}function lc(e){let t=Ma(e,Dt);if(t.schema===Dr){let n=mi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${rr}`}}if(t.schema===Hr){let n=vi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${rr}`}}if(t.schema!==rr){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 ir(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=qa(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new ir(t.schema,r).message};let i=Bt(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}var nw,N_,aw,b_,k_,S_,E_,x_,Dt,ip,ow,C_,sn,ir,uc=I(()=>{"use strict";La();nw=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],N_=new Set(nw),aw=new Set([...nw,"minimum_runtime_version","revision"]),b_=new Set([...aw,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),k_=new Set(["capability","operation","source","base_hash"]),S_=new Set(["shape","build","verify","archive"]),E_=new Set(["implicit","confirmed"]),x_=new Set(["pending","pass","fail"]),Dt="comet-state.yaml",ip=/^[a-f0-9]{64}$/u,ow=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,C_=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,sn=class extends Error{constructor(r,i){super(`Native change ${r} uses ${i}; run comet native doctor ${r} --repair before mutating it`);this.change=r;this.schema=i;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},ir=class extends Error{constructor(r,i){super(r!==rr||i===null?`Unsupported Native change schema ${r} for runtime protocol ${3}`:`Native change ${r} requires runtime protocol ${i}; current protocol is ${3}`);this.schema=r;this.minimumRuntimeVersion=i;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"}});import uw from"node:path";function D_(e,t){return e<t?-1:e>t?1:0}function fw(e,t){if(Buffer.byteLength(e,"utf8")<=t)return{value:e,truncated:!1};let r="",i=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(i+a>t)break;r+=n,i+=a}return{value:r,truncated:!0}}function hw(e,t){let r=t.toString(36),i=T("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${r}.${i}`}function B_(e){if(!O_.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=H_.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 r=Number.parseInt(t[2],36);if(!Number.isSafeInteger(r)||r<=0||r>=e.total||r.toString(36)!==t[2])throw new Error("Native acceptance cursor offset is invalid");if(t[3]!==T("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:r}))throw new Error("Native acceptance cursor integrity check failed");return r}function F_(e,t){let r=fw(e.text,nr.maxTextBytes),i=e.context.slice(0,nr.maxContextItems).map(n=>fw(n,nr.maxContextItemBytes));return{id:e.id,kind:e.kind,source:e.source,context:i.map(n=>n.value),text:r.value,contextTruncated:e.context.length>i.length||i.some(n=>n.truncated),textTruncated:r.truncated,verificationStatus:t}}function vw(e){let t=B_({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),r=[],i=[...new Set(e.failedCheckIds??[])].sort(D_),n=i.slice(0,nr.maxFailedCheckIds),a=e.criteria.slice(t,t+nr.maxItems);for(let c of a){let l=[...r,F_(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(p=>p.verificationStatus==="failed").map(p=>p.id),missingAcceptanceIds:l.filter(p=>p.verificationStatus==="missing").map(p=>p.id),failedCheckIds:n,failedCheckIdsTruncated:i.length>n.length,nextCursor:u<e.criteria.length?hw(e.acceptanceHash,u):null,limits:{...nr}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>nr.maxSerializedBytes){if(r.length===0)throw new Error("Native acceptance criterion exceeds the page serialization budget");break}r.push(l.at(-1))}if(e.criteria.length>0&&r.length===0)throw new Error("Native acceptance page could not project its next criterion");let o=t+r.length,s={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:r,failedAcceptanceIds:r.filter(c=>c.verificationStatus==="failed").map(c=>c.id),missingAcceptanceIds:r.filter(c=>c.verificationStatus==="missing").map(c=>c.id),failedCheckIds:n,failedCheckIdsTruncated:i.length>n.length,nextCursor:o<e.criteria.length?hw(e.acceptanceHash,o):null,limits:{...nr}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>nr.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function op(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 ap(e,t){let r=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!r)return t;let i=r[1][0];return t===null?{marker:i,length:r[1].length}:i===t.marker&&r[1].length>=t.length&&r[2].trim().length===0?null:t}function mw(e){return e.includes("-->")||e.includes("--!>")}function*ln(e){let t=null,r=!1,i=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
160
164
  `),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
161
- `,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!r&&i===null,index:s},s+=1,t!==null)t=tp(l,t);else if(r)aw(l)&&(r=!1);else if(i!==null)new RegExp(`</${i}\\s*>`,"iu").test(l)&&(i=null);else{let d=tp(l,null);if(d!==null)t=d;else{let p=l.trimStart();if(p.startsWith("<!--")&&!aw(p))r=!0;else{let f=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(p);f&&n.has(f[1].toLowerCase())&&!p.startsWith("</")&&!p.endsWith("/>")&&!new RegExp(`</${f[1]}\\s*>`,"iu").test(p)&&(i=f[1])}}}if(c===-1)break;o=c+1}}function P_(e){return[...cn(e)].map(({line:t,body:r})=>({line:t,body:r}))}function lc(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function __(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function ip(e,t,r,i=[],n="content-hash"){let a=lc(r),o=t.replaceAll("\\","/").trim(),s=i.map(lc);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-${T(y_,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function np(e,t,r="content-hash"){let i=new Set;for(let n of e){let a=r==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(i.has(a))throw new Error(`${t} contains duplicate acceptance criteria`);i.add(a)}return e}function A_(e){let t=null,r=null,i=0,n=0;for(let{line:a,body:o,index:s}of cn(e)){n=s+1;let c=o?rp(a):null;c?.level===1&&(Us(c.text)==="acceptanceExamples"?(i+=1,i===1&&(t=s+1)):t!==null&&r===null&&(r=s))}if(i===0||t===null)return null;if(i!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:r??n}}function ap(e,t="brief.md",r=Ma.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let n=A_(e);if(n===null)return[];let a=null;for(let{line:l,body:u,index:d}of cn(e)){if(d<n.start||d>=n.end)continue;let p=u?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(p===null)continue;let f=p[1].length;a=a===null?f:Math.min(a,f)}let o=[],s=null,c=()=>{if(s!==null){if(o.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);o.push(s)}};for(let{line:l,body:u,index:d}of cn(e)){if(d<n.start||d>=n.end)continue;let p=u?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;p&&p[1].length===a?(c(),s=[p[2]]):s!==null&&s.push(l)}return c(),np(o.map(l=>ip("brief-example",t,l.join(`
162
- `),[],i)),"Brief",i)}function op(e,t="spec.md",r=Ma.maxCriteria,i="content-hash",n={}){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native specification acceptance budget is invalid");let a=[],o=[],s=null,c=()=>{if(s===null)return;if(a.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);let l=(n.resolveBriefReferences?s.body:[]).map(u=>/^\s*(?:Acceptance|验收)\s*[::]\s*(.*)$/iu.exec(u)?.[1]).filter(u=>u!==void 0);if(l.some(u=>!/^A[1-9]\d*$/u.test(u)))throw new Error("A Spec acceptance reference must be one brief ID such as A1");if(l.length>1)throw new Error("A Spec scenario may reference only one brief acceptance criterion");a.push({...ip("spec-scenario",t,[s.title,...s.body].join(`
163
- `),s.context,i),...l[0]===void 0?{}:{briefAcceptanceRef:l[0]}}),s=null};for(let{line:l,body:u}of cn(e)){let d=u?rp(l):null,p=d?/^Scenario\s*:\s*(.*)$/iu.exec(d.text):null;if(p){for(c();o.at(-1)&&o.at(-1).level>=d.level;)o.pop();let f=lc(p[1]);if(f.length===0)throw new Error("Scenario title must not be empty");s={level:d.level,title:f,body:[],context:o.map(m=>m.text)}}else if(d){for(s!==null&&d.level<=s.level?c():s!==null&&s.body.push(l);o.at(-1)&&o.at(-1).level>=d.level;)o.pop();o.push(d)}else s!==null&&u&&s.body.push(l)}return c(),np(a,"Specification",i)}function sw(e,t="spec.md",r=Ma.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=null,c=()=>{if(s!==null){if(n.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);n.push(ip("spec-must",t,s.parts.join(" "),s.context,i)),s=null}},l=()=>a.some(u=>/^(?:non-?goals?|非目标)$/iu.test(u.text.trim()));for(let{line:u,body:d}of cn(e)){let p=d?rp(u):null;if(p){for(c(),o!==null&&p.level<=o&&(o=null);a.at(-1)&&a.at(-1).level>=p.level;)a.pop();a.push(p),/^Scenario\s*:/iu.test(p.text)&&(o=p.level);continue}let f=u.trim();if(!d||o!==null||l()){c();continue}if(f.length===0||tp(u,null)!==null||f.startsWith("<!--")||f==="-->"||f==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(f)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(f)||/^(?:[-*_]\s*){3,}$/u.test(f)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(f)){c();continue}let m=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(u);if(m){c(),s={parts:[m[1]],context:a.map(h=>h.text)};continue}if(/^\|.*\|$/u.test(f)){c(),s={parts:[f],context:a.map(h=>h.text)},c();continue}s===null?s={parts:[f],context:a.map(h=>h.text)}:s.parts.push(f)}return c(),np(n,"Specification mandatory requirements",i)}function I_(e,t){let r=e.trim().replaceAll("\\","/");if(r.length===0||__(r)||ew.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~|[A-Za-z][A-Za-z0-9+.-]*:)/u.test(r)||r.split("/").includes(".."))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);let i=ew.posix.normalize(r);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);if(i.split("/").some(n=>n.toLowerCase()===".git"||n.toLowerCase().startsWith(".env")))throw new Error(`Acceptance evidence ${t} references sensitive content`);if(!k_.test(i))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return i}function T_(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`Acceptance evidence entry ${t} must be an object`);let r=e,i=Object.keys(r).filter(n=>!b_.has(n));if(i.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${i.join(", ")}`);return r}function cw(e){if(!Array.isArray(e))throw new Error("Native acceptance evidence block must be a JSON array");let t=new Set;return e.map((r,i)=>{let n=T_(r,i),a=n.acceptance_id;if(typeof a!="string"||!N_.test(a))throw new Error(`Acceptance evidence entry ${i} has an invalid acceptance_id`);if(t.has(a))throw new Error(`Native acceptance evidence has duplicate acceptance_id: ${a}`);if(t.add(a),!Array.isArray(n.evidence_refs))throw new Error(`Acceptance evidence ${a} requires an evidence_refs array`);let o=n.evidence_refs.map(l=>{if(typeof l!="string"||l.trim().length===0)throw new Error(`Acceptance evidence ${a} has a non-empty string requirement`);return I_(l,a)});if(new Set(o).size!==o.length)throw new Error(`Acceptance evidence ${a} has a duplicate evidence ref`);let s=n.status;if(s!=="passed"&&s!=="failed")throw new Error(`Acceptance evidence ${a} status is invalid`);let c;if(Object.prototype.hasOwnProperty.call(n,"skipped_reason")){if(typeof n.skipped_reason!="string"||n.skipped_reason.trim().length===0)throw new Error(`Acceptance evidence ${a} skipped_reason must be a non-empty string`);c=n.skipped_reason.trim()}if(s==="passed"&&o.length===0)throw new Error(`Acceptance evidence ${a} passed status requires evidence_refs`);if(s==="failed"&&o.length===0&&c===void 0)throw new Error(`Acceptance evidence ${a} failed status requires evidence_refs or a skipped_reason`);if(s==="passed"&&c!==void 0)throw new Error(`Acceptance evidence ${a} passed status has invalid fields`);return{acceptance_id:a,status:s,evidence_refs:o,...c===void 0?{}:{skipped_reason:c}}})}function lw(e){let t=P_(e);if(t.some(({line:l,body:u})=>!u&&(l===tw||l===rw)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let i=t.flatMap(({line:l,body:u},d)=>u&&l===tw?[d]:[]),n=t.flatMap(({line:l,body:u},d)=>u&&l===rw?[d]:[]);if(i.length!==1||n.length!==1)throw new Error("Verification must contain exactly one Native acceptance evidence block");if(i[0]>=n[0])throw new Error("Native acceptance evidence markers are out of order");let a=t.slice(i[0]+1,n[0]).map(({line:l})=>l).join(`
164
- `).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=cw(o),c=j_(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function j_(e){let t=cw([...e]).map(r=>({...r,evidence_refs:[...r.evidence_refs].sort()})).sort((r,i)=>r.acceptance_id.localeCompare(i.acceptance_id));return JSON.stringify(t,null,2)}var y_,N_,b_,k_,S_,E_,nr,Ma,tw,rw,Va=I(()=>{"use strict";pi();ue();y_="comet.native.acceptance.v1",N_=/^acceptance-[a-f0-9]{64}$/u,b_=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),k_=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,S_=/^[a-f0-9]{64}$/u,E_=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;nr=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Ma=Object.freeze({maxCriteria:1024}),tw="<!-- comet-native:acceptance-evidence:start -->",rw="<!-- comet-native:acceptance-evidence:end -->"});var sp=I(()=>{"use strict";Va()});function cp(e,t,r,i=""){let n=Object.keys(e),a=t.filter(s=>!Object.hasOwn(e,s)),o=n.filter(s=>!t.includes(s));if(a.length||o.length)throw new Wa({code:"invalid-fields",path:i,context:r,missingFields:a,unknownFields:o,expectedFields:[...t]})}var Wa,uc=I(()=>{"use strict";Wa=class extends Error{issues;constructor(t){let r=[t.missingFields.length?`missing: ${t.missingFields.join(", ")}`:"",t.unknownFields.length?`unknown: ${t.unknownFields.join(", ")}`:""].filter(Boolean).join("; ");super(`${t.context} fields are invalid at ${t.path||"/"} (${r})`),this.name="NativeInputValidationError",this.issues=[t]}}});function lp(e,t){if(typeof e!="string"||!e.trim()||e.length>4e3||/^<[^>]+>$/u.test(e.trim()))throw new Error(`${t} must contain a concrete statement of at most 4000 characters`);return e.trim()}function up(e){if(!Array.isArray(e))throw new Error("Native Builder acceptance_review must be an array");return e.map((t,r)=>{if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native Builder acceptance review entry must be an object");let i=t,n=`Native Builder acceptance_review[${r}]`;cp(i,["id","status","evidence","note"],n,`/acceptance_review/${r}`);let a=i.status;if(!["implemented-with-evidence","implemented-no-evidence","not-implemented","known-fail"].includes(a))throw new Error(`${n}.status is invalid`);if(!Array.isArray(i.evidence))throw new Error(`${n}.evidence must be an array`);return{id:lp(i.id,`${n}.id`),status:a,evidence:i.evidence.map(o=>lp(o,`${n}.evidence`)),note:lp(i.note,`${n}.note`)}})}function dp(e,t){if(!t)throw new ln(e.map(({id:c})=>c),[]);let r=new Set(e.map(({id:c})=>c)),i=t.map(({id:c})=>c),n=new Set(i);if(n.size!==i.length)throw new Error("Native Builder acceptance_review contains duplicate IDs");let a=i.filter(c=>!r.has(c));if(a.length)throw new Error(`Native Builder acceptance_review contains unknown IDs: ${a.join(", ")}`);let o=e.filter(({id:c})=>!n.has(c)).map(({id:c})=>c),s=t.filter(c=>c.status!=="implemented-with-evidence"||c.evidence.length===0).map(({id:c})=>c);if(o.length||s.length)throw new ln(o,s)}var ln,dc=I(()=>{"use strict";uc();ln=class extends Error{constructor(r,i){super(`Native Builder handoff is incomplete${r.length?`; missing: ${r.join(", ")}`:""}${i.length?`; not ready: ${i.join(", ")}`:""}. Complete acceptance_review for every requirement and its evidence before Verify`);this.missingIds=r;this.incompleteIds=i}missingIds;incompleteIds}});function pp(){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 un,pc,uw,za=I(()=>{"use strict";un="comet.native.v4",pc="comet.native.local-execution.v4",uw=["multi-session","single-session"]});var gp={};mS(gp,{NativePortableStateVersionConflictError:()=>Ga,appendNativePortableHistory:()=>Ja,compareAndSwapNativePortableState:()=>fw,createNativePortableState:()=>pw,parseNativePortableState:()=>qe,readNativePortableState:()=>Br,writeNativePortableState:()=>vp});import{promises as $_}from"node:fs";function je(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function $e(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function ye(e,t,r){if(typeof e!="string"||!r?.empty&&e.length===0)throw new Error(`${t} must be ${r?.empty?"a string":"a non-empty string"}`);return e}function hp(e,t){return e===null?null:ye(e,t)}function mp(e,t){let r=ye(e,t);if(!B_.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function dn(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function oe(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function L_(e,t){return e===null?null:oe(e,t,Number.MIN_SAFE_INTEGER)}function pe(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Ft(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function vc(e,t){return Ft(e,t,(r,i)=>ye(r,`${t}[${i}]`))}function vi(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function pn(e,t){let r=ye(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function hc(e,t,r=!1){let i=ye(e,t);if(i.includes("\\")||i.startsWith("/")||/^[A-Za-z]:/u.test(i)||i.split("/").includes("..")||!r&&(i==="."||i.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return i}function rt(e,t){let r=je(e,t);return $e(r,new Set(["text","truncated"]),t),{text:ye(r.text,`${t}.text`,{empty:!0}),truncated:dn(r.truncated,`${t}.truncated`)}}function q_(e,t){let r=`Native spec_changes[${t}]`,i=je(e,r);$e(i,new Set(["capability","operation","source","delta_source","base_hash"]),r);let n=ye(i.capability,`${r}.capability`);if(!H_.test(n))throw new Error(`${r}.capability is invalid`);let a=pe(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:hc(i.source,`${r}.source`),s=i.delta_source===void 0?void 0:hc(i.delta_source,`${r}.delta_source`),c=i.base_hash===void 0?void 0:i.base_hash===null?null:mp(i.base_hash,`${r}.base_hash`);if(a==="remove"&&o!==null)throw new Error(`${r} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${r} ${a} requires a source`);if(s!==void 0&&a==="remove")throw new Error(`${r} remove cannot contain delta_source`);if(s!==void 0&&c==null)throw new Error(`${r} delta_source requires a non-null base_hash`);if(c!==void 0&&s===void 0&&a!=="remove")throw new Error(`${r} base_hash requires delta_source for non-remove specs`);return{capability:n,operation:a,source:o,...s===void 0?{}:{delta_source:s},...c===void 0?{}:{base_hash:c}}}function M_(e){let t="Native workspace",r=je(e,t);$e(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=pe(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=hp(r.change_branch,`${t}.change_branch`),a=hp(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:pe(r.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(i==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(i==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(i!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:i,change_branch:n,target_branch:a,finish:o}}function V_(e){let t="Native loop",r=je(e,t);$e(r,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let i=vc(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);vi(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:pe(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:pe(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:oe(r.goal_cycle,`${t}.goal_cycle`,1),iteration:oe(r.iteration,`${t}.iteration`),attempt:oe(r.attempt,`${t}.attempt`),retry_epoch:oe(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:oe(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:oe(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:oe(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:hp(r.next_action,`${t}.next_action`)}}function W_(e,t){let r=`Native acceptance[${t}]`,i=je(e,r);$e(i,new Set(["id","source","text","result","reason"]),r);let n=ye(i.id,`${r}.id`);if(!D_.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:hc(i.source,`${r}.source`),text:ye(i.text,`${r}.text`),result:pe(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:rt(i.reason,`${r}.reason`)}}function z_(e,t){let r=`Native builder_handoff.checks[${t}]`,i=je(e,r);return $e(i,new Set(["name","result","note"]),r),{name:rt(i.name,`${r}.name`),result:pe(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:rt(i.note,`${r}.note`)}}function G_(e){let t="Native builder_handoff",r=je(e,t);$e(r,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","acceptance_review","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let i=vc(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);vi(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:je(r.review,`${t}.review`);return n&&$e(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:ye(r.candidate_id,`${t}.candidate_id`),identity_provider:ye(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:ye(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:oe(r.iteration,`${t}.iteration`,1),summary:rt(r.summary,`${t}.summary`),addressed_acceptance_ids:i,...r.acceptance_review===void 0?{}:{acceptance_review:up(r.acceptance_review)},checks:Ft(r.checks,`${t}.checks`,z_),checks_truncated:dn(r.checks_truncated,`${t}.checks_truncated`),known_limits:Ft(r.known_limits,`${t}.known_limits`,(a,o)=>rt(a,`${t}.known_limits[${o}]`)),known_limits_truncated:dn(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:pe(n.status,["passed"],`${t}.review.status`),summary:rt(n.summary,`${t}.review.summary`),reviewer_execution_ref:ye(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:pn(r.submitted_at,`${t}.submitted_at`)}}function J_(e,t){let r=`Native blockers[${t}]`,i=je(e,r);$e(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=vc(i.acceptance_ids,`${r}.acceptance_ids`);return vi(n,`${r}.acceptance_ids`),{owner:pe(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:rt(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:pe(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function U_(e,t){let r=`Native verification.checks[${t}]`,i=je(e,r);return $e(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:ye(i.id,`${r}.id`),name:rt(i.name,`${r}.name`),argv_display:Ft(i.argv_display,`${r}.argv_display`,(n,a)=>rt(n,`${r}.argv_display[${a}]`)),argv_truncated:dn(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:hc(i.cwd_ref,`${r}.cwd_ref`,!0),status:pe(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:L_(i.exit_code,`${r}.exit_code`),duration_ms:oe(i.duration_ms,`${r}.duration_ms`)}}function K_(e){let t="Native verification",r=je(e,t);$e(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=Ft(r.checks,`${t}.checks`,U_);vi(i.map(a=>a.id),`${t}.checks IDs`);let n=ye(r.identity_provider,`${t}.identity_provider`);return{candidate_id:ye(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:ye(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:oe(r.iteration,`${t}.iteration`,1),attempt:oe(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":pe(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:pe(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:rt(r.summary,`${t}.summary`),risks:Ft(r.risks,`${t}.risks`,(a,o)=>rt(a,`${t}.risks[${o}]`)),risks_truncated:dn(r.risks_truncated,`${t}.risks_truncated`),completed_at:pn(r.completed_at,`${t}.completed_at`)}}function dw(e,t){let r=`Native history[${t}]`,i=je(e,r);$e(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=vc(i.unresolved_ids,`${r}.unresolved_ids`);return vi(n,`${r}.unresolved_ids`),{goal_cycle:oe(i.goal_cycle,`${r}.goal_cycle`,1),iteration:oe(i.iteration,`${r}.iteration`),attempt:oe(i.attempt,`${r}.attempt`),outcome:pe(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:rt(i.summary,`${r}.summary`),completed_at:pn(i.completed_at,`${r}.completed_at`)}}function Y_(e){let t="Native history_overflow.outcome_counts",r=je(e,t),i=["pass","fail","blocked","execution-error","recovery"];return $e(r,new Set(i),t),{pass:oe(r.pass,`${t}.pass`),fail:oe(r.fail,`${t}.fail`),blocked:oe(r.blocked,`${t}.blocked`),"execution-error":oe(r["execution-error"],`${t}.execution-error`),recovery:oe(r.recovery,`${t}.recovery`)}}function X_(e){let t="Native history_overflow",r=je(e,t);$e(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=oe(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:pn(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:pn(r.last_dropped_at,`${t}.last_dropped_at`);if(i===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(i>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=Y_(r.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==i)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:i,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function Q_(e){let t=new Set(e.acceptance.map(r=>r.id));for(let r of e.loop.previous_unresolved_ids)if(!t.has(r))throw new Error(`Native loop references unknown acceptance ID ${r}`);for(let r of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(r))throw new Error(`Native builder handoff references unknown ID ${r}`);e.builder_handoff?.acceptance_review&&dp(e.acceptance,e.builder_handoff.acceptance_review);for(let r of e.blockers)for(let i of r.acceptance_ids)if(!t.has(i))throw new Error(`Native blocker references unknown ID ${i}`);if(e.builder_handoff){if(!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let i=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!i&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function Z_(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let r=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(r!==null&&e.loop.stage!==r)throw new Error(`Native status ${e.status} requires loop stage ${r}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(i=>i.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(i=>i.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function qe(e){let t=je(e,"Native portable state");if($e(t,F_,"Native portable state"),t.schema!==un)throw new Error(`Native portable state schema must be ${un}`);let r=ye(t.name,"Native state name");if(!O_.test(r))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let i=Ft(t.spec_changes,"Native spec_changes",q_);vi(i.map(s=>s.capability),"Native spec change capabilities");let n=Ft(t.acceptance,"Native acceptance",W_);vi(n.map(s=>s.id),"Native acceptance IDs");let a=Ft(t.history,"Native history",dw);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:un,name:r,language:pe(t.language,["en","zh-CN"],"Native state language"),phase:pe(t.phase,["shape","build","verify","archive"],"Native state phase"),status:pe(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:oe(t.state_version,"Native state_version",1),brief:"brief.md",...t.document_constraints_version===void 0?{}:t.document_constraints_version===1||t.document_constraints_version===2?{document_constraints_version:t.document_constraints_version}:(()=>{throw new Error("Native document_constraints_version must be 1 or 2")})(),...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:mp(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:mp(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:pe(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:M_(t.workspace),loop:V_(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:G_(t.builder_handoff),blockers:Ft(t.blockers,"Native blockers",J_),verification:t.verification===null?null:K_(t.verification),history:a,history_overflow:X_(t.history_overflow),verification_result:pe(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:pe(t.verification_report,["verification.md"],"Native verification_report"),archived:dn(t.archived,"Native archived"),created_at:pn(t.created_at,"Native created_at")};return Q_(o),Z_(o),o}function pw(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return qe({schema:un,name:e.name,language:e.language,phase:"shape",status:"active",state_version:1,brief:"brief.md",spec_changes:[],workspace:e.workspace??{isolation:"current",change_branch:null,target_branch:null,finish:null},loop:{stage:"shape",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:e.nextAction??null},acceptance:[],builder_handoff:null,blockers:[],verification:null,history:[],history_overflow:pp(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function Ja(e,t){let r=qe(e),i=dw(t,r.history.length),n=[...r.history,i],a={...r.history_overflow,outcome_counts:{...r.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return qe({...r,history:n,history_overflow:a})}function eA(e,t){let r=(0,mc.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`${t} is invalid YAML: ${r.errors[0].message}`);return r.toJS({mapAsMap:!1})}async function Br(e){let t=await $_.readFile(e,"utf8");return qe(eA(t,"Native portable state"))}async function vp(e,t,r={}){let i=qe(t);await $t(e,(0,mc.stringify)(i),r)}async function tA(e,t){let r=fc.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);fc.set(e,a),await r;try{return await t()}finally{i(),fc.get(e)===a&&fc.delete(e)}}async function fw(e){return tA(e.file,async()=>{let t=oe(e.expectedStateVersion,"Native expected state version",1),r=qe(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await Br(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new Ga(t,i.state_version);return await vp(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Br(e.file);if(n.state_version!==t)throw new Ga(t,n.state_version)}}),r})}var mc,O_,H_,D_,B_,F_,Ga,fc,gt=I(()=>{"use strict";dc();mc=Kt(It(),1);ae();za();O_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,H_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,D_=/^A[1-9][0-9]*$/u,B_=/^[a-f0-9]{64}$/u,F_=new Set(["schema","name","language","phase","status","state_version","brief","document_constraints_version","shape_confirmation_hash","children_contract_hash","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),Ga=class extends Error{constructor(r,i){super(`Native state version conflict: expected ${r}, got ${i}`);this.expectedStateVersion=r;this.actualStateVersion=i;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};fc=new Map});var gi=I(()=>{"use strict"});var hw=I(()=>{"use strict";cc();sp();gt();gi();za();Fa()});var mw,Sq,Eq,wp=I(()=>{"use strict";et();Xd();hw();mw="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",Sq=new RegExp(`^portable-archive-(${mw})\\.json$`,"u"),Eq=new RegExp(`^portable-migration-(${mw})\\.json$`,"u")});import{createHash as vw}from"node:crypto";import{constants as Fr,promises as fe}from"node:fs";import Me from"node:path";import{TextDecoder as nA}from"node:util";function fn(e,t){let r=Me.relative(e,t);return r===""||!Me.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Me.sep}`)}function gw(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function aA(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ww(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Lr(e,t){return G({...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 gc(e,t){let r=await fe.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await fe.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function wc(e,t,r){let i=Me.resolve(e),n=Me.resolve(t);if(!fn(i,n))throw new Error(`${r} is outside its managed root`);let a=[await gc(i,r)],o=i;for(let s of Me.relative(i,n).split(Me.sep).filter(Boolean)){await Oe(a,r),o=Me.join(o,s);let c=await gc(o,r);if(!fn(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await Oe(a,r),a}async function Oe(e,t){for(let r of e){let i=await fe.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!aA(r,i)||await fe.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function oA(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(t===null?64*1024:Math.min(64*1024,t+1));for(;;){let o=t===null?a.length:t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,t!==null&&n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function wi(e){let t=e.maxBytes===null?null:gw(e.maxBytes),r=Me.resolve(e.file),i=await wc(e.root,Me.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>gc(Me.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Oe(i,e.label);let a=await fe.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(t!==null&&a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=ww(a),s=await fe.realpath(r);if(!fn(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>fn(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Fr.O_RDONLY:Fr.O_RDONLY|Fr.O_NOFOLLOW|Fr.O_NONBLOCK,l=await fe.open(r,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,p]=await Promise.all([fe.lstat(r),fe.realpath(r)]);if(await Oe(i,e.label),await Oe(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||p!==s||!Lr(o,u)||!Lr(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let f=await oA(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([l.stat(),fe.lstat(r),fe.realpath(r)]);if(await Oe(i,e.label),await Oe(n,e.label),!h.isFile()||h.isSymbolicLink()||v!==s||!Lr(o,m)||!Lr(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:f,hash:vw("sha256").update(f).digest("hex"),size:f.length}}finally{await l.close()}}async function yp(e){let t=Me.resolve(e.file),r=await wc(e.root,Me.dirname(t),e.label),i=await Promise.all((e.forbiddenRoots??[]).map(l=>gc(Me.resolve(l),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Oe(r,e.label);let n=await fe.lstat(t);if(!n.isFile()||n.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let a=ww(n),o=await fe.realpath(t);if(!fn(r[0].realPath,o))throw new Error(`${e.label} resolves outside its managed root`);if(i.some(l=>fn(l.realPath,o)))throw new Error(`${e.label} resolves inside an excluded root`);let s=process.platform==="win32"?Fr.O_RDONLY:Fr.O_RDONLY|Fr.O_NOFOLLOW|Fr.O_NONBLOCK,c=await fe.open(t,s);try{let l=await c.stat();await e.hooks?.afterOpen?.();let[u,d]=await Promise.all([fe.lstat(t),fe.realpath(t)]);if(await Oe(r,e.label),await Oe(i,e.label),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Lr(a,l)||!Lr(a,u))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=vw("sha256"),f=0,m=Buffer.allocUnsafe(64*1024);for(;;){let{bytesRead:b}=await c.read(m,0,m.length,null);if(b===0)break;f+=b,p.update(m.subarray(0,b))}await e.hooks?.beforeFinalCheck?.();let[h,v,g]=await Promise.all([c.stat(),fe.lstat(t),fe.realpath(t)]);if(await Oe(r,e.label),await Oe(i,e.label),!v.isFile()||v.isSymbolicLink()||g!==o||!Lr(a,h)||!Lr(a,v))throw new Error(`${e.label} changed while reading`);return{hash:p.digest("hex"),size:f}}finally{await c.close()}}async function yw(e){let t=await wi(e),r;try{r=new nA("utf-8",{fatal:!0}).decode(t.bytes)}catch(i){throw new Error(`${e.label} is not valid UTF-8`,{cause:i})}return{...t,text:r}}async function Ka(e){let t=await wc(e.root,e.directory,e.label),r;if(e.maxEntries===void 0)r=await fe.readdir(e.directory,{withFileTypes:!0});else{let i=gw(e.maxEntries);r=[];let n=await fe.opendir(e.directory);try{for await(let a of n)if(r.push(a),r.length>i)throw new Error(`${e.label} exceeds ${i} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await Oe(t,e.label),{entries:r,verify:()=>Oe(t,e.label)}}async function Np(e){let t=await wc(e.root,e.directory,e.label);return{verify:()=>Oe(t,e.label)}}var wt=I(()=>{"use strict";ae();jt()});import{TextDecoder as cA}from"util";var Lq,yc=I(()=>{"use strict";ae();U();wt();Lq=new cA("utf-8",{fatal:!0})});var Se=I(()=>{"use strict";Je();Da();wp();yc()});import{createHash as Ew}from"crypto";import{createReadStream as uA}from"fs";async function bp(e){let t=Ew("sha256");for await(let r of uA(e))t.update(r);return t.digest("hex")}function ee(e){return Ew("sha256").update(e).digest("hex")}var Lt=I(()=>{"use strict"});import{createHash as Ec}from"crypto";import{spawn as $w}from"node:child_process";import{promises as re}from"fs";import F from"path";import{performance as xw}from"node:perf_hooks";function Hw(e){let t=e.deadlineMs??PA;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 yt(e){return Math.max(0,e.deadlineAt-Date.now())}function H(e){return yt(e)>=1}function kp(e){let t=e===void 0?new Error("Native snapshot deadline exceeded while waiting for Git"):new Error("Native snapshot deadline exceeded while waiting for Git",{cause:e});return Object.assign(t,{code:"GIT_SNAPSHOT_TIMEOUT"})}function vn(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function TA(e,t){let r={...IA,...t===void 0?{}:{maxNodes:t},...e};if(!Number.isSafeInteger(r.maxNodes)||r.maxNodes<1||!Number.isSafeInteger(r.maxBytes)||r.maxBytes<1||!Number.isSafeInteger(r.maxPathBytes)||r.maxPathBytes<1||r.maxPathBytes>r.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return r}async function jA(e,t){if(t.terminateTree){await t.terminateTree(e);return}let r=e.pid;if(r===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let i=process.env.SystemRoot??process.env.WINDIR,n=i&&F.win32.isAbsolute(i)?F.win32.resolve(i):"C:\\Windows",a=F.win32.join(n,"System32","taskkill.exe");if(!F.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=(p,f=!1)=>{c||(c=!0,u&&clearTimeout(u),f&&l?.kill("SIGKILL"),s(p))};try{l=$w(a,["/pid",String(r),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>d(!1)),l.once("close",p=>d(p===0)),u=setTimeout(()=>d(!1,!0),_A),u.unref()}catch{d(!1)}});for(let s=0;s<AA;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(-r,"SIGKILL")}catch(i){if(i.code!=="ESRCH")throw i}e.kill("SIGKILL")}function Pp(e,t,r,i){let n=yt(e);if(n<1)throw kp();let a=e.gitProcess,o=xw.now(),s=$w(a.command,[...a.argsPrefix??[],"-C",t,...r],{cwd:t,stdio:[i?"pipe":"ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"}),c=null,l=!1,u=null;s.once("error",m=>{c=m});let d=new Promise(m=>{s.once("close",m)}),p=setTimeout(()=>{l=!0,u=jA(s,a).then(()=>({error:null}),m=>({error:m}))},n);p.unref();let f=d.then(async m=>{if(clearTimeout(p),l){let h=await u;throw h?.error?kp(h.error):kp()}return{code:m,spawnError:c}}).finally(()=>Bl(xw.now()-o));return{child:s,completion:f}}function Dw(e,t){let r={...Rp,...t===void 0?{}:{maxRecords:t},...e};if(!Number.isSafeInteger(r.maxRecords)||r.maxRecords<1||!Number.isSafeInteger(r.maxBytes)||r.maxBytes<1||!Number.isSafeInteger(r.maxRecordBytes)||r.maxRecordBytes<1||r.maxRecordBytes>r.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return r}async function bc(e,t,r,i=xp){let{child:n,completion:a}=Pp(e,t,r,!1),o=[],s=[],c=0,l=0,u=!1;n.stdout.on("data",f=>{let m=Math.max(0,i-l);m>0&&o.push(Buffer.from(f).subarray(0,m)),l+=f.byteLength,l>i&&(u=!0)}),n.stderr.on("data",f=>{if(c>=wn)return;let m=wn-c,h=Buffer.from(f).subarray(0,m);s.push(h),c+=h.byteLength});let{code:d,spawnError:p}=await a;if(d===0&&p===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${r.join(" ")} failed${p?`: ${p.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function Sp(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function Xa(e,t,r,i){if(i.outputChunkBytes!==void 0&&(!Number.isSafeInteger(i.outputChunkBytes)||i.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}=Pp(e,t,r,i.stdin!==void 0),c=[],l=Ec("sha256"),u=[],d=0,p=0,f=0,m=0,h=Buffer.alloc(0),v=!1,g=!1,b=!1,k=N=>{let x=0;for(;x<N.byteLength;){let w=N.indexOf(0,x),S=w<0?N.byteLength:w,E=N.subarray(x,S);if(!v&&E.byteLength>0&&(h.byteLength+E.byteLength>i.maxRecordBytes?(h=Buffer.alloc(0),v=!0,g=!0):h=Buffer.concat([h,E])),w<0)break;m+=1,h.byteLength===0&&!v&&(b=!0);let y=h.byteLength+1;!v&&m<=i.maxRecords&&f+y<=i.maxBytes?(c.push(h),f+=y):g=!0,h=Buffer.alloc(0),v=!1,x=w+1}};o.stdout.on("data",N=>{l.update(N),p+=N.byteLength,p>i.maxBytes&&(g=!0);let x=i.outputChunkBytes;if(x===void 0){k(N);return}for(let w=0;w<N.byteLength;w+=x)k(N.subarray(w,Math.min(N.byteLength,w+x)))}),o.stderr.on("data",N=>{if(d>=wn)return;let x=wn-d,w=Buffer.from(N).subarray(0,x);u.push(w),d+=w.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:N,spawnError:x})=>{let w=i.acceptedExitCodes??[0];if(N!==null&&w.includes(N)&&x===null&&!b&&h.byteLength===0&&!v){n({records:c,digest:l.digest("hex"),overflow:g,recordCount:m,stdoutBytes:p});return}a(new Error(`git ${r.join(" ")} failed${x?`: ${x.message}`:b||h.byteLength>0||v?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),i.stdin&&o.stdin?.end(i.stdin)})}function kc(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 $A(e,t,r){if(r.length===0)return new Set;let i=await Xa(e,t,["check-ignore","--no-index","-z","--stdin"],{...Rp,maxRecords:Math.max(1,r.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${r.join("\0")}\0`,"utf8")});if(i.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(i.records.map(n=>{let a=kc(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function OA(e,t,r){let{child:i,completion:n}=Pp(e,t,r,!1),a=[],o=0,s=!1;i.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),i.stderr.on("data",u=>{if(o>=wn)return;let d=wn-o,p=Buffer.from(u).subarray(0,d);a.push(p),o+=p.byteLength});let{code:c,spawnError:l}=await n;if(c===0&&l===null)return s;throw new Error(`git ${r.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function gn(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||F.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||F.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function HA(e,t){return e.map(r=>{let i=gn(r);if(i===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return i})}async function DA(e){let t=F.resolve(e);for(;;){try{return await re.lstat(F.join(t,".git")),!0}catch(i){if(i.code!=="ENOENT")throw i}let r=F.dirname(t);if(r===t)return!1;t=r}}function BA(e){return e?e.filter(t=>t&&!t.startsWith("!")).flatMap(t=>t.includes("**")?[`:(exclude,glob)${t}`]:[`:(exclude)${t}`]):[]}async function Bw(e,t,r,i={},n){let a=F.resolve(t.projectRoot),o=F.join(a,".comet","current-change.json"),c=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,o].map(f=>{let m=F.relative(a,F.resolve(f)).replaceAll("\\","/"),h=gn(m);if(h===null)throw new Error("Native Git snapshot exclusion escaped the project root");return h}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`]),...BA(n)],l={...r,...i.outputChunkBytes===void 0?{}:{outputChunkBytes:i.outputChunkBytes}},u=await Xa(e,a,["ls-files","--stage","-z",...c],l);await i.afterStageBefore?.();let d=await Xa(e,a,["ls-files","--cached","--others","--exclude-standard","-z",...c],l);await i.afterCombined?.();let p=await Xa(e,a,["ls-files","--stage","-z",...c],l);return{stagedBefore:u,combined:d,stagedAfter:p}}function Fw(e){return{stageBefore:Sp(e.stagedBefore),combined:Sp(e.combined),stageAfter:Sp(e.stagedAfter)}}async function Lw(e,t,r=Rp,i={},n){let a=F.resolve(t.projectRoot);if(!await DA(a))return null;let o;try{o=await bc(e,a,["rev-parse","--is-inside-work-tree"])}catch(k){throw vn(k)?k:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:k})}if(o.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let s;try{s=await Bw(e,t,r,i,n)}catch(k){throw vn(k)?k:new Error("Native Git snapshot provider failed after repository detection",{cause:k})}let{stagedBefore:c,combined:l,stagedAfter:u}=s,d=new Set,p=new Map,f=new Set,m=k=>{for(let N of k){let x=kc(N),w=x.indexOf(" ");if(w<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(x.slice(0,w))?.groups;if(!S)throw new Error("Native Git snapshot provider returned a malformed staged header");let E=gn(x.slice(w+1));if(E===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");d.add(E),S.stage==="0"&&p.set(E,S.objectId),S.mode==="160000"&&S.stage==="0"&&f.add(E)}};m(c.records),m(u.records);let h=l.records.map(kc),v=HA(h,"combined"),g=new Set(v.filter(k=>!d.has(k))),b=new Set(v.filter((k,N)=>!d.has(k)&&h[N].endsWith("/")));for(let k of f)b.delete(k);return{tracked:d,trackedObjectIds:p,untracked:g,gitlinks:f,nestedRepositories:b,omissions:[],overflow:null,evidence:null,initialFence:Fw(s)}}function Mr(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function Cw(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function FA(e,t){return!Mr(e.stageBefore,e.stageAfter)||!Mr(e.stageAfter,t.stageBefore)||!Mr(e.combined,t.combined)||!Mr(t.stageBefore,t.stageAfter)}async function qw(e,t,r,i,n,a){let o;try{o=await Bw(e,t,r,{...n===void 0?{}:{outputChunkBytes:n}},a)}catch(d){throw vn(d)?d:new Error("Native Git snapshot provider failed during its final selection fence",{cause:d})}let s=i.initialFence,c=Fw(o),l=Cw(s)||Cw(c),u=FA(s,c);l&&i.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),u&&i.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),i.evidence=l||u?{schema:"comet.native.git-selection.v1",status:l&&u?"overflow-and-changed":l?"overflow":"changed",...s,finalStageBefore:c.stageBefore,finalCombined:c.combined,finalStageAfter:c.stageAfter}:null,(s.combined.overflow||c.combined.overflow)&&(i.overflow={count:Math.max(1,s.combined.recordCount-s.combined.storedRecordCount,c.combined.recordCount-c.combined.storedRecordCount),hash:ee(`comet.native.git-selection-overflow.v2
165
- ${JSON.stringify({initial:s.combined,final:c.combined})}`)})}function qA(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function Rw(e){let t=F.resolve(e.paths.projectRoot),r=F.resolve(e.paths.nativeRoot),i=F.resolve(e.paths.runtimeDir),n=F.resolve(e.paths.configFile),a=F.join(t,".comet","current-change.json"),o=[],s=[],c=Buffer.alloc(32),l=0n,u=0,d=0,p=0,f=!1,m=!1,h=!1,v=()=>yt(e.execution)>=1?!0:(f=!0,h=!0,!1),g=N=>{let x=Buffer.from(`${N.type}\0${N.path}`,"utf8"),w=Ec("sha256").update("comet.native.physical-selection-record.v1\0").update(x).digest();for(let S=0;S<c.length;S+=1)c[S]^=w[S];if(l=l+BigInt(`0x${w.toString("hex")}`)&LA,d+=1,p+=x.byteLength,Buffer.byteLength(N.path,"utf8")>e.limits.maxPathBytes||p>e.limits.maxBytes){f=!0,h=!0;return}o.push(N)},b=async N=>{if(h||!v())return;let x;try{x=await re.opendir(N)}catch(C){if(!v())return;if(!me(C)&&!he(C)||N===t&&me(C))throw C;m||=he(C),f||=me(C),h=!0;return}if(!v()){try{await x.close()}catch(C){if(C.code!=="ERR_DIR_CLOSED")throw C}return}let w=!1,S;try{for(;!h&&v();){let C;try{C=await x.read()}catch(Z){if(!v())break;if(!me(Z)&&!he(Z)||N===t&&me(Z))throw Z;m||=he(Z),f||=me(Z),h=!0;break}if(!v()||C===null)break;if(u+=1,u>e.limits.maxNodes){f=!0,h=!0;break}let O=F.join(N,C.name),j=VA(t,O);if(O===n||O===a||Nt(r,O)||Nt(i,O)||e.denylist.some(Z=>Nt(Z,O))||Tt(j)!==null)continue;if(!v())break;let Q;try{Q=await re.lstat(O)}catch(Z){if(!v())break;if(!me(Z)&&!he(Z))throw Z;if(m=!0,g({path:j,type:"other"}),s.push({path:j,size:null,type:"file",reason:me(Z)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(j),h||!v())break;continue}if(!v())break;let Pe=qA(Q);if(Pe==="directory"){if(JA(e.policy,j))continue;if(!v())break;let Z;try{Z=await re.realpath(O)}catch(Pt){if(!v())break;if(!me(Pt)&&!he(Pt))throw Pt;if(m=!0,g({path:j,type:Pe}),s.push({path:j,size:null,type:"directory",reason:me(Pt)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(j),h||!v())break;continue}if(!v())break;if(!q(e.physicalProjectRoot,Z)||Nt(e.physicalNativeRoot,Z))continue;if(g({path:j,type:Pe}),await e.hooks?.afterNode?.(j),!v()||(await b(O),h))break;continue}if(g({path:j,type:Pe}),await e.hooks?.afterNode?.(j),!v()||h)break}}catch(C){w=!0,S=C}let E;try{await x.close()}catch(C){E=C}let y=v();if(w)throw S;if(y&&E!==void 0&&E.code!=="ERR_DIR_CLOSED")throw E};await b(t),v(),f?(o.length=0,d=0,p=0):(o.sort((N,x)=>N.path.localeCompare(x.path,"en")),s.sort((N,x)=>N.path.localeCompare(x.path,"en")));let k=f?ee(`comet.native.physical-selection-incomplete.v1
165
+ `,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!r&&i===null,index:s},s+=1,t!==null)t=ap(l,t);else if(r)mw(l)&&(r=!1);else if(i!==null)new RegExp(`</${i}\\s*>`,"iu").test(l)&&(i=null);else{let d=ap(l,null);if(d!==null)t=d;else{let p=l.trimStart();if(p.startsWith("<!--")&&!mw(p))r=!0;else{let f=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(p);f&&n.has(f[1].toLowerCase())&&!p.startsWith("</")&&!p.endsWith("/>")&&!new RegExp(`</${f[1]}\\s*>`,"iu").test(p)&&(i=f[1])}}}if(c===-1)break;o=c+1}}function L_(e){return[...ln(e)].map(({line:t,body:r})=>({line:t,body:r}))}function dc(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function q_(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function sp(e,t,r,i=[],n="content-hash"){let a=dc(r),o=t.replaceAll("\\","/").trim(),s=i.map(dc);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-${T(I_,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function cp(e,t,r="content-hash"){let i=new Set;for(let n of e){let a=r==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(i.has(a))throw new Error(`${t} contains duplicate acceptance criteria`);i.add(a)}return e}function M_(e){let t=null,r=null,i=0,n=0;for(let{line:a,body:o,index:s}of ln(e)){n=s+1;let c=o?op(a):null;c?.level===1&&(Ys(c.text)==="acceptanceExamples"?(i+=1,i===1&&(t=s+1)):t!==null&&r===null&&(r=s))}if(i===0||t===null)return null;if(i!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:r??n}}function lp(e,t="brief.md",r=Va.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let n=M_(e);if(n===null)return[];let a=null;for(let{line:l,body:u,index:d}of ln(e)){if(d<n.start||d>=n.end)continue;let p=u?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(p===null)continue;let f=p[1].length;a=a===null?f:Math.min(a,f)}let o=[],s=null,c=()=>{if(s!==null){if(o.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);o.push(s)}};for(let{line:l,body:u,index:d}of ln(e)){if(d<n.start||d>=n.end)continue;let p=u?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;p&&p[1].length===a?(c(),s=[p[2]]):s!==null&&s.push(l)}return c(),cp(o.map(l=>sp("brief-example",t,l.join(`
166
+ `),[],i)),"Brief",i)}function up(e,t="spec.md",r=Va.maxCriteria,i="content-hash",n={}){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native specification acceptance budget is invalid");let a=[],o=[],s=null,c=()=>{if(s===null)return;if(a.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);let l=(n.resolveBriefReferences?s.body:[]).map(u=>/^\s*(?:Acceptance|验收)\s*[::]\s*(.*)$/iu.exec(u)?.[1]).filter(u=>u!==void 0);if(l.some(u=>!/^A[1-9]\d*$/u.test(u)))throw new Error("A Spec acceptance reference must be one brief ID such as A1");if(l.length>1)throw new Error("A Spec scenario may reference only one brief acceptance criterion");a.push({...sp("spec-scenario",t,[s.title,...s.body].join(`
167
+ `),s.context,i),...l[0]===void 0?{}:{briefAcceptanceRef:l[0]}}),s=null};for(let{line:l,body:u}of ln(e)){let d=u?op(l):null,p=d?/^Scenario\s*:\s*(.*)$/iu.exec(d.text):null;if(p){for(c();o.at(-1)&&o.at(-1).level>=d.level;)o.pop();let f=dc(p[1]);if(f.length===0)throw new Error("Scenario title must not be empty");s={level:d.level,title:f,body:[],context:o.map(m=>m.text)}}else if(d){for(s!==null&&d.level<=s.level?c():s!==null&&s.body.push(l);o.at(-1)&&o.at(-1).level>=d.level;)o.pop();o.push(d)}else s!==null&&u&&s.body.push(l)}return c(),cp(a,"Specification",i)}function gw(e,t="spec.md",r=Va.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=null,c=()=>{if(s!==null){if(n.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);n.push(sp("spec-must",t,s.parts.join(" "),s.context,i)),s=null}},l=()=>a.some(u=>/^(?:non-?goals?|非目标)$/iu.test(u.text.trim()));for(let{line:u,body:d}of ln(e)){let p=d?op(u):null;if(p){for(c(),o!==null&&p.level<=o&&(o=null);a.at(-1)&&a.at(-1).level>=p.level;)a.pop();a.push(p),/^Scenario\s*:/iu.test(p.text)&&(o=p.level);continue}let f=u.trim();if(!d||o!==null||l()){c();continue}if(f.length===0||ap(u,null)!==null||f.startsWith("<!--")||f==="-->"||f==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(f)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(f)||/^(?:[-*_]\s*){3,}$/u.test(f)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(f)){c();continue}let m=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(u);if(m){c(),s={parts:[m[1]],context:a.map(h=>h.text)};continue}if(/^\|.*\|$/u.test(f)){c(),s={parts:[f],context:a.map(h=>h.text)},c();continue}s===null?s={parts:[f],context:a.map(h=>h.text)}:s.parts.push(f)}return c(),cp(n,"Specification mandatory requirements",i)}function V_(e,t){let r=e.trim().replaceAll("\\","/");if(r.length===0||q_(r)||uw.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~|[A-Za-z][A-Za-z0-9+.-]*:)/u.test(r)||r.split("/").includes(".."))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);let i=uw.posix.normalize(r);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);if(i.split("/").some(n=>n.toLowerCase()===".git"||n.toLowerCase().startsWith(".env")))throw new Error(`Acceptance evidence ${t} references sensitive content`);if(!$_.test(i))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return i}function W_(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`Acceptance evidence entry ${t} must be an object`);let r=e,i=Object.keys(r).filter(n=>!j_.has(n));if(i.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${i.join(", ")}`);return r}function ww(e){if(!Array.isArray(e))throw new Error("Native acceptance evidence block must be a JSON array");let t=new Set;return e.map((r,i)=>{let n=W_(r,i),a=n.acceptance_id;if(typeof a!="string"||!T_.test(a))throw new Error(`Acceptance evidence entry ${i} 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 V_(l,a)});if(new Set(o).size!==o.length)throw new Error(`Acceptance evidence ${a} has a duplicate evidence ref`);let s=n.status;if(s!=="passed"&&s!=="failed")throw new Error(`Acceptance evidence ${a} status is invalid`);let c;if(Object.prototype.hasOwnProperty.call(n,"skipped_reason")){if(typeof n.skipped_reason!="string"||n.skipped_reason.trim().length===0)throw new Error(`Acceptance evidence ${a} skipped_reason must be a non-empty string`);c=n.skipped_reason.trim()}if(s==="passed"&&o.length===0)throw new Error(`Acceptance evidence ${a} passed status requires evidence_refs`);if(s==="failed"&&o.length===0&&c===void 0)throw new Error(`Acceptance evidence ${a} failed status requires evidence_refs or a skipped_reason`);if(s==="passed"&&c!==void 0)throw new Error(`Acceptance evidence ${a} passed status has invalid fields`);return{acceptance_id:a,status:s,evidence_refs:o,...c===void 0?{}:{skipped_reason:c}}})}function yw(e){let t=L_(e);if(t.some(({line:l,body:u})=>!u&&(l===dw||l===pw)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let i=t.flatMap(({line:l,body:u},d)=>u&&l===dw?[d]:[]),n=t.flatMap(({line:l,body:u},d)=>u&&l===pw?[d]:[]);if(i.length!==1||n.length!==1)throw new Error("Verification must contain exactly one Native acceptance evidence block");if(i[0]>=n[0])throw new Error("Native acceptance evidence markers are out of order");let a=t.slice(i[0]+1,n[0]).map(({line:l})=>l).join(`
168
+ `).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=ww(o),c=z_(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function z_(e){let t=ww([...e]).map(r=>({...r,evidence_refs:[...r.evidence_refs].sort()})).sort((r,i)=>r.acceptance_id.localeCompare(i.acceptance_id));return JSON.stringify(t,null,2)}var I_,T_,j_,$_,O_,H_,nr,Va,dw,pw,Wa=I(()=>{"use strict";fi();ue();I_="comet.native.acceptance.v1",T_=/^acceptance-[a-f0-9]{64}$/u,j_=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),$_=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,O_=/^[a-f0-9]{64}$/u,H_=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;nr=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Va=Object.freeze({maxCriteria:1024}),dw="<!-- comet-native:acceptance-evidence:start -->",pw="<!-- comet-native:acceptance-evidence:end -->"});var dp=I(()=>{"use strict";Wa()});function pp(e,t,r,i=""){let n=Object.keys(e),a=t.filter(s=>!Object.hasOwn(e,s)),o=n.filter(s=>!t.includes(s));if(a.length||o.length)throw new za({code:"invalid-fields",path:i,context:r,missingFields:a,unknownFields:o,expectedFields:[...t]})}var za,pc=I(()=>{"use strict";za=class extends Error{issues;constructor(t){let r=[t.missingFields.length?`missing: ${t.missingFields.join(", ")}`:"",t.unknownFields.length?`unknown: ${t.unknownFields.join(", ")}`:""].filter(Boolean).join("; ");super(`${t.context} fields are invalid at ${t.path||"/"} (${r})`),this.name="NativeInputValidationError",this.issues=[t]}}});function fp(e,t){if(typeof e!="string"||!e.trim()||e.length>4e3||/^<[^>]+>$/u.test(e.trim()))throw new Error(`${t} must contain a concrete statement of at most 4000 characters`);return e.trim()}function hp(e){if(!Array.isArray(e))throw new Error("Native Builder acceptance_review must be an array");return e.map((t,r)=>{if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native Builder acceptance review entry must be an object");let i=t,n=`Native Builder acceptance_review[${r}]`;pp(i,["id","status","evidence","note"],n,`/acceptance_review/${r}`);let a=i.status;if(!["implemented-with-evidence","implemented-no-evidence","not-implemented","known-fail"].includes(a))throw new Error(`${n}.status is invalid`);if(!Array.isArray(i.evidence))throw new Error(`${n}.evidence must be an array`);return{id:fp(i.id,`${n}.id`),status:a,evidence:i.evidence.map(o=>fp(o,`${n}.evidence`)),note:fp(i.note,`${n}.note`)}})}function mp(e,t){if(!t)throw new un(e.map(({id:c})=>c),[]);let r=new Set(e.map(({id:c})=>c)),i=t.map(({id:c})=>c),n=new Set(i);if(n.size!==i.length)throw new Error("Native Builder acceptance_review contains duplicate IDs");let a=i.filter(c=>!r.has(c));if(a.length)throw new Error(`Native Builder acceptance_review contains unknown IDs: ${a.join(", ")}`);let o=e.filter(({id:c})=>!n.has(c)).map(({id:c})=>c),s=t.filter(c=>c.status!=="implemented-with-evidence"||c.evidence.length===0).map(({id:c})=>c);if(o.length||s.length)throw new un(o,s)}var un,fc=I(()=>{"use strict";pc();un=class extends Error{constructor(r,i){super(`Native Builder handoff is incomplete${r.length?`; missing: ${r.join(", ")}`:""}${i.length?`; not ready: ${i.join(", ")}`:""}. Complete acceptance_review for every requirement and its evidence before Verify`);this.missingIds=r;this.incompleteIds=i}missingIds;incompleteIds}});function vp(){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 dn,hc,Nw,Ga=I(()=>{"use strict";dn="comet.native.v4",hc="comet.native.local-execution.v4",Nw=["multi-session","single-session"]});var bp={};CS(bp,{NativePortableStateVersionConflictError:()=>Ja,appendNativePortableHistory:()=>Ua,compareAndSwapNativePortableState:()=>Sw,createNativePortableState:()=>kw,parseNativePortableState:()=>qe,readNativePortableState:()=>Br,writeNativePortableState:()=>Np});import{promises as G_}from"node:fs";function je(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function $e(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function ye(e,t,r){if(typeof e!="string"||!r?.empty&&e.length===0)throw new Error(`${t} must be ${r?.empty?"a string":"a non-empty string"}`);return e}function wp(e,t){return e===null?null:ye(e,t)}function yp(e,t){let r=ye(e,t);if(!Y_.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function pn(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function oe(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function Q_(e,t){return e===null?null:oe(e,t,Number.MIN_SAFE_INTEGER)}function pe(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Ft(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function wc(e,t){return Ft(e,t,(r,i)=>ye(r,`${t}[${i}]`))}function gi(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function fn(e,t){let r=ye(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function vc(e,t,r=!1){let i=ye(e,t);if(i.includes("\\")||i.startsWith("/")||/^[A-Za-z]:/u.test(i)||i.split("/").includes("..")||!r&&(i==="."||i.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return i}function rt(e,t){let r=je(e,t);return $e(r,new Set(["text","truncated"]),t),{text:ye(r.text,`${t}.text`,{empty:!0}),truncated:pn(r.truncated,`${t}.truncated`)}}function Z_(e,t){let r=`Native spec_changes[${t}]`,i=je(e,r);$e(i,new Set(["capability","operation","source","delta_source","base_hash"]),r);let n=ye(i.capability,`${r}.capability`);if(!U_.test(n))throw new Error(`${r}.capability is invalid`);let a=pe(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:vc(i.source,`${r}.source`),s=i.delta_source===void 0?void 0:vc(i.delta_source,`${r}.delta_source`),c=i.base_hash===void 0?void 0:i.base_hash===null?null:yp(i.base_hash,`${r}.base_hash`);if(a==="remove"&&o!==null)throw new Error(`${r} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${r} ${a} requires a source`);if(s!==void 0&&a==="remove")throw new Error(`${r} remove cannot contain delta_source`);if(s!==void 0&&c==null)throw new Error(`${r} delta_source requires a non-null base_hash`);if(c!==void 0&&s===void 0&&a!=="remove")throw new Error(`${r} base_hash requires delta_source for non-remove specs`);return{capability:n,operation:a,source:o,...s===void 0?{}:{delta_source:s},...c===void 0?{}:{base_hash:c}}}function eA(e){let t="Native workspace",r=je(e,t);$e(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=pe(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=wp(r.change_branch,`${t}.change_branch`),a=wp(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:pe(r.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(i==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(i==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(i!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:i,change_branch:n,target_branch:a,finish:o}}function tA(e){let t="Native loop",r=je(e,t);$e(r,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let i=wc(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);gi(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:pe(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:pe(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:oe(r.goal_cycle,`${t}.goal_cycle`,1),iteration:oe(r.iteration,`${t}.iteration`),attempt:oe(r.attempt,`${t}.attempt`),retry_epoch:oe(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:oe(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:oe(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:oe(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:wp(r.next_action,`${t}.next_action`)}}function rA(e,t){let r=`Native acceptance[${t}]`,i=je(e,r);$e(i,new Set(["id","source","text","result","reason"]),r);let n=ye(i.id,`${r}.id`);if(!K_.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:vc(i.source,`${r}.source`),text:ye(i.text,`${r}.text`),result:pe(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:rt(i.reason,`${r}.reason`)}}function iA(e,t){let r=`Native builder_handoff.checks[${t}]`,i=je(e,r);return $e(i,new Set(["name","result","note"]),r),{name:rt(i.name,`${r}.name`),result:pe(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:rt(i.note,`${r}.note`)}}function nA(e){let t="Native builder_handoff",r=je(e,t);$e(r,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","acceptance_review","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let i=wc(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);gi(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:je(r.review,`${t}.review`);return n&&$e(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:ye(r.candidate_id,`${t}.candidate_id`),identity_provider:ye(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:ye(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:oe(r.iteration,`${t}.iteration`,1),summary:rt(r.summary,`${t}.summary`),addressed_acceptance_ids:i,...r.acceptance_review===void 0?{}:{acceptance_review:hp(r.acceptance_review)},checks:Ft(r.checks,`${t}.checks`,iA),checks_truncated:pn(r.checks_truncated,`${t}.checks_truncated`),known_limits:Ft(r.known_limits,`${t}.known_limits`,(a,o)=>rt(a,`${t}.known_limits[${o}]`)),known_limits_truncated:pn(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:pe(n.status,["passed"],`${t}.review.status`),summary:rt(n.summary,`${t}.review.summary`),reviewer_execution_ref:ye(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:fn(r.submitted_at,`${t}.submitted_at`)}}function aA(e,t){let r=`Native blockers[${t}]`,i=je(e,r);$e(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=wc(i.acceptance_ids,`${r}.acceptance_ids`);return gi(n,`${r}.acceptance_ids`),{owner:pe(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:rt(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:pe(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function oA(e,t){let r=`Native verification.checks[${t}]`,i=je(e,r);return $e(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:ye(i.id,`${r}.id`),name:rt(i.name,`${r}.name`),argv_display:Ft(i.argv_display,`${r}.argv_display`,(n,a)=>rt(n,`${r}.argv_display[${a}]`)),argv_truncated:pn(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:vc(i.cwd_ref,`${r}.cwd_ref`,!0),status:pe(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:Q_(i.exit_code,`${r}.exit_code`),duration_ms:oe(i.duration_ms,`${r}.duration_ms`)}}function sA(e){let t="Native verification",r=je(e,t);$e(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=Ft(r.checks,`${t}.checks`,oA);gi(i.map(a=>a.id),`${t}.checks IDs`);let n=ye(r.identity_provider,`${t}.identity_provider`);return{candidate_id:ye(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:ye(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:oe(r.iteration,`${t}.iteration`,1),attempt:oe(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":pe(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:pe(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:rt(r.summary,`${t}.summary`),risks:Ft(r.risks,`${t}.risks`,(a,o)=>rt(a,`${t}.risks[${o}]`)),risks_truncated:pn(r.risks_truncated,`${t}.risks_truncated`),completed_at:fn(r.completed_at,`${t}.completed_at`)}}function bw(e,t){let r=`Native history[${t}]`,i=je(e,r);$e(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=wc(i.unresolved_ids,`${r}.unresolved_ids`);return gi(n,`${r}.unresolved_ids`),{goal_cycle:oe(i.goal_cycle,`${r}.goal_cycle`,1),iteration:oe(i.iteration,`${r}.iteration`),attempt:oe(i.attempt,`${r}.attempt`),outcome:pe(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:rt(i.summary,`${r}.summary`),completed_at:fn(i.completed_at,`${r}.completed_at`)}}function cA(e){let t="Native history_overflow.outcome_counts",r=je(e,t),i=["pass","fail","blocked","execution-error","recovery"];return $e(r,new Set(i),t),{pass:oe(r.pass,`${t}.pass`),fail:oe(r.fail,`${t}.fail`),blocked:oe(r.blocked,`${t}.blocked`),"execution-error":oe(r["execution-error"],`${t}.execution-error`),recovery:oe(r.recovery,`${t}.recovery`)}}function lA(e){let t="Native history_overflow",r=je(e,t);$e(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=oe(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:fn(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:fn(r.last_dropped_at,`${t}.last_dropped_at`);if(i===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(i>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=cA(r.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==i)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:i,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function uA(e){let t=new Set(e.acceptance.map(r=>r.id));for(let r of e.loop.previous_unresolved_ids)if(!t.has(r))throw new Error(`Native loop references unknown acceptance ID ${r}`);for(let r of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(r))throw new Error(`Native builder handoff references unknown ID ${r}`);e.builder_handoff?.acceptance_review&&mp(e.acceptance,e.builder_handoff.acceptance_review);for(let r of e.blockers)for(let i of r.acceptance_ids)if(!t.has(i))throw new Error(`Native blocker references unknown ID ${i}`);if(e.builder_handoff){if(!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let i=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!i&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function dA(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let r=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(r!==null&&e.loop.stage!==r)throw new Error(`Native status ${e.status} requires loop stage ${r}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(i=>i.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(i=>i.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function qe(e){let t=je(e,"Native portable state");if($e(t,X_,"Native portable state"),t.schema!==dn)throw new Error(`Native portable state schema must be ${dn}`);let r=ye(t.name,"Native state name");if(!J_.test(r))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let i=Ft(t.spec_changes,"Native spec_changes",Z_);gi(i.map(s=>s.capability),"Native spec change capabilities");let n=Ft(t.acceptance,"Native acceptance",rA);gi(n.map(s=>s.id),"Native acceptance IDs");let a=Ft(t.history,"Native history",bw);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:dn,name:r,language:pe(t.language,["en","zh-CN"],"Native state language"),phase:pe(t.phase,["shape","build","verify","archive"],"Native state phase"),status:pe(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:oe(t.state_version,"Native state_version",1),brief:"brief.md",...t.document_constraints_version===void 0?{}:t.document_constraints_version===1||t.document_constraints_version===2||t.document_constraints_version===3?{document_constraints_version:t.document_constraints_version}:(()=>{throw new Error("Native document_constraints_version must be 1, 2, or 3")})(),...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:yp(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:yp(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:pe(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:eA(t.workspace),loop:tA(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:nA(t.builder_handoff),blockers:Ft(t.blockers,"Native blockers",aA),verification:t.verification===null?null:sA(t.verification),history:a,history_overflow:lA(t.history_overflow),verification_result:pe(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:pe(t.verification_report,["verification.md"],"Native verification_report"),archived:pn(t.archived,"Native archived"),created_at:fn(t.created_at,"Native created_at")};return uA(o),dA(o),o}function kw(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return qe({schema:dn,name:e.name,language:e.language,phase:"shape",status:"active",state_version:1,brief:"brief.md",spec_changes:[],workspace:e.workspace??{isolation:"current",change_branch:null,target_branch:null,finish:null},loop:{stage:"shape",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:e.nextAction??null},acceptance:[],builder_handoff:null,blockers:[],verification:null,history:[],history_overflow:vp(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function Ua(e,t){let r=qe(e),i=bw(t,r.history.length),n=[...r.history,i],a={...r.history_overflow,outcome_counts:{...r.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return qe({...r,history:n,history_overflow:a})}function pA(e,t){let r=(0,gc.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`${t} is invalid YAML: ${r.errors[0].message}`);return r.toJS({mapAsMap:!1})}async function Br(e){let t=await G_.readFile(e,"utf8");return qe(pA(t,"Native portable state"))}async function Np(e,t,r={}){let i=qe(t);await $t(e,(0,gc.stringify)(i),r)}async function fA(e,t){let r=mc.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);mc.set(e,a),await r;try{return await t()}finally{i(),mc.get(e)===a&&mc.delete(e)}}async function Sw(e){return fA(e.file,async()=>{let t=oe(e.expectedStateVersion,"Native expected state version",1),r=qe(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await Br(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new Ja(t,i.state_version);return await Np(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Br(e.file);if(n.state_version!==t)throw new Ja(t,n.state_version)}}),r})}var gc,J_,U_,K_,Y_,X_,Ja,mc,gt=I(()=>{"use strict";fc();gc=Kt(It(),1);ae();Ga();J_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,U_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,K_=/^A[1-9][0-9]*$/u,Y_=/^[a-f0-9]{64}$/u,X_=new Set(["schema","name","language","phase","status","state_version","brief","document_constraints_version","shape_confirmation_hash","children_contract_hash","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),Ja=class extends Error{constructor(r,i){super(`Native state version conflict: expected ${r}, got ${i}`);this.expectedStateVersion=r;this.actualStateVersion=i;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};mc=new Map});var wi=I(()=>{"use strict"});var Ew=I(()=>{"use strict";uc();dp();gt();wi();Ga();La()});var xw,Hq,Dq,kp=I(()=>{"use strict";et();tp();Ew();xw="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",Hq=new RegExp(`^portable-archive-(${xw})\\.json$`,"u"),Dq=new RegExp(`^portable-migration-(${xw})\\.json$`,"u")});import{createHash as Cw}from"node:crypto";import{constants as Fr,promises as fe}from"node:fs";import Me from"node:path";import{TextDecoder as vA}from"node:util";function hn(e,t){let r=Me.relative(e,t);return r===""||!Me.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Me.sep}`)}function Rw(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function gA(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Pw(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Lr(e,t){return G({...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 yc(e,t){let r=await fe.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await fe.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function Nc(e,t,r){let i=Me.resolve(e),n=Me.resolve(t);if(!hn(i,n))throw new Error(`${r} is outside its managed root`);let a=[await yc(i,r)],o=i;for(let s of Me.relative(i,n).split(Me.sep).filter(Boolean)){await Oe(a,r),o=Me.join(o,s);let c=await yc(o,r);if(!hn(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await Oe(a,r),a}async function Oe(e,t){for(let r of e){let i=await fe.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!gA(r,i)||await fe.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function wA(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(t===null?64*1024:Math.min(64*1024,t+1));for(;;){let o=t===null?a.length:t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,t!==null&&n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function yi(e){let t=e.maxBytes===null?null:Rw(e.maxBytes),r=Me.resolve(e.file),i=await Nc(e.root,Me.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>yc(Me.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Oe(i,e.label);let a=await fe.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(t!==null&&a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=Pw(a),s=await fe.realpath(r);if(!hn(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>hn(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Fr.O_RDONLY:Fr.O_RDONLY|Fr.O_NOFOLLOW|Fr.O_NONBLOCK,l=await fe.open(r,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,p]=await Promise.all([fe.lstat(r),fe.realpath(r)]);if(await Oe(i,e.label),await Oe(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||p!==s||!Lr(o,u)||!Lr(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let f=await wA(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([l.stat(),fe.lstat(r),fe.realpath(r)]);if(await Oe(i,e.label),await Oe(n,e.label),!h.isFile()||h.isSymbolicLink()||v!==s||!Lr(o,m)||!Lr(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:f,hash:Cw("sha256").update(f).digest("hex"),size:f.length}}finally{await l.close()}}async function Sp(e){let t=Me.resolve(e.file),r=await Nc(e.root,Me.dirname(t),e.label),i=await Promise.all((e.forbiddenRoots??[]).map(l=>yc(Me.resolve(l),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Oe(r,e.label);let n=await fe.lstat(t);if(!n.isFile()||n.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let a=Pw(n),o=await fe.realpath(t);if(!hn(r[0].realPath,o))throw new Error(`${e.label} resolves outside its managed root`);if(i.some(l=>hn(l.realPath,o)))throw new Error(`${e.label} resolves inside an excluded root`);let s=process.platform==="win32"?Fr.O_RDONLY:Fr.O_RDONLY|Fr.O_NOFOLLOW|Fr.O_NONBLOCK,c=await fe.open(t,s);try{let l=await c.stat();await e.hooks?.afterOpen?.();let[u,d]=await Promise.all([fe.lstat(t),fe.realpath(t)]);if(await Oe(r,e.label),await Oe(i,e.label),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Lr(a,l)||!Lr(a,u))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=Cw("sha256"),f=0,m=Buffer.allocUnsafe(64*1024);for(;;){let{bytesRead:b}=await c.read(m,0,m.length,null);if(b===0)break;f+=b,p.update(m.subarray(0,b))}await e.hooks?.beforeFinalCheck?.();let[h,v,g]=await Promise.all([c.stat(),fe.lstat(t),fe.realpath(t)]);if(await Oe(r,e.label),await Oe(i,e.label),!v.isFile()||v.isSymbolicLink()||g!==o||!Lr(a,h)||!Lr(a,v))throw new Error(`${e.label} changed while reading`);return{hash:p.digest("hex"),size:f}}finally{await c.close()}}async function _w(e){let t=await yi(e),r;try{r=new vA("utf-8",{fatal:!0}).decode(t.bytes)}catch(i){throw new Error(`${e.label} is not valid UTF-8`,{cause:i})}return{...t,text:r}}async function Ya(e){let t=await Nc(e.root,e.directory,e.label),r;if(e.maxEntries===void 0)r=await fe.readdir(e.directory,{withFileTypes:!0});else{let i=Rw(e.maxEntries);r=[];let n=await fe.opendir(e.directory);try{for await(let a of n)if(r.push(a),r.length>i)throw new Error(`${e.label} exceeds ${i} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await Oe(t,e.label),{entries:r,verify:()=>Oe(t,e.label)}}async function Ep(e){let t=await Nc(e.root,e.directory,e.label);return{verify:()=>Oe(t,e.label)}}var wt=I(()=>{"use strict";ae();jt()});import{TextDecoder as NA}from"util";var Zq,bc=I(()=>{"use strict";ae();U();wt();Zq=new NA("utf-8",{fatal:!0})});var Se=I(()=>{"use strict";Je();Ba();kp();bc()});import{createHash as $w}from"crypto";import{createReadStream as kA}from"fs";async function xp(e){let t=$w("sha256");for await(let r of kA(e))t.update(r);return t.digest("hex")}function ee(e){return $w("sha256").update(e).digest("hex")}var Lt=I(()=>{"use strict"});import{createHash as Cc}from"crypto";import{spawn as Ww}from"node:child_process";import{promises as re}from"fs";import F from"path";import{performance as Ow}from"node:perf_hooks";function Gw(e){let t=e.deadlineMs??LA;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 yt(e){return Math.max(0,e.deadlineAt-Date.now())}function H(e){return yt(e)>=1}function Cp(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 gn(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function WA(e,t){let r={...VA,...t===void 0?{}:{maxNodes:t},...e};if(!Number.isSafeInteger(r.maxNodes)||r.maxNodes<1||!Number.isSafeInteger(r.maxBytes)||r.maxBytes<1||!Number.isSafeInteger(r.maxPathBytes)||r.maxPathBytes<1||r.maxPathBytes>r.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return r}async function zA(e,t){if(t.terminateTree){await t.terminateTree(e);return}let r=e.pid;if(r===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let i=process.env.SystemRoot??process.env.WINDIR,n=i&&F.win32.isAbsolute(i)?F.win32.resolve(i):"C:\\Windows",a=F.win32.join(n,"System32","taskkill.exe");if(!F.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=(p,f=!1)=>{c||(c=!0,u&&clearTimeout(u),f&&l?.kill("SIGKILL"),s(p))};try{l=Ww(a,["/pid",String(r),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>d(!1)),l.once("close",p=>d(p===0)),u=setTimeout(()=>d(!1,!0),qA),u.unref()}catch{d(!1)}});for(let s=0;s<MA;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(-r,"SIGKILL")}catch(i){if(i.code!=="ESRCH")throw i}e.kill("SIGKILL")}function Tp(e,t,r,i){let n=yt(e);if(n<1)throw Cp();let a=e.gitProcess,o=Ow.now(),s=Ww(a.command,[...a.argsPrefix??[],"-C",t,...r],{cwd:t,stdio:[i?"pipe":"ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"}),c=null,l=!1,u=null;s.once("error",m=>{c=m});let d=new Promise(m=>{s.once("close",m)}),p=setTimeout(()=>{l=!0,u=zA(s,a).then(()=>({error:null}),m=>({error:m}))},n);p.unref();let f=d.then(async m=>{if(clearTimeout(p),l){let h=await u;throw h?.error?Cp(h.error):Cp()}return{code:m,spawnError:c}}).finally(()=>ql(Ow.now()-o));return{child:s,completion:f}}function Jw(e,t){let r={...Ip,...t===void 0?{}:{maxRecords:t},...e};if(!Number.isSafeInteger(r.maxRecords)||r.maxRecords<1||!Number.isSafeInteger(r.maxBytes)||r.maxBytes<1||!Number.isSafeInteger(r.maxRecordBytes)||r.maxRecordBytes<1||r.maxRecordBytes>r.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return r}async function Sc(e,t,r,i=_p){let{child:n,completion:a}=Tp(e,t,r,!1),o=[],s=[],c=0,l=0,u=!1;n.stdout.on("data",f=>{let m=Math.max(0,i-l);m>0&&o.push(Buffer.from(f).subarray(0,m)),l+=f.byteLength,l>i&&(u=!0)}),n.stderr.on("data",f=>{if(c>=yn)return;let m=yn-c,h=Buffer.from(f).subarray(0,m);s.push(h),c+=h.byteLength});let{code:d,spawnError:p}=await a;if(d===0&&p===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${r.join(" ")} failed${p?`: ${p.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function Rp(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function Qa(e,t,r,i){if(i.outputChunkBytes!==void 0&&(!Number.isSafeInteger(i.outputChunkBytes)||i.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}=Tp(e,t,r,i.stdin!==void 0),c=[],l=Cc("sha256"),u=[],d=0,p=0,f=0,m=0,h=Buffer.alloc(0),v=!1,g=!1,b=!1,k=N=>{let x=0;for(;x<N.byteLength;){let w=N.indexOf(0,x),S=w<0?N.byteLength:w,E=N.subarray(x,S);if(!v&&E.byteLength>0&&(h.byteLength+E.byteLength>i.maxRecordBytes?(h=Buffer.alloc(0),v=!0,g=!0):h=Buffer.concat([h,E])),w<0)break;m+=1,h.byteLength===0&&!v&&(b=!0);let y=h.byteLength+1;!v&&m<=i.maxRecords&&f+y<=i.maxBytes?(c.push(h),f+=y):g=!0,h=Buffer.alloc(0),v=!1,x=w+1}};o.stdout.on("data",N=>{l.update(N),p+=N.byteLength,p>i.maxBytes&&(g=!0);let x=i.outputChunkBytes;if(x===void 0){k(N);return}for(let w=0;w<N.byteLength;w+=x)k(N.subarray(w,Math.min(N.byteLength,w+x)))}),o.stderr.on("data",N=>{if(d>=yn)return;let x=yn-d,w=Buffer.from(N).subarray(0,x);u.push(w),d+=w.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:N,spawnError:x})=>{let w=i.acceptedExitCodes??[0];if(N!==null&&w.includes(N)&&x===null&&!b&&h.byteLength===0&&!v){n({records:c,digest:l.digest("hex"),overflow:g,recordCount:m,stdoutBytes:p});return}a(new Error(`git ${r.join(" ")} failed${x?`: ${x.message}`:b||h.byteLength>0||v?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),i.stdin&&o.stdin?.end(i.stdin)})}function Ec(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 GA(e,t,r){if(r.length===0)return new Set;let i=await Qa(e,t,["check-ignore","--no-index","-z","--stdin"],{...Ip,maxRecords:Math.max(1,r.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${r.join("\0")}\0`,"utf8")});if(i.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(i.records.map(n=>{let a=Ec(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function JA(e,t,r){let{child:i,completion:n}=Tp(e,t,r,!1),a=[],o=0,s=!1;i.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),i.stderr.on("data",u=>{if(o>=yn)return;let d=yn-o,p=Buffer.from(u).subarray(0,d);a.push(p),o+=p.byteLength});let{code:c,spawnError:l}=await n;if(c===0&&l===null)return s;throw new Error(`git ${r.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function wn(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||F.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||F.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function UA(e,t){return e.map(r=>{let i=wn(r);if(i===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return i})}async function KA(e){let t=F.resolve(e);for(;;){try{return await re.lstat(F.join(t,".git")),!0}catch(i){if(i.code!=="ENOENT")throw i}let r=F.dirname(t);if(r===t)return!1;t=r}}function YA(e){return e?e.filter(t=>t&&!t.startsWith("!")).flatMap(t=>t.includes("**")?[`:(exclude,glob)${t}`]:[`:(exclude)${t}`]):[]}async function Uw(e,t,r,i={},n){let a=F.resolve(t.projectRoot),o=F.join(a,".comet","current-change.json"),c=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,o].map(f=>{let m=F.relative(a,F.resolve(f)).replaceAll("\\","/"),h=wn(m);if(h===null)throw new Error("Native Git snapshot exclusion escaped the project root");return h}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`]),...YA(n)],l={...r,...i.outputChunkBytes===void 0?{}:{outputChunkBytes:i.outputChunkBytes}},u=await Qa(e,a,["ls-files","--stage","-z",...c],l);await i.afterStageBefore?.();let d=await Qa(e,a,["ls-files","--cached","--others","--exclude-standard","-z",...c],l);await i.afterCombined?.();let p=await Qa(e,a,["ls-files","--stage","-z",...c],l);return{stagedBefore:u,combined:d,stagedAfter:p}}function Kw(e){return{stageBefore:Rp(e.stagedBefore),combined:Rp(e.combined),stageAfter:Rp(e.stagedAfter)}}async function Yw(e,t,r=Ip,i={},n){let a=F.resolve(t.projectRoot);if(!await KA(a))return null;let o;try{o=await Sc(e,a,["rev-parse","--is-inside-work-tree"])}catch(k){throw gn(k)?k:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:k})}if(o.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let s;try{s=await Uw(e,t,r,i,n)}catch(k){throw gn(k)?k:new Error("Native Git snapshot provider failed after repository detection",{cause:k})}let{stagedBefore:c,combined:l,stagedAfter:u}=s,d=new Set,p=new Map,f=new Set,m=k=>{for(let N of k){let x=Ec(N),w=x.indexOf(" ");if(w<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(x.slice(0,w))?.groups;if(!S)throw new Error("Native Git snapshot provider returned a malformed staged header");let E=wn(x.slice(w+1));if(E===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");d.add(E),S.stage==="0"&&p.set(E,S.objectId),S.mode==="160000"&&S.stage==="0"&&f.add(E)}};m(c.records),m(u.records);let h=l.records.map(Ec),v=UA(h,"combined"),g=new Set(v.filter(k=>!d.has(k))),b=new Set(v.filter((k,N)=>!d.has(k)&&h[N].endsWith("/")));for(let k of f)b.delete(k);return{tracked:d,trackedObjectIds:p,untracked:g,gitlinks:f,nestedRepositories:b,omissions:[],overflow:null,evidence:null,initialFence:Kw(s)}}function Mr(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function Hw(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function XA(e,t){return!Mr(e.stageBefore,e.stageAfter)||!Mr(e.stageAfter,t.stageBefore)||!Mr(e.combined,t.combined)||!Mr(t.stageBefore,t.stageAfter)}async function Xw(e,t,r,i,n,a){let o;try{o=await Uw(e,t,r,{...n===void 0?{}:{outputChunkBytes:n}},a)}catch(d){throw gn(d)?d:new Error("Native Git snapshot provider failed during its final selection fence",{cause:d})}let s=i.initialFence,c=Kw(o),l=Hw(s)||Hw(c),u=XA(s,c);l&&i.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),u&&i.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),i.evidence=l||u?{schema:"comet.native.git-selection.v1",status:l&&u?"overflow-and-changed":l?"overflow":"changed",...s,finalStageBefore:c.stageBefore,finalCombined:c.combined,finalStageAfter:c.stageAfter}:null,(s.combined.overflow||c.combined.overflow)&&(i.overflow={count:Math.max(1,s.combined.recordCount-s.combined.storedRecordCount,c.combined.recordCount-c.combined.storedRecordCount),hash:ee(`comet.native.git-selection-overflow.v2
169
+ ${JSON.stringify({initial:s.combined,final:c.combined})}`)})}function ZA(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function Dw(e){let t=F.resolve(e.paths.projectRoot),r=F.resolve(e.paths.nativeRoot),i=F.resolve(e.paths.runtimeDir),n=F.resolve(e.paths.configFile),a=F.join(t,".comet","current-change.json"),o=[],s=[],c=Buffer.alloc(32),l=0n,u=0,d=0,p=0,f=!1,m=!1,h=!1,v=()=>yt(e.execution)>=1?!0:(f=!0,h=!0,!1),g=N=>{let x=Buffer.from(`${N.type}\0${N.path}`,"utf8"),w=Cc("sha256").update("comet.native.physical-selection-record.v1\0").update(x).digest();for(let S=0;S<c.length;S+=1)c[S]^=w[S];if(l=l+BigInt(`0x${w.toString("hex")}`)&QA,d+=1,p+=x.byteLength,Buffer.byteLength(N.path,"utf8")>e.limits.maxPathBytes||p>e.limits.maxBytes){f=!0,h=!0;return}o.push(N)},b=async N=>{if(h||!v())return;let x;try{x=await re.opendir(N)}catch(C){if(!v())return;if(!me(C)&&!he(C)||N===t&&me(C))throw C;m||=he(C),f||=me(C),h=!0;return}if(!v()){try{await x.close()}catch(C){if(C.code!=="ERR_DIR_CLOSED")throw C}return}let w=!1,S;try{for(;!h&&v();){let C;try{C=await x.read()}catch(Z){if(!v())break;if(!me(Z)&&!he(Z)||N===t&&me(Z))throw Z;m||=he(Z),f||=me(Z),h=!0;break}if(!v()||C===null)break;if(u+=1,u>e.limits.maxNodes){f=!0,h=!0;break}let O=F.join(N,C.name),j=tI(t,O);if(O===n||O===a||Nt(r,O)||Nt(i,O)||e.denylist.some(Z=>Nt(Z,O))||Tt(j)!==null)continue;if(!v())break;let Q;try{Q=await re.lstat(O)}catch(Z){if(!v())break;if(!me(Z)&&!he(Z))throw Z;if(m=!0,g({path:j,type:"other"}),s.push({path:j,size:null,type:"file",reason:me(Z)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(j),h||!v())break;continue}if(!v())break;let Pe=ZA(Q);if(Pe==="directory"){if(aI(e.policy,j))continue;if(!v())break;let Z;try{Z=await re.realpath(O)}catch(Pt){if(!v())break;if(!me(Pt)&&!he(Pt))throw Pt;if(m=!0,g({path:j,type:Pe}),s.push({path:j,size:null,type:"directory",reason:me(Pt)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(j),h||!v())break;continue}if(!v())break;if(!q(e.physicalProjectRoot,Z)||Nt(e.physicalNativeRoot,Z))continue;if(g({path:j,type:Pe}),await e.hooks?.afterNode?.(j),!v()||(await b(O),h))break;continue}if(g({path:j,type:Pe}),await e.hooks?.afterNode?.(j),!v()||h)break}}catch(C){w=!0,S=C}let E;try{await x.close()}catch(C){E=C}let y=v();if(w)throw S;if(y&&E!==void 0&&E.code!=="ERR_DIR_CLOSED")throw E};await b(t),v(),f?(o.length=0,d=0,p=0):(o.sort((N,x)=>N.path.localeCompare(x.path,"en")),s.sort((N,x)=>N.path.localeCompare(x.path,"en")));let k=f?ee(`comet.native.physical-selection-incomplete.v1
166
170
  ${JSON.stringify({maxNodes:e.limits.maxNodes,maxBytes:e.limits.maxBytes,maxPathBytes:e.limits.maxPathBytes})}`):ee(`comet.native.physical-selection.v1
167
- ${JSON.stringify({visitedNodeCount:u,recordCount:d,encodedBytes:p,xor:c.toString("hex"),sum:l.toString(16).padStart(64,"0")})}`);return{records:o,omissions:s,evidence:{hash:k,visitedNodeCount:u,recordCount:d,storedRecordCount:o.length,encodedBytes:p,overflow:f,unstable:m}}}function Mw(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 MA(e,t){let r=e.overflow||t.overflow,i=e.unstable||t.unstable||!Mw(e,t),n=[];return r&&n.push({path:".",size:null,type:"directory",reason:"physical-enumeration-limit"}),i&&n.push({path:".",size:null,type:"directory",reason:"physical-selection-changed"}),{omissions:n,evidence:r||i?{schema:"comet.native.physical-selection.v1",status:r&&i?"overflow-and-changed":r?"overflow":"changed",before:e,after:t}:null}}function Vw(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,r)=>t.localeCompare(r,"en"))}async function Pw(e,t){let i=(await bc(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!Ow.test(i))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return ee(`gitlink:${i}`)}async function _w(e,t){let r=await Pw(e,t),i=await OA(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),n=await Pw(e,t);if(n!==r)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:n,dirty:i}}function Ya(e,t){if(Tt(t)!==null)return!1;let r=F.resolve(e.projectRoot,...t.split("/"));return!Nt(F.resolve(e.nativeRoot),r)&&!Nt(F.resolve(e.runtimeDir),r)}function VA(e,t){return F.relative(e,t).split(F.sep).join("/")}function WA(e,t){return t.map(r=>F.resolve(e,...r.split(/[\\/]/u)))}function Nt(e,t){let r=F.resolve(e),i=F.resolve(t);return i===r||q(r,i)}function me(e){return RA.has(e.code??"")}function he(e){return e.code==="ENOENT"}function zA(e,t){return ee(`comet.native.snapshot-policy.v1
168
- ${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function Ep(e,t,r){let i=new Set(t),n=[...t];for(;n.length>0;){if(r&&!r())return null;let a=n.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!i.has(a+1)&&(i.add(a+1),n.push(a+1))}return i}function GA(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function Aw(e){let t=ac(e,"Native snapshot pattern"),r=[];for(let i=0;i<t.length;i+=1){let n=t[i];n==="*"&&t[i+1]==="*"?(i+=1,t[i+1]==="/"?(i+=1,r.push({kind:"globstar-slash"})):r.push({kind:"globstar"})):n==="*"?r.push({kind:"star"}):n==="?"?r.push({kind:"question"}):r.push({kind:"literal",value:n})}return(i,n)=>{let a=n?GA(n):void 0;if(a&&!a())return!1;let o=Ep(r,new Set([0]),a);if(o===null)return!1;for(let s of i){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let u=r[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=Ep(r,c,a),o===null||o.size===0)return!1}return Ep(r,o,a)?.has(r.length)??!1}}function Ww(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>ac(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),r=[...new Set(e.exclude.map(n=>ac(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 i=zA(t,r);if("hash"in e&&e.hash!==i)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:r,hash:i},includeMatchers:t.map(Aw),excludeMatchers:r.map(Aw),excludedDirectoryPrefixes:r.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 JA(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function Iw(e,t,r){if(!e)return!0;let i=()=>H(r),n=!1;for(let a of e.includeMatchers){if(!i())return!1;if(a(t,i)){n=!0;break}}if(!n)return!1;for(let a of e.excludeMatchers)if(!i()||a(t,i))return!1;return!0}function Sc(e,t,r){let i=JSON.stringify(r);return ee(`${e}
171
+ ${JSON.stringify({visitedNodeCount:u,recordCount:d,encodedBytes:p,xor:c.toString("hex"),sum:l.toString(16).padStart(64,"0")})}`);return{records:o,omissions:s,evidence:{hash:k,visitedNodeCount:u,recordCount:d,storedRecordCount:o.length,encodedBytes:p,overflow:f,unstable:m}}}function Qw(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 eI(e,t){let r=e.overflow||t.overflow,i=e.unstable||t.unstable||!Qw(e,t),n=[];return r&&n.push({path:".",size:null,type:"directory",reason:"physical-enumeration-limit"}),i&&n.push({path:".",size:null,type:"directory",reason:"physical-selection-changed"}),{omissions:n,evidence:r||i?{schema:"comet.native.physical-selection.v1",status:r&&i?"overflow-and-changed":r?"overflow":"changed",before:e,after:t}:null}}function Zw(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,r)=>t.localeCompare(r,"en"))}async function Bw(e,t){let i=(await Sc(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!zw.test(i))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return ee(`gitlink:${i}`)}async function Fw(e,t){let r=await Bw(e,t),i=await JA(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),n=await Bw(e,t);if(n!==r)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:n,dirty:i}}function Xa(e,t){if(Tt(t)!==null)return!1;let r=F.resolve(e.projectRoot,...t.split("/"));return!Nt(F.resolve(e.nativeRoot),r)&&!Nt(F.resolve(e.runtimeDir),r)}function tI(e,t){return F.relative(e,t).split(F.sep).join("/")}function rI(e,t){return t.map(r=>F.resolve(e,...r.split(/[\\/]/u)))}function Nt(e,t){let r=F.resolve(e),i=F.resolve(t);return i===r||q(r,i)}function me(e){return FA.has(e.code??"")}function he(e){return e.code==="ENOENT"}function iI(e,t){return ee(`comet.native.snapshot-policy.v1
172
+ ${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function Pp(e,t,r){let i=new Set(t),n=[...t];for(;n.length>0;){if(r&&!r())return null;let a=n.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!i.has(a+1)&&(i.add(a+1),n.push(a+1))}return i}function nI(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function Lw(e){let t=sc(e,"Native snapshot pattern"),r=[];for(let i=0;i<t.length;i+=1){let n=t[i];n==="*"&&t[i+1]==="*"?(i+=1,t[i+1]==="/"?(i+=1,r.push({kind:"globstar-slash"})):r.push({kind:"globstar"})):n==="*"?r.push({kind:"star"}):n==="?"?r.push({kind:"question"}):r.push({kind:"literal",value:n})}return(i,n)=>{let a=n?nI(n):void 0;if(a&&!a())return!1;let o=Pp(r,new Set([0]),a);if(o===null)return!1;for(let s of i){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let u=r[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=Pp(r,c,a),o===null||o.size===0)return!1}return Pp(r,o,a)?.has(r.length)??!1}}function ey(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>sc(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),r=[...new Set(e.exclude.map(n=>sc(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 i=iI(t,r);if("hash"in e&&e.hash!==i)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:r,hash:i},includeMatchers:t.map(Lw),excludeMatchers:r.map(Lw),excludedDirectoryPrefixes:r.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 aI(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function qw(e,t,r){if(!e)return!0;let i=()=>H(r),n=!1;for(let a of e.includeMatchers){if(!i())return!1;if(a(t,i)){n=!0;break}}if(!n)return!1;for(let a of e.excludeMatchers)if(!i()||a(t,i))return!1;return!0}function xc(e,t,r){let i=JSON.stringify(r);return ee(`${e}
169
173
  ${Buffer.byteLength(t)}:${t}
170
- ${Buffer.byteLength(i)}:${i}`)}function zw(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function Gw(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(!zw(r))return e.splice(t,1),r}return null}function qr(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Qe(r,i)?G(r,i):G(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function UA(e,t,r,i){if(!H(i))return{status:"budget-exhausted"};let n;try{n=await re.open(e,"r")}catch(c){if(!H(i))return{status:"budget-exhausted"};throw c}if(!H(i))return await n.close(),{status:"budget-exhausted"};let a=Ec("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!H(i))return{status:"budget-exhausted"};let c=await n.stat();if(!H(i))return{status:"budget-exhausted"};if(!c.isFile()||!qr(r,c))return{status:"changed"};for(;;){if(!H(i))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(!H(i))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!H(i))return{status:"budget-exhausted"};let d=await n.stat();return H(i)?!d.isFile()||!qr(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 nt(e,t,r){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function mn(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function qt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Jw(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 r=F.posix.normalize(e);if(r!==e||F.posix.isAbsolute(e)||r===".."||r.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function KA(e,t){let r=it(e,`Native snapshot entry ${t}`);nt(r,bA,`Native snapshot entry ${t}`);let i=Jw(r.path,`Native snapshot entry ${t} path`);if(typeof r.hash!="string"||!xc.test(r.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(r.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:i,hash:r.hash,size:qt(r.size,`Native snapshot entry ${t} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!Ow.test(r.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=r.gitObjectId}return n}function YA(e,t){let r=it(e,`Native snapshot omission ${t}`);if(nt(r,kA,`Native snapshot omission ${t}`),!xA.has(r.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!CA.has(r.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:Jw(r.path,`Native snapshot omission ${t} path`),size:r.size===null?null:qt(r.size,`Native snapshot omission ${t} size`),type:r.type,reason:r.reason}}function XA(e){let t=it(e,"Native snapshot omission overflow");if(nt(t,SA,"Native snapshot omission overflow"),typeof t.hash!="string"||!xc.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let r=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==r)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:r,hash:t.hash,count:mn(t.count,"Native snapshot omission overflow count")}}function hn(e,t){let r=it(e,t);if(nt(r,wA,t),typeof r.hash!="string"||!xc.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let i=qt(r.recordCount,`${t} recordCount`),n=qt(r.storedRecordCount,`${t} storedRecordCount`),a=qt(r.stdoutBytes,`${t} stdoutBytes`);if(n>i||!r.overflow&&n!==i)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,recordCount:i,storedRecordCount:n,stdoutBytes:a,overflow:r.overflow}}function Tw(e){let t=it(e,"Native Git selection evidence");if(nt(t,gA,"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 r=hn(t.stageBefore,"Native Git selection stageBefore"),i=hn(t.combined,"Native Git selection combined"),n=hn(t.stageAfter,"Native Git selection stageAfter"),a=hn(t.finalStageBefore,"Native Git selection finalStageBefore"),o=hn(t.finalCombined,"Native Git selection finalCombined"),s=hn(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,i,n,a,o,s].some(d=>d.overflow),l=!Mr(r,n)||!Mr(n,a)||!Mr(i,o)||!Mr(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:r,combined:i,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function jw(e,t){let r=it(e,t);if(nt(r,NA,t),typeof r.hash!="string"||!xc.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean"||typeof r.unstable!="boolean")throw new Error(`${t} flags are invalid`);let i=qt(r.visitedNodeCount,`${t} visitedNodeCount`),n=qt(r.recordCount,`${t} recordCount`),a=qt(r.storedRecordCount,`${t} storedRecordCount`),o=qt(r.encodedBytes,`${t} encodedBytes`);if(a>n||!r.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,visitedNodeCount:i,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:r.overflow,unstable:r.unstable}}function QA(e){let t=it(e,"Native physical selection evidence");if(nt(t,yA,"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 r=jw(t.before,"Native physical selection before"),i=jw(t.after,"Native physical selection after"),n=r.overflow||i.overflow,a=r.unstable||i.unstable||!Mw(r,i);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:r,after:i}}function yi(e){let t=it(e,"Native content snapshot manifest");if(nt(t,pA,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!EA.has(t.origin))throw new Error("Native content snapshot origin is invalid");let r;if(t.capture!==void 0){let w=it(t.capture,"Native content snapshot capture");if(nt(w,mA,"Native content snapshot capture"),w.provider!=="git"&&w.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let S=w.gitSelection===void 0?void 0:Tw(w.gitSelection),E=w.physicalSelection===void 0?void 0:QA(w.physicalSelection),y=null;if(w.projection!==void 0){let C=it(w.projection,"Native content snapshot projection");if(nt(C,vA,"Native content snapshot projection"),C.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");y={provider:"git",...C.selection===void 0?{}:{selection:Tw(C.selection)}}}if(w.provider==="git"){if(E||y)throw new Error("Native Git capture cannot include physical or projection evidence");r={provider:"git",...S?{gitSelection:S}:{}}}else{if(S)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(E&&y)throw new Error("Native physical-tree capture cannot combine selection and projection");r=y?{provider:"physical-tree",projection:y}:{provider:"physical-tree",...E?{physicalSelection:E}:{}}}}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 i=it(t.limits,"Native content snapshot limits");nt(i,fA,"Native content snapshot limits");let n={maxFiles:mn(i.maxFiles,"Native snapshot maxFiles"),maxFileBytes:mn(i.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:mn(i.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:mn(i.maxManifestBytes,"Native snapshot maxManifestBytes"),...i.maxDurationMs===void 0?{}:{maxDurationMs:mn(i.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let w=it(t.policy,"Native snapshot policy");if(nt(w,hA,"Native snapshot policy"),w.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(w.include)||!Array.isArray(w.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=Ww({include:w.include,exclude:w.exclude,hash:w.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(KA),s=t.omitted.map(YA),c=qt(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:XA(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(w=>w.size>n.maxFileBytes)||o.reduce((w,S)=>w+S.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(w=>w.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>Cp||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(w=>w.reason==="git-enumeration-limit"),p=s.filter(w=>w.reason==="git-selection-changed");for(let w of[...d,...p])if(w.path!=="."||w.size!==null||w.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||p.length>1)throw new Error("Native Git selection omissions must not be duplicated");let f=r?.provider==="git"?r.gitSelection:r?.projection?.selection,m=f?.status==="overflow"||f?.status==="overflow-and-changed",h=f?.status==="changed"||f?.status==="overflow-and-changed";if(m!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(p.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let v=s.filter(w=>w.reason==="physical-enumeration-limit"),g=s.filter(w=>w.reason==="physical-selection-changed");for(let w of[...v,...g])if(w.path!=="."||w.size!==null||w.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(v.length>1||g.length>1)throw new Error("Native physical selection omissions must not be duplicated");let b=r?.physicalSelection,k=b?.status==="overflow"||b?.status==="overflow-and-changed",N=b?.status==="changed"||b?.status==="overflow-and-changed";if(k!==(v.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(N!==(g.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");return{schema:"comet.native.content-snapshot.v1",origin:t.origin,...r?{capture:r}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}}}async function Uw(e,t,r={}){let i=yi(t);if(i.capture?.provider==="git"||i.capture?.projection||i.capture?.physicalSelection)return i;let n=F.resolve(e.projectRoot),a=Hw(r),o=Dw(r.gitSelectionLimits),s=await Lw(a,e,o,r.gitSelectionHooks);if(s===null)return i;let c=new Set(Vw(s).filter(S=>Ya(e,S))),l=[...s.gitlinks].filter(S=>c.has(S)),u=[...s.nestedRepositories].filter(S=>Ya(e,S)),d=(S,E)=>E.some(y=>S===y||S.startsWith(`${y}/`)),p=S=>d(S,l),f=S=>d(S,u),m=[...i.entries.map(S=>S.path),...i.omitted.flatMap(S=>S.type==="directory"?[S.path,`${S.path}/`]:[S.path])].filter(S=>!c.has(S)&&!p(S)&&!f(S)),h=await $A(a,n,m),v=i.entries.filter(S=>!p(S.path)&&!f(S.path)&&Ya(e,S.path)&&(c.has(S.path)||!h.has(S.path)));await qw(a,e,o,s,r.gitSelectionHooks?.outputChunkBytes);let g=[...s.omissions];for(let S of l)g.push({path:S,size:null,type:"directory",reason:"legacy-gitlink-boundary"});v.sort((S,E)=>S.path.localeCompare(E.path,"en"));let b=i.omitted.filter(S=>p(S.path)||f(S.path)||!Ya(e,S.path)?!1:h.has(S.path)?c.has(S.path)||[...c].some(E=>E.startsWith(`${S.path}/`)):!0);for(let S of g)b.some(E=>E.path===S.path&&E.reason===S.reason)||b.push(S);b.sort((S,E)=>S.path.localeCompare(E.path,"en"));let k=i.omissionOverflow?.count??0,N=i.omissionOverflow?.hash??ee("comet.native.snapshot-omission-overflow.v1");s.overflow&&(k+=s.overflow.count,N=Sc(N,"git-selection",{source:"git-selection",...s.overflow}));let x=S=>{k+=1,N=Sc(N,"omission",S)};for(;b.length>Cp;){let S=Gw(b);if(S===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");x(S)}return yi({...i,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:b.length+k===0,entries:v,omitted:b,omittedCount:b.length+k,...k>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${N}`,hash:N,count:k}}:{}})}function ZA(e,t){if(!dA.test(t))throw new Error(`Invalid Native change name: ${t}`);return F.join(Y(e,t),"baseline-manifest.json")}async function Kw(e,t={}){let r={maxFiles:t.limits?.maxFiles??Nc.maxFiles,maxFileBytes:t.limits?.maxFileBytes??Nc.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??Nc.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??Nc.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},i=Ww(t.policy),n=Hw({...t,deadlineMs:t.deadlineMs??r.maxDurationMs}),a=Dw(t.gitSelectionLimits,t.maxSelectionRecords),o=TA(t.physicalSelectionLimits,t.maxSelectionRecords);if(r.maxFiles<1||r.maxFileBytes<1||r.maxTotalBytes<1||r.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=F.resolve(e.projectRoot),c=await re.realpath(s),l=F.resolve(e.nativeRoot),u=await re.realpath(l),d=F.resolve(e.runtimeDir),p=F.resolve(e.configFile),f=F.join(s,".comet","current-change.json"),m=WA(s,t.denylist??[]),h=[],v=[],g=new Map,b=new Map,k=0,N=0,x=ee("comet.native.snapshot-omission-overflow.v1"),w=0,S=!1,E=null,y=_=>{N+=1,x=Sc(x,"omission",_)},C=_=>{if(k+=1,v.length<Cp){v.push(_);return}if(zw(_)){let A=Gw(v);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");y(A),v.push(_);return}y(_)},O=_=>{k+=_.count,N+=_.count,x=Sc(x,"git-selection",{source:"git-selection",..._})},j=async(_,A)=>{h.push(_),w+=_.size,g.set(_.path,A),S||(S=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(_.path))},Q=(_,A)=>{let $=h.findIndex(te=>te.path===_);if($<0)return;let[V]=h.splice($,1);w-=V.size,g.delete(_),C(A)},Pe=async(_,A,$,V)=>{if(!$.isFile()||$.isSymbolicLink()||!H(n))return;let te;try{te=await re.realpath(_)}catch(P){if(!H(n))return;if(!me(P)&&!he(P))throw P;C({path:A,size:$.size,type:"file",reason:he(P)?"changed-during-read":"unreadable"});return}if(!H(n)||!q(c,te)||Nt(u,te))return;if(h.length>=r.maxFiles){C({path:A,size:$.size,type:"file",reason:"file-count"});return}if($.size>r.maxFileBytes){C({path:A,size:$.size,type:"file",reason:"file-size"});return}if(w+$.size>r.maxTotalBytes){C({path:A,size:$.size,type:"file",reason:"total-size"});return}let z,D,ce;try{if(z=await UA(te,$.size,$,n),z.status==="budget-exhausted"||!H(n))return;if(z.status==="changed"){C({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!H(n)||(ce=await re.realpath(_),!H(n)))return;D=await re.lstat(_)}catch(P){if(!H(n))return;if(!me(P)&&!he(P))throw P;C({path:A,size:$.size,type:"file",reason:he(P)?"changed-during-read":"unreadable"});return}if(H(n)){if(z.bytes!==$.size||ce!==te||!qr($,z.finalStat)||!qr(z.finalStat,D)||!D.isFile()||D.isSymbolicLink()||D.size!==$.size||D.mtimeMs!==$.mtimeMs||D.ctimeMs!==$.ctimeMs){C({path:A,size:D.isFile()?D.size:null,type:D.isFile()?"file":"other",reason:"changed-during-read"});return}H(n)&&await j({path:A,hash:z.hash,size:D.size,type:"file",...V===void 0?{}:{gitObjectId:V}},{kind:"file",target:_,realTarget:te,stat:D})}},Z=async(_,A,$)=>{if(!H(n))return;let V,te,z;try{if(V=await re.readlink(_,{encoding:"buffer"}),!H(n)||(z=await re.lstat(_),!H(n)))return;te=await re.readlink(_,{encoding:"buffer"})}catch(P){if(!H(n))return;if(!me(P)&&!he(P))throw P;C({path:A,size:null,type:"other",reason:he(P)?"changed-during-read":"unreadable"});return}if(!H(n))return;if(!z.isSymbolicLink()||!qr($,z)||z.mtimeMs!==$.mtimeMs||z.ctimeMs!==$.ctimeMs||!V.equals(te)){C({path:A,size:null,type:"other",reason:"changed-during-read"});return}let D=V.byteLength;if(h.length>=r.maxFiles){C({path:A,size:D,type:"other",reason:"file-count"});return}if(D>r.maxFileBytes){C({path:A,size:D,type:"other",reason:"file-size"});return}if(w+D>r.maxTotalBytes){C({path:A,size:D,type:"other",reason:"total-size"});return}let ce=Ec("sha256").update("symlink\0").update(V).digest("hex");H(n)&&await j({path:A,hash:ce,size:D,type:"file"},{kind:"symlink",target:_,rawTarget:V,stat:z})},Pt=async()=>{for(let[_,A]of[...g]){if(!H(n))return;if(A.kind==="file"){let D,ce;try{if(D=await re.realpath(A.target),!H(n))return;ce=await re.lstat(A.target)}catch(P){if(!H(n))return;if(!me(P)&&!he(P))throw P;Q(_,{path:_,size:null,type:"file",reason:me(P)?"unreadable":"changed-during-read"});continue}if(!H(n))return;(D!==A.realTarget||!ce.isFile()||ce.isSymbolicLink()||!qr(A.stat,ce)||ce.size!==A.stat.size||ce.mtimeMs!==A.stat.mtimeMs||ce.ctimeMs!==A.stat.ctimeMs)&&Q(_,{path:_,size:ce.isFile()?ce.size:null,type:ce.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let D,ce;try{if(D=await re.lstat(A.target),!H(n))return;ce=await re.readlink(A.target,{encoding:"buffer"})}catch(P){if(!H(n))return;if(!me(P)&&!he(P))throw P;Q(_,{path:_,size:null,type:"other",reason:me(P)?"unreadable":"changed-during-read"});continue}if(!H(n))return;(!D.isSymbolicLink()||!qr(A.stat,D)||D.mtimeMs!==A.stat.mtimeMs||D.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(ce))&&Q(_,{path:_,size:null,type:"other",reason:"changed-during-read"});continue}let $,V;try{if($=await re.realpath(A.target),!H(n))return;V=await re.lstat(A.target)}catch{if(!H(n))return;Q(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!H(n))return;if(!($===A.realTarget&&V.isDirectory()&&!V.isSymbolicLink()&&qr(A.stat,V)&&q(c,$)&&!Nt(u,$))){Q(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let z;try{if(!H(n))return;z=await _w(n,$)}catch(D){if(vn(D))throw D;Q(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!H(n))return;z.dirty?Q(_,{path:_,size:null,type:"directory",reason:"gitlink-dirty"}):z.hash!==A.hash&&Q(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"})}for(let[_,A]of b){if(!H(n))return;try{let $=await re.lstat(A);if(!H(n))return;C({path:_,size:$.isFile()?$.size:null,type:$.isFile()?"file":$.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch($){if(!H(n))return;if(he($))continue;if(!me($))throw $;C({path:_,size:null,type:"file",reason:"unreadable"})}}},se=await Lw(n,e,a,t.gitSelectionHooks,i?.manifest.exclude);if(se===null){let _=await Rw({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:m,policy:i,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let V of _.records){if(V.type!=="file"&&V.type!=="symlink"||g.has(V.path))continue;if(yt(n)<1)break;if(!Iw(i,V.path,n))continue;if(yt(n)<1)break;let te=F.resolve(s,...V.path.split("/")),z;try{z=await re.lstat(te)}catch(D){if(!H(n))break;if(!me(D)&&!he(D))throw D;C({path:V.path,size:null,type:"file",reason:he(D)?"changed-during-read":"unreadable"});continue}if(yt(n)<1)break;if(V.type==="symlink"&&z.isSymbolicLink()){if(await Z(te,V.path,z),yt(n)<1)break;continue}if(V.type!=="file"||!z.isFile()||z.isSymbolicLink()){C({path:V.path,size:z.isFile()?z.size:null,type:z.isDirectory()?"directory":z.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await Pe(te,V.path,z),yt(n)<1)break}yt(n)>=1&&await Pt();let A=await Rw({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:m,policy:i,limits:o}),$=MA(_.evidence,A.evidence);E=$.evidence;for(let V of[..._.omissions,...A.omissions,...$.omissions])v.some(te=>te.path===V.path&&te.reason===V.reason)||C(V)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let _=t.incrementalBaseline,A=new Map,$=!1;if(_){let P=yi(_);for(let ie of P.entries)ie.gitObjectId!==void 0&&A.set(ie.path,ie);$=A.size>0}let V=new Set,te=!0;try{let P=await Xa(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(P.overflow)$=!1,te=!1,A.clear();else for(let ie of P.records){let le=kc(ie),_e=le.indexOf(" "),Ee=_e<0?null:gn(le.slice(_e+1));if(_e!==1||Ee===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");le[0]!=="H"&&V.add(Ee)}}catch(P){if(vn(P))throw P;$=!1,te=!1,A.clear()}let z=new Set;try{let P=await bc(n,s,["ls-files","--modified","-z"],xp);for(let ie of P.toString("utf8").split("\0")){let le=gn(ie);le!==null&&z.add(le)}}catch{$=!1,te=!1,A.clear()}let D=new Set,ce=new Set;for(let P of Vw(se)){if(g.has(P)||!Ya(e,P))continue;if(yt(n)<1)break;if(!Iw(i,P,n))continue;if(yt(n)<1)break;let ie=F.resolve(s,...P.split("/"));if(ie===p||ie===f||Nt(d,ie)||m.some(Ge=>Nt(Ge,ie)))continue;if(se.gitlinks.has(P)){if(h.length>=r.maxFiles){C({path:P,size:0,type:"file",reason:"file-count"});continue}let Ge,Wo;try{[Ge,Wo]=await Promise.all([re.realpath(ie),re.lstat(ie)])}catch{C({path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(Wo.isSymbolicLink()||!Wo.isDirectory()||!q(c,Ge)||Nt(u,Ge)){C({path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let Oi=await _w(n,Ge);if(Oi.dirty){C({path:P,size:null,type:"directory",reason:"gitlink-dirty"});continue}await j({path:P,hash:Oi.hash,size:0,type:"file"},{kind:"gitlink",target:ie,realTarget:Ge,stat:Wo,hash:Oi.hash})}catch(Oi){if(vn(Oi))throw Oi;C({path:P,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let le;try{le=await re.lstat(ie)}catch(Ge){if(he(Ge)&&se.tracked.has(P)){b.set(P,ie);continue}if(!me(Ge)&&!he(Ge))throw Ge;C({path:P,size:null,type:"file",reason:he(Ge)?"changed-during-read":"unreadable"});continue}if(le.isSymbolicLink()){await Z(ie,P,le);continue}if(!le.isFile()){se.nestedRepositories.has(P)||C({path:P,size:null,type:"other",reason:"changed-during-read"});continue}let _e=se.trackedObjectIds.get(P),Ee=_e?A.get(P):void 0;if($&&Ee?.gitObjectId!==void 0&&Ee.gitObjectId===_e&&!V.has(P)&&!z.has(P)){if(h.length>=r.maxFiles){C({path:P,size:Ee.size,type:"file",reason:"file-count"});continue}if(Ee.size>r.maxFileBytes){C({path:P,size:Ee.size,type:"file",reason:"file-size"});continue}if(w+Ee.size>r.maxTotalBytes){C({path:P,size:Ee.size,type:"file",reason:"total-size"});continue}h.push({...Ee}),w+=Ee.size,D.add(P);continue}let Rh=te&&!V.has(P)&&!z.has(P)?_e:void 0;await Pe(ie,P,le,Rh),Rh!==void 0&&ce.add(P)}if(await Pt(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await qw(n,e,a,se,t.gitSelectionHooks?.outputChunkBytes,i?.manifest.exclude),D.size>0||$&&ce.size>0){let P=await bc(n,s,["ls-files","--modified","-z"],xp),ie=new Set;for(let le of P.toString("utf8").split("\0")){let _e=gn(le);_e!==null&&ie.add(_e)}for(let le of D){if(!ie.has(le))continue;let _e=h.find(Ee=>Ee.path===le);Q(le,{path:le,size:_e?.size??null,type:"file",reason:"changed-during-read"})}for(let le of ce){if(!ie.has(le))continue;let _e=h.find(Ee=>Ee.path===le);_e&&delete _e.gitObjectId}}for(let P of se.omissions)C(P);se.overflow&&O(se.overflow)}h.sort((_,A)=>_.path.localeCompare(A.path,"en")),v.sort((_,A)=>_.path.localeCompare(A.path,"en"));let lS=se===null?{provider:"physical-tree",...E?{physicalSelection:E}:{}}:{provider:"git",...se.evidence?{gitSelection:se.evidence}:{}};return{schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:lS,createdAt:(t.now??new Date).toISOString(),complete:k===0,limits:r,...i?{policy:i.manifest}:{},entries:h,omitted:v,omittedCount:k,...N>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${x}`,hash:x,count:N}}:{}}}async function _p(e,t,r={}){let n=(await Te(e.projectRoot))?.native.snapshot??Yd;return Kw(e,{...r,policy:t.policy,incrementalBaseline:t,maxSelectionRecords:n.max_selection_records,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 Cc(e,t){let r=ZA(e,t),i=we(e,r);await K(i,r);try{let n=await yw({root:i,file:r,maxBytes:null,label:"Native baseline snapshot manifest"});return yi(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}var Nc,Cp,dA,pA,fA,hA,mA,vA,gA,wA,yA,NA,bA,kA,SA,EA,xA,CA,xc,Ow,RA,wn,xp,PA,_A,AA,Rp,IA,LA,yn=I(()=>{"use strict";Hi();ae();Je();Lt();jt();U();wt();Ra();Nc={maxFiles:1e4,maxFileBytes:1024*1024*1024,maxTotalBytes:1024*1024*1024,maxManifestBytes:1024*1024*1024},Cp=1e3,dA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,pA=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),fA=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),hA=new Set(["schema","include","exclude","hash"]),mA=new Set(["provider","gitSelection","physicalSelection","projection"]),vA=new Set(["provider","selection"]),gA=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),wA=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),yA=new Set(["schema","status","before","after"]),NA=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),bA=new Set(["path","hash","size","type","gitObjectId"]),kA=new Set(["path","size","type","reason"]),SA=new Set(["ref","hash","count"]),EA=new Set(["change-created","legacy-migration","explicit"]),xA=new Set(["file","directory","other"]),CA=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"]),xc=/^[a-f0-9]{64}$/u,Ow=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,RA=new Set(["EACCES","EPERM"]),wn=64*1024,xp=64*1024,PA=6e4,_A=1e3,AA=2,Rp={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},IA={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};LA=(1n<<256n)-1n});import{execFileSync as iT}from"node:child_process";function oT(e,t){try{return zn(()=>iT("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:nT,maxBuffer:aT,windowsHide:!0}))}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new Wp(e,t,i)}}function Ve(e,t){return oT(e,t).trim()}var nT,aT,Wp,ot=I(()=>{"use strict";Hi();nT=3e4,aT=8*1024*1024,Wp=class extends Error{constructor(r,i,n){super(`git ${i.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=r;this.args=i;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr}});import{promises as pj}from"node:fs";import fj from"node:path";function Yc(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function Kc(e,t,r){let i=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(i.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...i.length>0?[`unexpected ${i.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${r} fields are invalid: ${a.join("; ")}`)}}function tN(e,t){if(!Array.isArray(e)||!e.every(r=>typeof r=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((r,i)=>r.localeCompare(i,"en"))}function yj(e){let t=new Map(e.map(a=>[a.name,a])),r=new Set,i=new Set,n=a=>{if(!i.has(a)){if(r.has(a))throw new Error(`Native children dependency cycle includes ${a}`);r.add(a);for(let o of t.get(a).depends_on)n(o);r.delete(a),i.add(a)}};for(let a of e)n(a.name)}function rN(e,t,r=t){let i=new Set(t);for(let o of e){let s=o.covers.filter(c=>!i.has(c));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=r.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function oN(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===uf&&e.acceptance_index){let n=r.requiredAcceptanceIds??t??[],a=r.allowedAcceptanceIds??n,o=Object.keys(e.acceptance_index);i.missing=n.filter(l=>!(l in e.acceptance_index)),i.extra=o.filter(l=>!a.includes(l));let s=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of o){let u=s.get(l),d=e.acceptance_index[l];u&&d&&(d.source!==u.source||d.text!==u.text)&&i.mismatched.push(l)}let c=new Set(o);for(let l of e.children)i.unknownCovers.push(...l.covers.filter(u=>!c.has(u)));return i.uncovered=o.filter(l=>!iN(e.children,l)),nN(i)?i:null}if(e.schema===xi&&t){let n=new Set(t);for(let a of e.children)i.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return i.uncovered=t.filter(a=>!iN(e.children,a)),nN(i)?i:null}return null}function iN(e,t){return e.some(r=>r.covers.includes(t))}function nN(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function Jr(e){let t=new Set(e.acceptance.map(({id:n})=>n)),r=new Set(e.acceptance.filter(({source:n})=>n===e.brief).map(({id:n})=>n)),i=new Set(r);for(let n of e.history.filter(({outcome:a})=>a==="fail"))for(let a of n.unresolved_ids)t.has(a)&&i.add(a);if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let n=[...e.history].reverse().find(({outcome:a})=>a==="fail");for(let a of n?.unresolved_ids??[])r.add(a)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...r],allowedAcceptanceIds:[...i]}}function Nj(e){let t=Yc(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),r={};for(let[i,n]of Object.entries(t)){let a=Yc(n,`Native children acceptance_index.${i}`);if(Kc(a,new Set(["source","text"]),`Native children acceptance_index.${i}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${i}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${i}.text must be a non-empty string`);r[i]={source:a.source,text:a.text}}return r}function bj(e,t,r){let i=r.requiredAcceptanceIds??t??[],n=r.allowedAcceptanceIds??i,a=Object.keys(e),o=i.filter(l=>!(l in e)),s=a.filter(l=>!n.includes(l));if(o.length>0||s.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${o.join(", ")||"none"}; extra ${s.join(", ")||"none"}`);let c=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of a){let u=c.get(l);if(!u)continue;let d=e[l];if(d.source!==u.source||d.text!==u.text){let p=["source","text"].filter(f=>d[f]!==u[f]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${p.join(", ")} exactly from the current acceptance catalog`)}}}function sN(e,t,r={}){let i=(0,aN.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=Yc(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==xi&&a!==Gr)throw Kc(n,eN,"Native children contract"),new Error(`Native children schema must be ${xi} or ${Gr}`);let o=a===xi?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(Kc(n,o==="indexed-v2"?mj:eN,"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((p,f)=>{let m=Yc(p,`Native child ${f}`);if(Kc(m,o==="indexed-v2"?wj:o==="summary-v2"?gj:vj,`Native ${s} child fields (child ${f})`),typeof m.name!="string"||!hj.test(m.name))throw new Error(`Native child ${f} name is invalid`);let h=o==="summary-v2";if(h){if(typeof m.summary!="string"||m.summary.trim().length===0)throw new Error(`Native child ${m.name} summary must be a non-empty string`);if(m.summary.length>2e3)throw new Error(`Native child ${m.name} summary exceeds 2000 characters`)}return{name:m.name,summary:h?m.summary:null,depends_on:tN(m.depends_on,`Native child ${m.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?tN(m.covers,`Native child ${m.name} covers`):[]}}),l=c.map(({name:p})=>p);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let u=new Set(l);for(let p of c){let f=p.depends_on.filter(m=>!u.has(m));if(f.length>0)throw new Error(`Native child ${p.name} depends on unknown child: ${f.join(", ")}`)}yj(c);let d=r.policy==="advisory";if(a===uf){if(o==="indexed-v2"){let p=Nj(n.acceptance_index);d||bj(p,t,r);let f=Object.keys(p);return d||rN(c,f,f),{schema:Gr,acceptance_index:p,children:c}}return{schema:Gr,children:c}}return t&&!d&&rN(c,t),{schema:xi,children:c}}async function Vt(e){let t=fj.join(e.changeDir,lf);try{await pj.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await ne({root:e.changeDir,ref:lf}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=sN(r.text,e.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?oN(a,e.acceptanceIds,e.validation??{}):null}}var aN,lf,xi,Gr,uf,hj,eN,mj,vj,gj,wj,Xc=I(()=>{"use strict";aN=Kt(It(),1);et();lf="children.yaml",xi="comet.native.children.v1",Gr="comet.native.children.v2",uf=Gr,hj=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,eN=new Set(["schema","children"]),mj=new Set(["schema","acceptance_index","children"]),vj=new Set(["name","depends_on","covers"]),gj=new Set(["name","summary","depends_on"]),wj=new Set(["name","depends_on","covers"])});var ho=I(()=>{"use strict"});var Qc=I(()=>{"use strict";uc();ho()});function lr(e,t){if(!Sj.test(e))throw new Error(`${t} must be a Git commit`)}function df(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function el(e){lr(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:i})=>i)),r=e.contract.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.depends_on],status:i.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null,acceptanceScope:pf(e.contract,i.name),contractHash:T("comet.native.supervisor-contract.v1",e.contract),builderFailureCount:0}));for(let i of r)for(let n of i.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${i.name} depends on unknown child ${n}`);return{schema:mo,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:r,history:[],finalVerification:{status:"pending",summary:null}}}function pf(e,t){let r=e.children.find(i=>i.name===t);return r.covers.length>0?r.covers.map(i=>({id:i,source:e.acceptance_index?.[i]?.source??"brief.md",text:e.acceptance_index?.[i]?.text??i})):[{id:`child:${t}`,source:"children.yaml",text:r.summary??t}]}function tl(e){let t=e.children.every(i=>i.acceptanceScope&&i.acceptanceScope.length>0&&(!i.task||i.task.acceptance&&i.task.acceptance.length>0)),r=e.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.dependsOn],covers:i.acceptanceScope?.map(({id:n})=>n)??[],status:(i.status==="ready"||i.status==="active")&&i.blocker&&[...e.history].reverse().find(n=>n.child===i.name)?.kind==="task-blocked"?"blocked":i.status,phase:null,projectRoot:i.projectRoot??i.task?.projectRoot??null,message:t?i.blocker:"Supervisor acceptance scope is unavailable; restore children.yaml and confirm Shape before continuing",builderFailureCount:i.builderFailureCount??0}));return{contractHash:null,supervisorStateVersion:e.stateVersion,confirmed:t,parentBranch:e.integration.branch,children:r,readyChildren:t?r.filter(({status:i})=>i==="ready").map(({name:i})=>i):[],allDone:t&&r.every(({status:i})=>i==="integrated"||i==="archived")}}var Sj,mo,Zc,Ci=I(()=>{"use strict";ue();Qc();Sj=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;mo="comet.native.supervisor.v2",Zc=3});import vo from"node:path";import{promises as lN}from"node:fs";function ff(e,t){return vo.join(vt(e,t),"supervisor")}function go(e,t){return vo.join(ff(e,t),"state.json")}function uN(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!==mo)throw new Error(`Native Supervisor state schema must be ${mo}`);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(n!=="checkExecution"&&(typeof a!="string"||a.length===0))throw new Error(`Native Supervisor integration field ${n} is invalid`);if(lr(t.integration.targetCommit,"Native Supervisor target commit"),lr(t.integration.headCommit,"Native Supervisor integration head commit"),t.integration.checkExecution){let n=t.integration.checkExecution;if(!n.operationId||!n.key||!n.child||!["running","completed","interrupted"].includes(n.status)||!Number.isSafeInteger(n.ownerPid)||n.ownerPid<=0)throw new Error("Native Supervisor integration check execution is invalid");lr(n.candidateCommit,"Native Supervisor integration candidate commit"),lr(n.integrationCommit,"Native Supervisor integration check commit"),cN(n.checkStates,"Native Supervisor integration")}if(!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let r=new Set,i=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(r.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(r.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.builderFailureCount!==void 0&&(!Number.isSafeInteger(n.builderFailureCount)||n.builderFailureCount<0))throw new Error(`Native Supervisor child ${n.name} Builder failure count 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&&lr(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(lr(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),i.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(i.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.checkExecution&&cN(n.task.checkExecution.checkStates,`Native Supervisor child ${n.name}`),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 Ue(e,t,r={}){try{let i=await lN.readFile(go(e,t),"utf8"),n=JSON.parse(i);if(uN(n),n.children.some(o=>!o.acceptanceScope||o.task&&!o.task.acceptance))try{let o=e;if(!o.changesDir)throw new Error("Native Supervisor upgrade requires full project paths to recover confirmed acceptance");let{readNativePortableState:s}=await Promise.resolve().then(()=>(gt(),gp)),c=await s(vo.join(o.changesDir,t,"comet-state.yaml")),l=await Vt({changeDir:vo.join(o.changesDir,t),acceptanceIds:c.acceptance.map(({id:u})=>u),validation:Jr(c)});if(!l)throw new Error("Native Supervisor upgrade requires the confirmed children contract");for(let u of n.children)l.contract.children.some(({name:d})=>d===u.name)&&(u.acceptanceScope=pf(l.contract,u.name),u.contractHash=T("comet.native.supervisor-contract.v1",l.contract),u.task&&(u.task.acceptance=structuredClone(u.acceptanceScope),u.task.contractHash=u.contractHash,u.task.verificationBoundary="child-scope-parent-reverifies-all",u.task.checksReason="not-run"))}catch(o){if(!r.diagnostics)throw o}let a=e;if(a.changesDir)try{let{readNativePortableState:o}=await Promise.resolve().then(()=>(gt(),gp)),s=await o(vo.join(a.changesDir,t,"comet-state.yaml"));s.workspace.change_branch&&(n.integration.targetBranch=s.workspace.change_branch)}catch(o){if(o.code!=="ENOENT")throw o}return n}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Ur(e,t){uN(t),await lN.mkdir(e.changesRuntimeDir,{recursive:!0}),await Ie(go(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function cN(e,t){if(e===void 0)return;if(!Array.isArray(e)||e.length===0)throw new Error(`${t} check states are invalid`);let r=new Set;for(let i of e){if(!i||typeof i.id!="string"||!i.id||r.has(i.id)||typeof i.name!="string"||!["planned","running","passed","failed","interrupted"].includes(i.status)||typeof i.repeatable!="boolean"||!Number.isSafeInteger(i.executionCount)||i.executionCount<0||!Array.isArray(i.argvDisplay)||!i.argvDisplay.every(n=>typeof n=="string")||typeof i.cwdRef!="string"||!Number.isSafeInteger(i.durationMs)||i.durationMs<0||i.exitCode!==null&&!Number.isSafeInteger(i.exitCode)||i.signal!==null&&typeof i.signal!="string"||typeof i.timedOut!="boolean"||i.startedAt!==null&&typeof i.startedAt!="string"||i.completedAt!==null&&typeof i.completedAt!="string"||i.logRef!==null&&typeof i.logRef!="string")throw new Error(`${t} check state is invalid`);r.add(i.id)}}var Kr=I(()=>{"use strict";ae();ue();Xc();U();Ci()});var hf=I(()=>{"use strict"});function ct(e){return e.replace(Ej,"$1 [REDACTED]").replace(xj,"[REDACTED PRIVATE KEY]").replace(Cj,"$1[REDACTED]@").replace(Rj,"[REDACTED TOKEN]").replace(Pj,'$1"[REDACTED]"').replace(_j,"$1$2$1$3$4[REDACTED]$4").replace(Aj,"$1$2[REDACTED]")}var Ej,xj,Cj,Rj,Pj,_j,Aj,Ri=I(()=>{"use strict";Ej=/\b(Bearer|Basic)\s+[^\s"']+/giu,xj=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,Cj=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,Rj=/\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,Pj=/("(?:[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,_j=/(["'])((?:[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,Aj=/\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});import{accessSync as rz,constants as iz,createWriteStream as nz,existsSync as az,promises as oz,statSync as jj}from"node:fs";import Pi from"node:path";function $j(e,t){let r=Pi.relative(e,t);return r===""||!Pi.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Pi.sep}`)}function dN(e,t){if(t.length===0||t.includes("\\")||Pi.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||Pi.posix.normalize(t)!==t)throw new Error("Native check cwd must be a normalized project-relative ref");let r=Pi.resolve(e),i=Pi.resolve(r,...t.split("/"));if(!$j(r,i))throw new Error("Native check cwd escaped the project root");let n;try{n=jj(i)}catch(a){throw new Error(`Native check cwd does not exist: ${t}`,{cause:a})}if(!n.isDirectory())throw new Error(`Native check cwd is not a directory: ${t}`);return i}var rl=I(()=>{"use strict";Gn();hf();Ri()});var pN=I(()=>{"use strict";ot();rl();ue()});var il=I(()=>{"use strict";ot();ae()});import{createHash as xN}from"node:crypto";import wN from"path";function Ce(e,t){return e<t?-1:e>t?1:0}function Nf(e){if(!Sf.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function l$(e,t){return e===t?0:e===null?-1:t===null?1:Ce(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 r=wN.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||wN.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function PN(e,t){return e==="."?e:Xr(e,t)}function An(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function u$(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:An(e.size,`${t} size`),type:"file"}}function d$(e,t){return{path:PN(e.path,`${t} path`),size:e.size===null?null:An(e.size,`${t} size`),type:e.type,reason:e.reason}}function p$(e,t){return Ce(e.path,t.path)||Ce(e.hash,t.hash)||e.size-t.size}function f$(e,t){return Ce(e.path,t.path)||Ce(e.reason,t.reason)||Ce(e.type,t.type)||(e.size??-1)-(t.size??-1)}function bo(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
174
+ ${Buffer.byteLength(i)}:${i}`)}function ty(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function ry(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(!ty(r))return e.splice(t,1),r}return null}function qr(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Qe(r,i)?G(r,i):G(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function oI(e,t,r,i){if(!H(i))return{status:"budget-exhausted"};let n;try{n=await re.open(e,"r")}catch(c){if(!H(i))return{status:"budget-exhausted"};throw c}if(!H(i))return await n.close(),{status:"budget-exhausted"};let a=Cc("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!H(i))return{status:"budget-exhausted"};let c=await n.stat();if(!H(i))return{status:"budget-exhausted"};if(!c.isFile()||!qr(r,c))return{status:"changed"};for(;;){if(!H(i))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(!H(i))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!H(i))return{status:"budget-exhausted"};let d=await n.stat();return H(i)?!d.isFile()||!qr(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 nt(e,t,r){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function vn(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function qt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function iy(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 r=F.posix.normalize(e);if(r!==e||F.posix.isAbsolute(e)||r===".."||r.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function sI(e,t){let r=it(e,`Native snapshot entry ${t}`);nt(r,jA,`Native snapshot entry ${t}`);let i=iy(r.path,`Native snapshot entry ${t} path`);if(typeof r.hash!="string"||!Rc.test(r.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(r.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:i,hash:r.hash,size:qt(r.size,`Native snapshot entry ${t} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!zw.test(r.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=r.gitObjectId}return n}function cI(e,t){let r=it(e,`Native snapshot omission ${t}`);if(nt(r,$A,`Native snapshot omission ${t}`),!DA.has(r.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!BA.has(r.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:iy(r.path,`Native snapshot omission ${t} path`),size:r.size===null?null:qt(r.size,`Native snapshot omission ${t} size`),type:r.type,reason:r.reason}}function lI(e){let t=it(e,"Native snapshot omission overflow");if(nt(t,OA,"Native snapshot omission overflow"),typeof t.hash!="string"||!Rc.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let r=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==r)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:r,hash:t.hash,count:vn(t.count,"Native snapshot omission overflow count")}}function mn(e,t){let r=it(e,t);if(nt(r,AA,t),typeof r.hash!="string"||!Rc.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let i=qt(r.recordCount,`${t} recordCount`),n=qt(r.storedRecordCount,`${t} storedRecordCount`),a=qt(r.stdoutBytes,`${t} stdoutBytes`);if(n>i||!r.overflow&&n!==i)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,recordCount:i,storedRecordCount:n,stdoutBytes:a,overflow:r.overflow}}function Mw(e){let t=it(e,"Native Git selection evidence");if(nt(t,_A,"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 r=mn(t.stageBefore,"Native Git selection stageBefore"),i=mn(t.combined,"Native Git selection combined"),n=mn(t.stageAfter,"Native Git selection stageAfter"),a=mn(t.finalStageBefore,"Native Git selection finalStageBefore"),o=mn(t.finalCombined,"Native Git selection finalCombined"),s=mn(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,i,n,a,o,s].some(d=>d.overflow),l=!Mr(r,n)||!Mr(n,a)||!Mr(i,o)||!Mr(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:r,combined:i,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function Vw(e,t){let r=it(e,t);if(nt(r,TA,t),typeof r.hash!="string"||!Rc.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean"||typeof r.unstable!="boolean")throw new Error(`${t} flags are invalid`);let i=qt(r.visitedNodeCount,`${t} visitedNodeCount`),n=qt(r.recordCount,`${t} recordCount`),a=qt(r.storedRecordCount,`${t} storedRecordCount`),o=qt(r.encodedBytes,`${t} encodedBytes`);if(a>n||!r.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,visitedNodeCount:i,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:r.overflow,unstable:r.unstable}}function uI(e){let t=it(e,"Native physical selection evidence");if(nt(t,IA,"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 r=Vw(t.before,"Native physical selection before"),i=Vw(t.after,"Native physical selection after"),n=r.overflow||i.overflow,a=r.unstable||i.unstable||!Qw(r,i);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:r,after:i}}function Ni(e){let t=it(e,"Native content snapshot manifest");if(nt(t,EA,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!HA.has(t.origin))throw new Error("Native content snapshot origin is invalid");let r;if(t.capture!==void 0){let w=it(t.capture,"Native content snapshot capture");if(nt(w,RA,"Native content snapshot capture"),w.provider!=="git"&&w.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let S=w.gitSelection===void 0?void 0:Mw(w.gitSelection),E=w.physicalSelection===void 0?void 0:uI(w.physicalSelection),y=null;if(w.projection!==void 0){let C=it(w.projection,"Native content snapshot projection");if(nt(C,PA,"Native content snapshot projection"),C.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");y={provider:"git",...C.selection===void 0?{}:{selection:Mw(C.selection)}}}if(w.provider==="git"){if(E||y)throw new Error("Native Git capture cannot include physical or projection evidence");r={provider:"git",...S?{gitSelection:S}:{}}}else{if(S)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(E&&y)throw new Error("Native physical-tree capture cannot combine selection and projection");r=y?{provider:"physical-tree",projection:y}:{provider:"physical-tree",...E?{physicalSelection:E}:{}}}}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 i=it(t.limits,"Native content snapshot limits");nt(i,xA,"Native content snapshot limits");let n={maxFiles:vn(i.maxFiles,"Native snapshot maxFiles"),maxFileBytes:vn(i.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:vn(i.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:vn(i.maxManifestBytes,"Native snapshot maxManifestBytes"),...i.maxDurationMs===void 0?{}:{maxDurationMs:vn(i.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let w=it(t.policy,"Native snapshot policy");if(nt(w,CA,"Native snapshot policy"),w.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(w.include)||!Array.isArray(w.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=ey({include:w.include,exclude:w.exclude,hash:w.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(sI),s=t.omitted.map(cI),c=qt(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:lI(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(w=>w.size>n.maxFileBytes)||o.reduce((w,S)=>w+S.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(w=>w.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>Ap||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(w=>w.reason==="git-enumeration-limit"),p=s.filter(w=>w.reason==="git-selection-changed");for(let w of[...d,...p])if(w.path!=="."||w.size!==null||w.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||p.length>1)throw new Error("Native Git selection omissions must not be duplicated");let f=r?.provider==="git"?r.gitSelection:r?.projection?.selection,m=f?.status==="overflow"||f?.status==="overflow-and-changed",h=f?.status==="changed"||f?.status==="overflow-and-changed";if(m!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(p.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let v=s.filter(w=>w.reason==="physical-enumeration-limit"),g=s.filter(w=>w.reason==="physical-selection-changed");for(let w of[...v,...g])if(w.path!=="."||w.size!==null||w.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(v.length>1||g.length>1)throw new Error("Native physical selection omissions must not be duplicated");let b=r?.physicalSelection,k=b?.status==="overflow"||b?.status==="overflow-and-changed",N=b?.status==="changed"||b?.status==="overflow-and-changed";if(k!==(v.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(N!==(g.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");return{schema:"comet.native.content-snapshot.v1",origin:t.origin,...r?{capture:r}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}}}async function ny(e,t,r={}){let i=Ni(t);if(i.capture?.provider==="git"||i.capture?.projection||i.capture?.physicalSelection)return i;let n=F.resolve(e.projectRoot),a=Gw(r),o=Jw(r.gitSelectionLimits),s=await Yw(a,e,o,r.gitSelectionHooks);if(s===null)return i;let c=new Set(Zw(s).filter(S=>Xa(e,S))),l=[...s.gitlinks].filter(S=>c.has(S)),u=[...s.nestedRepositories].filter(S=>Xa(e,S)),d=(S,E)=>E.some(y=>S===y||S.startsWith(`${y}/`)),p=S=>d(S,l),f=S=>d(S,u),m=[...i.entries.map(S=>S.path),...i.omitted.flatMap(S=>S.type==="directory"?[S.path,`${S.path}/`]:[S.path])].filter(S=>!c.has(S)&&!p(S)&&!f(S)),h=await GA(a,n,m),v=i.entries.filter(S=>!p(S.path)&&!f(S.path)&&Xa(e,S.path)&&(c.has(S.path)||!h.has(S.path)));await Xw(a,e,o,s,r.gitSelectionHooks?.outputChunkBytes);let g=[...s.omissions];for(let S of l)g.push({path:S,size:null,type:"directory",reason:"legacy-gitlink-boundary"});v.sort((S,E)=>S.path.localeCompare(E.path,"en"));let b=i.omitted.filter(S=>p(S.path)||f(S.path)||!Xa(e,S.path)?!1:h.has(S.path)?c.has(S.path)||[...c].some(E=>E.startsWith(`${S.path}/`)):!0);for(let S of g)b.some(E=>E.path===S.path&&E.reason===S.reason)||b.push(S);b.sort((S,E)=>S.path.localeCompare(E.path,"en"));let k=i.omissionOverflow?.count??0,N=i.omissionOverflow?.hash??ee("comet.native.snapshot-omission-overflow.v1");s.overflow&&(k+=s.overflow.count,N=xc(N,"git-selection",{source:"git-selection",...s.overflow}));let x=S=>{k+=1,N=xc(N,"omission",S)};for(;b.length>Ap;){let S=ry(b);if(S===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");x(S)}return Ni({...i,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:b.length+k===0,entries:v,omitted:b,omittedCount:b.length+k,...k>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${N}`,hash:N,count:k}}:{}})}function dI(e,t){if(!SA.test(t))throw new Error(`Invalid Native change name: ${t}`);return F.join(Y(e,t),"baseline-manifest.json")}async function ay(e,t={}){let r={maxFiles:t.limits?.maxFiles??kc.maxFiles,maxFileBytes:t.limits?.maxFileBytes??kc.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??kc.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??kc.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},i=ey(t.policy),n=Gw({...t,deadlineMs:t.deadlineMs??r.maxDurationMs}),a=Jw(t.gitSelectionLimits,t.maxSelectionRecords),o=WA(t.physicalSelectionLimits,t.maxSelectionRecords);if(r.maxFiles<1||r.maxFileBytes<1||r.maxTotalBytes<1||r.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=F.resolve(e.projectRoot),c=await re.realpath(s),l=F.resolve(e.nativeRoot),u=await re.realpath(l),d=F.resolve(e.runtimeDir),p=F.resolve(e.configFile),f=F.join(s,".comet","current-change.json"),m=rI(s,t.denylist??[]),h=[],v=[],g=new Map,b=new Map,k=0,N=0,x=ee("comet.native.snapshot-omission-overflow.v1"),w=0,S=!1,E=null,y=_=>{N+=1,x=xc(x,"omission",_)},C=_=>{if(k+=1,v.length<Ap){v.push(_);return}if(ty(_)){let A=ry(v);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");y(A),v.push(_);return}y(_)},O=_=>{k+=_.count,N+=_.count,x=xc(x,"git-selection",{source:"git-selection",..._})},j=async(_,A)=>{h.push(_),w+=_.size,g.set(_.path,A),S||(S=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(_.path))},Q=(_,A)=>{let $=h.findIndex(te=>te.path===_);if($<0)return;let[V]=h.splice($,1);w-=V.size,g.delete(_),C(A)},Pe=async(_,A,$,V)=>{if(!$.isFile()||$.isSymbolicLink()||!H(n))return;let te;try{te=await re.realpath(_)}catch(P){if(!H(n))return;if(!me(P)&&!he(P))throw P;C({path:A,size:$.size,type:"file",reason:he(P)?"changed-during-read":"unreadable"});return}if(!H(n)||!q(c,te)||Nt(u,te))return;if(h.length>=r.maxFiles){C({path:A,size:$.size,type:"file",reason:"file-count"});return}if($.size>r.maxFileBytes){C({path:A,size:$.size,type:"file",reason:"file-size"});return}if(w+$.size>r.maxTotalBytes){C({path:A,size:$.size,type:"file",reason:"total-size"});return}let z,D,ce;try{if(z=await oI(te,$.size,$,n),z.status==="budget-exhausted"||!H(n))return;if(z.status==="changed"){C({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!H(n)||(ce=await re.realpath(_),!H(n)))return;D=await re.lstat(_)}catch(P){if(!H(n))return;if(!me(P)&&!he(P))throw P;C({path:A,size:$.size,type:"file",reason:he(P)?"changed-during-read":"unreadable"});return}if(H(n)){if(z.bytes!==$.size||ce!==te||!qr($,z.finalStat)||!qr(z.finalStat,D)||!D.isFile()||D.isSymbolicLink()||D.size!==$.size||D.mtimeMs!==$.mtimeMs||D.ctimeMs!==$.ctimeMs){C({path:A,size:D.isFile()?D.size:null,type:D.isFile()?"file":"other",reason:"changed-during-read"});return}H(n)&&await j({path:A,hash:z.hash,size:D.size,type:"file",...V===void 0?{}:{gitObjectId:V}},{kind:"file",target:_,realTarget:te,stat:D})}},Z=async(_,A,$)=>{if(!H(n))return;let V,te,z;try{if(V=await re.readlink(_,{encoding:"buffer"}),!H(n)||(z=await re.lstat(_),!H(n)))return;te=await re.readlink(_,{encoding:"buffer"})}catch(P){if(!H(n))return;if(!me(P)&&!he(P))throw P;C({path:A,size:null,type:"other",reason:he(P)?"changed-during-read":"unreadable"});return}if(!H(n))return;if(!z.isSymbolicLink()||!qr($,z)||z.mtimeMs!==$.mtimeMs||z.ctimeMs!==$.ctimeMs||!V.equals(te)){C({path:A,size:null,type:"other",reason:"changed-during-read"});return}let D=V.byteLength;if(h.length>=r.maxFiles){C({path:A,size:D,type:"other",reason:"file-count"});return}if(D>r.maxFileBytes){C({path:A,size:D,type:"other",reason:"file-size"});return}if(w+D>r.maxTotalBytes){C({path:A,size:D,type:"other",reason:"total-size"});return}let ce=Cc("sha256").update("symlink\0").update(V).digest("hex");H(n)&&await j({path:A,hash:ce,size:D,type:"file"},{kind:"symlink",target:_,rawTarget:V,stat:z})},Pt=async()=>{for(let[_,A]of[...g]){if(!H(n))return;if(A.kind==="file"){let D,ce;try{if(D=await re.realpath(A.target),!H(n))return;ce=await re.lstat(A.target)}catch(P){if(!H(n))return;if(!me(P)&&!he(P))throw P;Q(_,{path:_,size:null,type:"file",reason:me(P)?"unreadable":"changed-during-read"});continue}if(!H(n))return;(D!==A.realTarget||!ce.isFile()||ce.isSymbolicLink()||!qr(A.stat,ce)||ce.size!==A.stat.size||ce.mtimeMs!==A.stat.mtimeMs||ce.ctimeMs!==A.stat.ctimeMs)&&Q(_,{path:_,size:ce.isFile()?ce.size:null,type:ce.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let D,ce;try{if(D=await re.lstat(A.target),!H(n))return;ce=await re.readlink(A.target,{encoding:"buffer"})}catch(P){if(!H(n))return;if(!me(P)&&!he(P))throw P;Q(_,{path:_,size:null,type:"other",reason:me(P)?"unreadable":"changed-during-read"});continue}if(!H(n))return;(!D.isSymbolicLink()||!qr(A.stat,D)||D.mtimeMs!==A.stat.mtimeMs||D.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(ce))&&Q(_,{path:_,size:null,type:"other",reason:"changed-during-read"});continue}let $,V;try{if($=await re.realpath(A.target),!H(n))return;V=await re.lstat(A.target)}catch{if(!H(n))return;Q(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!H(n))return;if(!($===A.realTarget&&V.isDirectory()&&!V.isSymbolicLink()&&qr(A.stat,V)&&q(c,$)&&!Nt(u,$))){Q(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let z;try{if(!H(n))return;z=await Fw(n,$)}catch(D){if(gn(D))throw D;Q(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!H(n))return;z.dirty?Q(_,{path:_,size:null,type:"directory",reason:"gitlink-dirty"}):z.hash!==A.hash&&Q(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"})}for(let[_,A]of b){if(!H(n))return;try{let $=await re.lstat(A);if(!H(n))return;C({path:_,size:$.isFile()?$.size:null,type:$.isFile()?"file":$.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch($){if(!H(n))return;if(he($))continue;if(!me($))throw $;C({path:_,size:null,type:"file",reason:"unreadable"})}}},se=await Yw(n,e,a,t.gitSelectionHooks,i?.manifest.exclude);if(se===null){let _=await Dw({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:m,policy:i,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let V of _.records){if(V.type!=="file"&&V.type!=="symlink"||g.has(V.path))continue;if(yt(n)<1)break;if(!qw(i,V.path,n))continue;if(yt(n)<1)break;let te=F.resolve(s,...V.path.split("/")),z;try{z=await re.lstat(te)}catch(D){if(!H(n))break;if(!me(D)&&!he(D))throw D;C({path:V.path,size:null,type:"file",reason:he(D)?"changed-during-read":"unreadable"});continue}if(yt(n)<1)break;if(V.type==="symlink"&&z.isSymbolicLink()){if(await Z(te,V.path,z),yt(n)<1)break;continue}if(V.type!=="file"||!z.isFile()||z.isSymbolicLink()){C({path:V.path,size:z.isFile()?z.size:null,type:z.isDirectory()?"directory":z.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await Pe(te,V.path,z),yt(n)<1)break}yt(n)>=1&&await Pt();let A=await Dw({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:m,policy:i,limits:o}),$=eI(_.evidence,A.evidence);E=$.evidence;for(let V of[..._.omissions,...A.omissions,...$.omissions])v.some(te=>te.path===V.path&&te.reason===V.reason)||C(V)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let _=t.incrementalBaseline,A=new Map,$=!1;if(_){let P=Ni(_);for(let ie of P.entries)ie.gitObjectId!==void 0&&A.set(ie.path,ie);$=A.size>0}let V=new Set,te=!0;try{let P=await Qa(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(P.overflow)$=!1,te=!1,A.clear();else for(let ie of P.records){let le=Ec(ie),_e=le.indexOf(" "),Ee=_e<0?null:wn(le.slice(_e+1));if(_e!==1||Ee===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");le[0]!=="H"&&V.add(Ee)}}catch(P){if(gn(P))throw P;$=!1,te=!1,A.clear()}let z=new Set;try{let P=await Sc(n,s,["ls-files","--modified","-z"],_p);for(let ie of P.toString("utf8").split("\0")){let le=wn(ie);le!==null&&z.add(le)}}catch{$=!1,te=!1,A.clear()}let D=new Set,ce=new Set;for(let P of Zw(se)){if(g.has(P)||!Xa(e,P))continue;if(yt(n)<1)break;if(!qw(i,P,n))continue;if(yt(n)<1)break;let ie=F.resolve(s,...P.split("/"));if(ie===p||ie===f||Nt(d,ie)||m.some(Ge=>Nt(Ge,ie)))continue;if(se.gitlinks.has(P)){if(h.length>=r.maxFiles){C({path:P,size:0,type:"file",reason:"file-count"});continue}let Ge,Go;try{[Ge,Go]=await Promise.all([re.realpath(ie),re.lstat(ie)])}catch{C({path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(Go.isSymbolicLink()||!Go.isDirectory()||!q(c,Ge)||Nt(u,Ge)){C({path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let Hi=await Fw(n,Ge);if(Hi.dirty){C({path:P,size:null,type:"directory",reason:"gitlink-dirty"});continue}await j({path:P,hash:Hi.hash,size:0,type:"file"},{kind:"gitlink",target:ie,realTarget:Ge,stat:Go,hash:Hi.hash})}catch(Hi){if(gn(Hi))throw Hi;C({path:P,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let le;try{le=await re.lstat(ie)}catch(Ge){if(he(Ge)&&se.tracked.has(P)){b.set(P,ie);continue}if(!me(Ge)&&!he(Ge))throw Ge;C({path:P,size:null,type:"file",reason:he(Ge)?"changed-during-read":"unreadable"});continue}if(le.isSymbolicLink()){await Z(ie,P,le);continue}if(!le.isFile()){se.nestedRepositories.has(P)||C({path:P,size:null,type:"other",reason:"changed-during-read"});continue}let _e=se.trackedObjectIds.get(P),Ee=_e?A.get(P):void 0;if($&&Ee?.gitObjectId!==void 0&&Ee.gitObjectId===_e&&!V.has(P)&&!z.has(P)){if(h.length>=r.maxFiles){C({path:P,size:Ee.size,type:"file",reason:"file-count"});continue}if(Ee.size>r.maxFileBytes){C({path:P,size:Ee.size,type:"file",reason:"file-size"});continue}if(w+Ee.size>r.maxTotalBytes){C({path:P,size:Ee.size,type:"file",reason:"total-size"});continue}h.push({...Ee}),w+=Ee.size,D.add(P);continue}let Ih=te&&!V.has(P)&&!z.has(P)?_e:void 0;await Pe(ie,P,le,Ih),Ih!==void 0&&ce.add(P)}if(await Pt(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await Xw(n,e,a,se,t.gitSelectionHooks?.outputChunkBytes,i?.manifest.exclude),D.size>0||$&&ce.size>0){let P=await Sc(n,s,["ls-files","--modified","-z"],_p),ie=new Set;for(let le of P.toString("utf8").split("\0")){let _e=wn(le);_e!==null&&ie.add(_e)}for(let le of D){if(!ie.has(le))continue;let _e=h.find(Ee=>Ee.path===le);Q(le,{path:le,size:_e?.size??null,type:"file",reason:"changed-during-read"})}for(let le of ce){if(!ie.has(le))continue;let _e=h.find(Ee=>Ee.path===le);_e&&delete _e.gitObjectId}}for(let P of se.omissions)C(P);se.overflow&&O(se.overflow)}h.sort((_,A)=>_.path.localeCompare(A.path,"en")),v.sort((_,A)=>_.path.localeCompare(A.path,"en"));let NS=se===null?{provider:"physical-tree",...E?{physicalSelection:E}:{}}:{provider:"git",...se.evidence?{gitSelection:se.evidence}:{}};return{schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:NS,createdAt:(t.now??new Date).toISOString(),complete:k===0,limits:r,...i?{policy:i.manifest}:{},entries:h,omitted:v,omittedCount:k,...N>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${x}`,hash:x,count:N}}:{}}}async function jp(e,t,r={}){let n=(await Te(e.projectRoot))?.native.snapshot??ep;return ay(e,{...r,policy:t.policy,incrementalBaseline:t,maxSelectionRecords:n.max_selection_records,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 Pc(e,t){let r=dI(e,t),i=we(e,r);await K(i,r);try{let n=await _w({root:i,file:r,maxBytes:null,label:"Native baseline snapshot manifest"});return Ni(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}var kc,Ap,SA,EA,xA,CA,RA,PA,_A,AA,IA,TA,jA,$A,OA,HA,DA,BA,Rc,zw,FA,yn,_p,LA,qA,MA,Ip,VA,QA,Nn=I(()=>{"use strict";Di();ae();Je();Lt();jt();U();wt();Pa();kc={maxFiles:1e4,maxFileBytes:1024*1024*1024,maxTotalBytes:1024*1024*1024,maxManifestBytes:1024*1024*1024},Ap=1e3,SA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,EA=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),xA=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),CA=new Set(["schema","include","exclude","hash"]),RA=new Set(["provider","gitSelection","physicalSelection","projection"]),PA=new Set(["provider","selection"]),_A=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),AA=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),IA=new Set(["schema","status","before","after"]),TA=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),jA=new Set(["path","hash","size","type","gitObjectId"]),$A=new Set(["path","size","type","reason"]),OA=new Set(["ref","hash","count"]),HA=new Set(["change-created","legacy-migration","explicit"]),DA=new Set(["file","directory","other"]),BA=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"]),Rc=/^[a-f0-9]{64}$/u,zw=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,FA=new Set(["EACCES","EPERM"]),yn=64*1024,_p=64*1024,LA=6e4,qA=1e3,MA=2,Ip={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},VA={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};QA=(1n<<256n)-1n});import{execFileSync as vT}from"node:child_process";function yT(e,t){try{return Gn(()=>vT("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:gT,maxBuffer:wT,windowsHide:!0}))}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new Up(e,t,i)}}function Ve(e,t){return yT(e,t).trim()}var gT,wT,Up,ot=I(()=>{"use strict";Di();gT=3e4,wT=8*1024*1024,Up=class extends Error{constructor(r,i,n){super(`git ${i.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=r;this.args=i;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr}});import{promises as xj}from"node:fs";import Cj from"node:path";function Zc(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function Qc(e,t,r){let i=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(i.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...i.length>0?[`unexpected ${i.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${r} fields are invalid: ${a.join("; ")}`)}}function pN(e,t){if(!Array.isArray(e)||!e.every(r=>typeof r=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((r,i)=>r.localeCompare(i,"en"))}function Tj(e){let t=new Map(e.map(a=>[a.name,a])),r=new Set,i=new Set,n=a=>{if(!i.has(a)){if(r.has(a))throw new Error(`Native children dependency cycle includes ${a}`);r.add(a);for(let o of t.get(a).depends_on)n(o);r.delete(a),i.add(a)}};for(let a of e)n(a.name)}function fN(e,t,r=t){let i=new Set(t);for(let o of e){let s=o.covers.filter(c=>!i.has(c));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=r.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function gN(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===hf&&e.acceptance_index){let n=r.requiredAcceptanceIds??t??[],a=r.allowedAcceptanceIds??n,o=Object.keys(e.acceptance_index);i.missing=n.filter(l=>!(l in e.acceptance_index)),i.extra=o.filter(l=>!a.includes(l));let s=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of o){let u=s.get(l),d=e.acceptance_index[l];u&&d&&(d.source!==u.source||d.text!==u.text)&&i.mismatched.push(l)}let c=new Set(o);for(let l of e.children)i.unknownCovers.push(...l.covers.filter(u=>!c.has(u)));return i.uncovered=o.filter(l=>!hN(e.children,l)),mN(i)?i:null}if(e.schema===Ci&&t){let n=new Set(t);for(let a of e.children)i.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return i.uncovered=t.filter(a=>!hN(e.children,a)),mN(i)?i:null}return null}function hN(e,t){return e.some(r=>r.covers.includes(t))}function mN(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function Jr(e){let t=new Set(e.acceptance.map(({id:n})=>n)),r=new Set(e.acceptance.filter(({source:n})=>n===e.brief).map(({id:n})=>n)),i=new Set(r);for(let n of e.history.filter(({outcome:a})=>a==="fail"))for(let a of n.unresolved_ids)t.has(a)&&i.add(a);if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let n=[...e.history].reverse().find(({outcome:a})=>a==="fail");for(let a of n?.unresolved_ids??[])r.add(a)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...r],allowedAcceptanceIds:[...i]}}function jj(e){let t=Zc(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),r={};for(let[i,n]of Object.entries(t)){let a=Zc(n,`Native children acceptance_index.${i}`);if(Qc(a,new Set(["source","text"]),`Native children acceptance_index.${i}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${i}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${i}.text must be a non-empty string`);r[i]={source:a.source,text:a.text}}return r}function $j(e,t,r){let i=r.requiredAcceptanceIds??t??[],n=r.allowedAcceptanceIds??i,a=Object.keys(e),o=i.filter(l=>!(l in e)),s=a.filter(l=>!n.includes(l));if(o.length>0||s.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${o.join(", ")||"none"}; extra ${s.join(", ")||"none"}`);let c=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of a){let u=c.get(l);if(!u)continue;let d=e[l];if(d.source!==u.source||d.text!==u.text){let p=["source","text"].filter(f=>d[f]!==u[f]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${p.join(", ")} exactly from the current acceptance catalog`)}}}function wN(e,t,r={}){let i=(0,vN.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=Zc(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==Ci&&a!==Gr)throw Qc(n,dN,"Native children contract"),new Error(`Native children schema must be ${Ci} or ${Gr}`);let o=a===Ci?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(Qc(n,o==="indexed-v2"?Pj:dN,"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((p,f)=>{let m=Zc(p,`Native child ${f}`);if(Qc(m,o==="indexed-v2"?Ij:o==="summary-v2"?Aj:_j,`Native ${s} child fields (child ${f})`),typeof m.name!="string"||!Rj.test(m.name))throw new Error(`Native child ${f} name is invalid`);let h=o==="summary-v2";if(h){if(typeof m.summary!="string"||m.summary.trim().length===0)throw new Error(`Native child ${m.name} summary must be a non-empty string`);if(m.summary.length>2e3)throw new Error(`Native child ${m.name} summary exceeds 2000 characters`)}return{name:m.name,summary:h?m.summary:null,depends_on:pN(m.depends_on,`Native child ${m.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?pN(m.covers,`Native child ${m.name} covers`):[]}}),l=c.map(({name:p})=>p);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let u=new Set(l);for(let p of c){let f=p.depends_on.filter(m=>!u.has(m));if(f.length>0)throw new Error(`Native child ${p.name} depends on unknown child: ${f.join(", ")}`)}Tj(c);let d=r.policy==="advisory";if(a===hf){if(o==="indexed-v2"){let p=jj(n.acceptance_index);d||$j(p,t,r);let f=Object.keys(p);return d||fN(c,f,f),{schema:Gr,acceptance_index:p,children:c}}return{schema:Gr,children:c}}return t&&!d&&fN(c,t),{schema:Ci,children:c}}async function Vt(e){let t=Cj.join(e.changeDir,ff);try{await xj.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await ne({root:e.changeDir,ref:ff}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=wN(r.text,e.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?gN(a,e.acceptanceIds,e.validation??{}):null}}var vN,ff,Ci,Gr,hf,Rj,dN,Pj,_j,Aj,Ij,el=I(()=>{"use strict";vN=Kt(It(),1);et();ff="children.yaml",Ci="comet.native.children.v1",Gr="comet.native.children.v2",hf=Gr,Rj=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,dN=new Set(["schema","children"]),Pj=new Set(["schema","acceptance_index","children"]),_j=new Set(["name","depends_on","covers"]),Aj=new Set(["name","summary","depends_on"]),Ij=new Set(["name","depends_on","covers"])});var vo=I(()=>{"use strict"});var tl=I(()=>{"use strict";pc();vo()});function lr(e,t){if(!Hj.test(e))throw new Error(`${t} must be a Git commit`)}function mf(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function il(e){lr(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:i})=>i)),r=e.contract.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.depends_on],status:i.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null,acceptanceScope:vf(e.contract,i.name),contractHash:T("comet.native.supervisor-contract.v1",e.contract),builderFailureCount:0}));for(let i of r)for(let n of i.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${i.name} depends on unknown child ${n}`);return{schema:go,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:r,history:[],finalVerification:{status:"pending",summary:null}}}function vf(e,t){let r=e.children.find(i=>i.name===t);return r.covers.length>0?r.covers.map(i=>({id:i,source:e.acceptance_index?.[i]?.source??"brief.md",text:e.acceptance_index?.[i]?.text??i})):[{id:`child:${t}`,source:"children.yaml",text:r.summary??t}]}function nl(e){let t=e.children.every(i=>i.acceptanceScope&&i.acceptanceScope.length>0&&(!i.task||i.task.acceptance&&i.task.acceptance.length>0)),r=e.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.dependsOn],covers:i.acceptanceScope?.map(({id:n})=>n)??[],status:(i.status==="ready"||i.status==="active")&&i.blocker&&[...e.history].reverse().find(n=>n.child===i.name)?.kind==="task-blocked"?"blocked":i.status,phase:null,projectRoot:i.projectRoot??i.task?.projectRoot??null,message:t?i.blocker:"Supervisor acceptance scope is unavailable; restore children.yaml and confirm Shape before continuing",builderFailureCount:i.builderFailureCount??0}));return{contractHash:null,supervisorStateVersion:e.stateVersion,confirmed:t,parentBranch:e.integration.branch,children:r,readyChildren:t?r.filter(({status:i})=>i==="ready").map(({name:i})=>i):[],allDone:t&&r.every(({status:i})=>i==="integrated"||i==="archived")}}var Hj,go,rl,Ri=I(()=>{"use strict";ue();tl();Hj=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;go="comet.native.supervisor.v2",rl=3});import wo from"node:path";import{promises as NN}from"node:fs";function gf(e,t){return wo.join(vt(e,t),"supervisor")}function yo(e,t){return wo.join(gf(e,t),"state.json")}function bN(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!==go)throw new Error(`Native Supervisor state schema must be ${go}`);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(n!=="checkExecution"&&(typeof a!="string"||a.length===0))throw new Error(`Native Supervisor integration field ${n} is invalid`);if(lr(t.integration.targetCommit,"Native Supervisor target commit"),lr(t.integration.headCommit,"Native Supervisor integration head commit"),t.integration.checkExecution){let n=t.integration.checkExecution;if(!n.operationId||!n.key||!n.child||!["running","completed","interrupted"].includes(n.status)||!Number.isSafeInteger(n.ownerPid)||n.ownerPid<=0)throw new Error("Native Supervisor integration check execution is invalid");lr(n.candidateCommit,"Native Supervisor integration candidate commit"),lr(n.integrationCommit,"Native Supervisor integration check commit"),yN(n.checkStates,"Native Supervisor integration")}if(!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let r=new Set,i=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(r.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(r.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.builderFailureCount!==void 0&&(!Number.isSafeInteger(n.builderFailureCount)||n.builderFailureCount<0))throw new Error(`Native Supervisor child ${n.name} Builder failure count 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&&lr(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(lr(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),i.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(i.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.checkExecution&&yN(n.task.checkExecution.checkStates,`Native Supervisor child ${n.name}`),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 Ue(e,t,r={}){try{let i=await NN.readFile(yo(e,t),"utf8"),n=JSON.parse(i);if(bN(n),n.children.some(o=>!o.acceptanceScope||o.task&&!o.task.acceptance))try{let o=e;if(!o.changesDir)throw new Error("Native Supervisor upgrade requires full project paths to recover confirmed acceptance");let{readNativePortableState:s}=await Promise.resolve().then(()=>(gt(),bp)),c=await s(wo.join(o.changesDir,t,"comet-state.yaml")),l=await Vt({changeDir:wo.join(o.changesDir,t),acceptanceIds:c.acceptance.map(({id:u})=>u),validation:Jr(c)});if(!l)throw new Error("Native Supervisor upgrade requires the confirmed children contract");for(let u of n.children)l.contract.children.some(({name:d})=>d===u.name)&&(u.acceptanceScope=vf(l.contract,u.name),u.contractHash=T("comet.native.supervisor-contract.v1",l.contract),u.task&&(u.task.acceptance=structuredClone(u.acceptanceScope),u.task.contractHash=u.contractHash,u.task.verificationBoundary="child-scope-parent-reverifies-all",u.task.checksReason="not-run"))}catch(o){if(!r.diagnostics)throw o}let a=e;if(a.changesDir)try{let{readNativePortableState:o}=await Promise.resolve().then(()=>(gt(),bp)),s=await o(wo.join(a.changesDir,t,"comet-state.yaml"));s.workspace.change_branch&&(n.integration.targetBranch=s.workspace.change_branch)}catch(o){if(o.code!=="ENOENT")throw o}return n}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Ur(e,t){bN(t),await NN.mkdir(e.changesRuntimeDir,{recursive:!0}),await Ie(yo(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function yN(e,t){if(e===void 0)return;if(!Array.isArray(e)||e.length===0)throw new Error(`${t} check states are invalid`);let r=new Set;for(let i of e){if(!i||typeof i.id!="string"||!i.id||r.has(i.id)||typeof i.name!="string"||!["planned","running","passed","failed","interrupted"].includes(i.status)||typeof i.repeatable!="boolean"||!Number.isSafeInteger(i.executionCount)||i.executionCount<0||!Array.isArray(i.argvDisplay)||!i.argvDisplay.every(n=>typeof n=="string")||typeof i.cwdRef!="string"||!Number.isSafeInteger(i.durationMs)||i.durationMs<0||i.exitCode!==null&&!Number.isSafeInteger(i.exitCode)||i.signal!==null&&typeof i.signal!="string"||typeof i.timedOut!="boolean"||i.startedAt!==null&&typeof i.startedAt!="string"||i.completedAt!==null&&typeof i.completedAt!="string"||i.logRef!==null&&typeof i.logRef!="string")throw new Error(`${t} check state is invalid`);r.add(i.id)}}var Kr=I(()=>{"use strict";ae();ue();el();U();Ri()});var wf=I(()=>{"use strict"});function ct(e){return e.replace(Dj,"$1 [REDACTED]").replace(Bj,"[REDACTED PRIVATE KEY]").replace(Fj,"$1[REDACTED]@").replace(Lj,"[REDACTED TOKEN]").replace(qj,'$1"[REDACTED]"').replace(Mj,"$1$2$1$3$4[REDACTED]$4").replace(Vj,"$1$2[REDACTED]")}var Dj,Bj,Fj,Lj,qj,Mj,Vj,Pi=I(()=>{"use strict";Dj=/\b(Bearer|Basic)\s+[^\s"']+/giu,Bj=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,Fj=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,Lj=/\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,qj=/("(?:[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,Mj=/(["'])((?:[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,Vj=/\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});import{accessSync as mz,constants as vz,createWriteStream as gz,existsSync as wz,promises as yz,statSync as Gj}from"node:fs";import _i from"node:path";function Jj(e,t){let r=_i.relative(e,t);return r===""||!_i.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${_i.sep}`)}function kN(e,t){if(t.length===0||t.includes("\\")||_i.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||_i.posix.normalize(t)!==t)throw new Error("Native check cwd must be a normalized project-relative ref");let r=_i.resolve(e),i=_i.resolve(r,...t.split("/"));if(!Jj(r,i))throw new Error("Native check cwd escaped the project root");let n;try{n=Gj(i)}catch(a){throw new Error(`Native check cwd does not exist: ${t}`,{cause:a})}if(!n.isDirectory())throw new Error(`Native check cwd is not a directory: ${t}`);return i}var al=I(()=>{"use strict";Jn();wf();Pi()});var SN=I(()=>{"use strict";ot();al();ue()});var ol=I(()=>{"use strict";ot();ae()});import{createHash as HN}from"node:crypto";import _N from"path";function Ce(e,t){return e<t?-1:e>t?1:0}function Ef(e){if(!Rf.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function k$(e,t){return e===t?0:e===null?-1:t===null?1:Ce(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 r=_N.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||_N.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function FN(e,t){return e==="."?e:Xr(e,t)}function In(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function S$(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:In(e.size,`${t} size`),type:"file"}}function E$(e,t){return{path:FN(e.path,`${t} path`),size:e.size===null?null:In(e.size,`${t} size`),type:e.type,reason:e.reason}}function x$(e,t){return Ce(e.path,t.path)||Ce(e.hash,t.hash)||e.size-t.size}function C$(e,t){return Ce(e.path,t.path)||Ce(e.reason,t.reason)||Ce(e.type,t.type)||(e.size??-1)-(t.size??-1)}function So(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
171
175
  `,"utf8")}function Yr(e,t,r){let i=`${t}
172
- ${Yn(r)}`;e.update(`${Buffer.byteLength(i,"utf8")}:`),e.update(i)}function h$(e){if(bo(e)<=Ai)return e;let t=[...e.entries],r=[...e.omitted],i=e.omittedCount,n=e.omissionOverflow?.count??0,a=xN("sha256");a.update(`${o$}
173
- `),e.omissionOverflow&&Yr(a,"existing-overflow",e.omissionOverflow);let o=(p,f)=>{f||(i+=1),n+=1,Yr(a,"omission",p)},s=p=>{i+=1,n+=1,Yr(a,"entry",p)},c=()=>{for(let p=r.length-1;p>=0;p-=1){let f=r[p];if(!(f.reason==="git-enumeration-limit"||f.reason==="git-selection-changed"||f.reason==="physical-enumeration-limit"||f.reason==="physical-selection-changed"))return r.splice(p,1),f}return null},l=()=>({...e,complete:i===0,entries:t,omitted:r,omittedCount:i,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:n}}),u=l();for(;bo(u)>Ai;){if(r.filter(f=>f.reason!=="git-enumeration-limit"&&f.reason!=="git-selection-changed"&&f.reason!=="physical-enumeration-limit"&&f.reason!=="physical-selection-changed").length>0){let f=Math.max(1,Math.ceil(r.length/4));for(let m=0;m<f;m+=1){let h=c();if(h===null)break;o(h,!0)}}else if(t.length>0){let f=Math.max(1,Math.ceil(t.length/4));for(let m of t.splice(-f))s(m)}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 bf(e){let t=yi(e),r=t.entries.map((n,a)=>u$(n,`Snapshot entry ${a}`));if(r.sort(p$),new Set(r.map(n=>n.path)).size!==r.length)throw new Error("Snapshot entries must not contain duplicate paths");let i=t.omitted.map((n,a)=>d$(n,`Snapshot omission ${a}`));return i.sort(f$),h$({schema:CN,origin:t.origin,...t.capture?{capture:t.capture}:{},complete:t.complete,limits:{maxFiles:t.limits.maxFiles,maxFileBytes:t.limits.maxFileBytes,maxTotalBytes:t.limits.maxTotalBytes,maxManifestBytes:t.limits.maxManifestBytes,...t.limits.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},...t.policy?{policy:t.policy}:{},entries:r,omitted:i,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:{ref:t.omissionOverflow.ref,hash:t.omissionOverflow.hash,count:t.omissionOverflow.count}}:{}})}function ko(e){let t=new Map;for(let[r,i]of e.entries()){if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${r} kind is invalid`);let n={path:Xr(i.path,`Declared artifact ${r} path`),kind:i.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((r,i)=>Ce(r.path,i.path)||Ce(r.kind,i.kind))}function So(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function yN(e){return e?{hash:e.hash,size:e.size}:null}function Ef(e,t,r){let i=0,n=0;for(;i<e.entries.length||n<t.entries.length;){let a=e.entries[i],o=t.entries[n],s=a===void 0?1:o===void 0?-1:Ce(a.path,o.path),c=s<=0?a:void 0,l=s>=0?o:void 0;if(s<=0&&(i+=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&&r({path:u,kind:c?l?"modified":"removed":"added",before:yN(c),after:yN(l)})}}function _N(e,t){return{...e,attributedTo:t.filter(r=>So(r,e.path))}}function xf(e){let t=ko(e.declaredArtifacts),r=[];return Ef(e.baseline,e.current,i=>{r.push(_N(i,t))}),r}function ur(e,t){return{id:`scope:${T(n$,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function m$(e,t){let r=t.omitted.map(i=>ur({kind:"snapshot-omission",source:e,path:i.path,evidence:{reason:i.reason,size:i.size,type:i.type}},`${e} snapshot omitted ${i.path}: ${i.reason}`));return t.complete||r.push(ur({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&r.push(ur({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`)),r}function NN(e,t){return m$(e,{...t,omitted:[]}).filter(r=>r.kind!=="snapshot-omission")}function kf(e,t){return Ce(e.kind,t.kind)||Ce(e.source,t.source)||l$(e.path,t.path)||Ce(e.id,t.id)}function v$(e){return[...new Map(e.map(r=>[r.id,r])).values()].sort(kf)}function AN(e){return[...new Set(e.map((t,r)=>Xr(t,`Git path ${r}`)))].sort(Ce)}function bN(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 g$(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 IN(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=AN(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:bN(e.baseCommit,"Native external drift base commit"),targetBranch:g$(e.targetBranch,"Native external drift target branch"),targetCommit:bN(e.targetCommit,"Native external drift target commit"),paths:t}}function TN(e){if(typeof e.contractHash!="string"||!Sf.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:ko(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:AN(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:IN(e.externalDrift)}}}function w$(e,t,r,i,n){let a=[],o=i===void 0?null:new Set(i),s=[],c=[],l=0,u=!1,d=0,p=0;return Ef(e,t,f=>{let m=r.some(h=>So(h,f.path));if(d+=1,c.push(f.path),!m&&!n?.has(f.path)&&(p+=1),o?.has(f.path)&&s.push(f.path),!u&&a.length<s$){let h=_N(f,r),v=bo(h);l+v<=Ai?(a.push(h),l+=v):u=!0}}),{candidates:a,gitPathsPresentInChanges:s,changePaths:c,totalChanges:d,totalUnattributed:p}}function jN(e,t){return ur({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 y$(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 r={changes:An(Number(t[1]),"Scope overflow change count"),unresolved:An(Number(t[2]),"Scope overflow unresolved count"),unattributed:An(Number(t[3]),"Scope overflow unattributed count")},i=_i(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(jN(i,r)))throw new Error("Implementation scope detail overflow is inconsistent");return{...r,hash:i}}function N$(e){let t=xN("sha256");t.update(`${a$}
174
- `);let r=0;Ef(e.baseline,e.current,n=>{if(r>=e.detailedChangeCount){Yr(t,"change",n);let a=0;for(let o of e.declaredArtifacts)So(o,n.path)&&(a+=1,Yr(t,"change-attribution",o));Yr(t,"change-end",{attributionCount:a}),a===0&&Yr(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}r+=1});let i=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)i>=e.detailedOmissionCount&&Yr(t,"snapshot-omission",{source:n,...o}),i+=1;return t.digest("hex")}function $N(e,t,r){let{contractHash:i,declaredArtifacts:n,noCodeReason:a}=r,o=w$(e,t,n,r.gitChangedPaths,r.externalDrift?new Set(r.externalDrift.paths):void 0);if(r.externalDrift){let S=new Set(r.externalDrift.paths),E=new Set(o.changePaths),y=r.externalDrift.paths.filter(C=>!E.has(C)||n.some(O=>So(O,C)));if(y.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${y.slice(0,8).join(", ")}`);if(S.size!==r.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=T(yo,e),c=T(yo,t),l=[],u=new Set(r.externalDrift?.paths??[]);for(let[S,E]of[["baseline",e],["current",t]])for(let y of E.omitted){if(l.length>=c$)break;l.push(ur({kind:"snapshot-omission",source:S,path:y.path,evidence:{reason:y.reason,size:y.size,type:y.type}},`${S} snapshot omitted ${y.path}: ${y.reason}`))}let d=e.omitted.length+t.omitted.length,p=[...NN("baseline",e),...NN("current",t),...o.totalChanges===0&&a===null?[ur({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")]:[]],f=()=>{if(r.gitChangedPaths===void 0)return;let S=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:r.gitChangedPaths,pathsPresentInSnapshotChanges:r.gitChangedPaths.filter(E=>S.has(E)),pathsAbsentFromSnapshotChanges:r.gitChangedPaths.filter(E=>!S.has(E))}},m=S=>{let E=o.candidates.slice(0,S.detailedChangeCount),y=E.filter(se=>se.attributedTo.length===0&&!u.has(se.path)),C=o.totalChanges-E.length,O=o.totalUnattributed-y.length,j=d-S.detailedOmissionCount,Q=O+j,Pe=[...y.map(se=>ur({kind:"unattributed-change",source:"implementation-scope",path:se.path,evidence:{after:se.after,before:se.before,changeKind:se.kind}},`Changed path is not covered by a declared artifact: ${se.path}`)),...l.slice(0,S.detailedOmissionCount),...p,...Q>0?[jN(S.overflowHash,{changes:C,unattributed:O,unresolved:Q})]:[]],Z=v$(Pe),Pt=S.includeGitAdvisory?f():void 0;return{schema:yf,contractHash:i,baselineProjectionRef:Nf(s),baselineProjectionHash:s,currentProjectionRef:Nf(c),currentProjectionHash:c,complete:Z.length===0,declaredArtifacts:n,changes:E,unattributed:y,unresolvedScopes:Z,noCodeReason:a,...Pt?{gitAdvisory:Pt}:{},...r.externalDrift?{externalDrift:r.externalDrift}:{}}},h=o.candidates.length,v=l.length,g=r.gitChangedPaths!==void 0,b="0".repeat(64);for(;;){let S=m({detailedChangeCount:h,detailedOmissionCount:v,includeGitAdvisory:g,overflowHash:b});if(bo({...S,scopeHash:b})<=Ai)break;if(g){g=!1;continue}if(v>0){v-=Math.max(1,Math.ceil(v/4));continue}if(h>0){h-=Math.max(1,Math.ceil(h/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let N=o.totalChanges>h||d>v?N$({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:h,detailedOmissionCount:v}):b,x=m({detailedChangeCount:h,detailedOmissionCount:v,includeGitAdvisory:g,overflowHash:N}),w={...x,scopeHash:T(RN,x)};if(bo(w)>Ai)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return w}function Cf(e){let t=bf(e.baseline),r=bf(e.current),i=TN(e);return{authority:i,baseline:t,current:r,scope:$N(t,r,i)}}function Wt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function zt(e,t,r,i){let n=new Set([...t,...r]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${i} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${i} is missing field(s): ${o.join(", ")}`)}function _i(e,t){if(typeof e!="string"||!Sf.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function kN(e,t,r){let i=Nf(t);if(e!==i)throw new Error(`${r} ref/hash mismatch`);return i}function ol(e,t){let r=Wt(e,"Native snapshot projection");if(zt(r,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),r.schema!==CN)throw new Error("Native snapshot projection schema is invalid");let i=yi({schema:"comet.native.content-snapshot.v1",origin:r.origin,...r.capture===void 0?{}:{capture:r.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:r.complete,limits:r.limits,...r.policy===void 0?{}:{policy:r.policy},entries:r.entries,omitted:r.omitted,omittedCount:r.omittedCount,...r.omissionOverflow===void 0?{}:{omissionOverflow:r.omissionOverflow}}),n=bf(i);if(T(yo,r)!==T(yo,n))throw new Error("Native snapshot projection is not canonical");let a=T(yo,n);if(t!==void 0&&_i(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function Rf(e,t){let r=Wt(e,`Declared artifact ${t}`);if(zt(r,["path","kind"],[],`Declared artifact ${t}`),r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:Xr(r.path,`Declared artifact ${t} path`),kind:r.kind}}function SN(e,t){if(e===null)return null;let r=Wt(e,t);return zt(r,["hash","size"],[],t),{hash:_i(r.hash,`${t} hash`),size:An(r.size,`${t} size`)}}function EN(e,t){let r=Wt(e,`Implementation change ${t}`);if(zt(r,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),r.kind!=="added"&&r.kind!=="modified"&&r.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(r.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let i=r.attributedTo.map(Rf),n=ko(i);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=SN(r.before,`Implementation change ${t} before`),o=SN(r.after,`Implementation change ${t} after`);if(r.kind==="added"&&(a!==null||o===null)||r.kind==="removed"&&(a===null||o!==null)||r.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(r.path,`Implementation change ${t} path`),kind:r.kind,before:a,after:o,attributedTo:i}}function k$(e,t){let r=Wt(e,`Unresolved scope ${t}`);zt(r,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let i=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof r.kind!="string"||!i.has(r.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(r.source!=="baseline"&&r.source!=="current"&&r.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof r.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(r.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(r.path!==null&&typeof r.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof r.reason!="string"||r.reason.length===0||r.reason.trim()!==r.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:r.id,kind:r.kind,source:r.source,path:r.path===null?null:r.kind==="snapshot-omission"?PN(r.path,`Unresolved scope ${t} path`):Xr(r.path,`Unresolved scope ${t} path`),reason:r.reason}}function No(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of paths`);let r=e.map((n,a)=>Xr(n,`${t} ${a}`)),i=[...new Set(r)].sort(Ce);if(JSON.stringify(r)!==JSON.stringify(i))throw new Error(`${t} must be sorted and unique`);return r}function ON(e){let t=Wt(e,"Native implementation external drift");if(zt(t,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),t.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let r=No(t.paths,"Native external drift paths");return IN({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:r})}function sl(e){let t=Wt(e,"Native implementation scope"),r=[...b$].filter(y=>y!=="gitAdvisory"&&y!=="externalDrift");if(zt(t,r,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==yf)throw new Error("Native implementation scope schema is invalid");let i=_i(t.contractHash,"Implementation scope contractHash"),n=_i(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=kN(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=_i(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=kN(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(Rf);if(JSON.stringify(c)!==JSON.stringify(ko(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(EN),u=[...l].sort((y,C)=>Ce(y.path,C.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(y=>y.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(y=>`${y.kind}:${y.path}`));if(l.some(y=>y.attributedTo.some(C=>!d.has(`${C.kind}:${C.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(y=>JSON.stringify(y.attributedTo)!==JSON.stringify(c.filter(C=>So(C,y.path)))))throw new Error("Implementation scope change attribution is inconsistent");let p=t.unattributed.map(EN),f=t.externalDrift===void 0?void 0:ON(t.externalDrift),m=new Set(f?.paths??[]),h=l.filter(y=>y.attributedTo.length===0&&!m.has(y.path));if(JSON.stringify(p)!==JSON.stringify(h))throw new Error("Implementation scope unattributed changes are inconsistent");let v=t.unresolvedScopes.map(k$),g=v.filter(y=>y.kind==="scope-detail-overflow");if(g.length>1)throw new Error("Implementation scope has multiple detail overflow records");let b=g[0]===void 0?null:y$(g[0]);if(b&&(b.changes+b.unresolved===0||b.unattributed>b.changes||b.unattributed>b.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let k=t.noCodeReason,N=[...h.map(y=>ur({kind:"unattributed-change",source:"implementation-scope",path:y.path,evidence:{after:y.after,before:y.before,changeKind:y.kind}},`Changed path is not covered by a declared artifact: ${y.path}`)),...l.length+(b?.changes??0)===0&&k===null?[ur({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")]:[]],x=v.filter(y=>y.kind==="unattributed-change"||y.kind==="missing-no-code-reason");if(JSON.stringify(v)!==JSON.stringify([...v].sort(kf))||new Set(v.map(y=>y.id)).size!==v.length||JSON.stringify(x)!==JSON.stringify(N.sort(kf))||t.complete!==(v.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 w;if(t.gitAdvisory!==void 0){let y=Wt(t.gitAdvisory,"Implementation scope Git advisory");if(zt(y,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),y.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let C=No(y.changedPaths,"Git changed paths"),O=No(y.pathsPresentInSnapshotChanges,"Git present paths"),j=No(y.pathsAbsentFromSnapshotChanges,"Git absent paths"),Q=[...O,...j].sort(Ce);if(JSON.stringify(Q)!==JSON.stringify(C)||j.some(Pe=>l.some(Z=>Z.path===Pe)))throw new Error("Implementation scope Git advisory partition is invalid");w={advisoryOnly:!0,changedPaths:C,pathsPresentInSnapshotChanges:O,pathsAbsentFromSnapshotChanges:j}}let S={schema:yf,contractHash:i,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:p,unresolvedScopes:v,noCodeReason:k,...w?{gitAdvisory:w}:{},...f?{externalDrift:f}:{}},E=_i(t.scopeHash,"Implementation scope scopeHash");if(T(RN,S)!==E)throw new Error("Implementation scope content hash mismatch");return{...S,scopeHash:E}}function S$(e){let t=Wt(e,"Native implementation scope authority");if(zt(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 r=t.declaredArtifacts.map(Rf);if(JSON.stringify(r)!==JSON.stringify(ko(r)))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 i;t.gitChangedPaths!==void 0&&(i=No(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:ON(t.externalDrift),a=TN({contractHash:t.contractHash,declaredArtifacts:r,noCodeReason:t.noCodeReason,...i===void 0?{}:{gitChangedPaths:i},...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 Eo(e){let t=Wt(e,"Native implementation scope bundle");zt(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let r=S$(t.authority),i=ol(t.baseline),n=ol(t.current),a=sl(t.scope),o=$N(i,n,r);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:r,baseline:i,current:n,scope:o}}function HN(e){let t=sl(e.scope);return Eo({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{},...t.externalDrift?{externalDrift:t.externalDrift}:{}},baseline:e.baseline,current:e.current,scope:t})}var yf,CN,yo,RN,n$,a$,o$,Sf,Ai,s$,c$,b$,Ii=I(()=>{"use strict";ue();yn();yf="comet.native.implementation-scope.v2",CN="comet.native.content-snapshot-projection.v1",yo="comet.native.content-snapshot-projection.v1",RN="comet.native.implementation-scope.v2",n$="comet.native.unresolved-scope-id.v1",a$="comet.native.scope-detail-overflow.v1",o$="comet.native.snapshot-projection-overflow.v2",Sf=/^[a-f0-9]{64}$/u,Ai=1024*1024,s$=128,c$=128;b$=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"])});import DN from"node:path";function dr(e,t){if(!FN.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function LN(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function qN(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 Pf(e,t,r=2e3){let i=ct(e).trim();if(i.length===0||i.length>r)throw new Error(`${t} must be between 1 and ${r} characters`);return i}function xo(e,t){let r=DN.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(i=>{let n=i.codePointAt(0)??0;return n<=31||n===127})||DN.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function R$(e,t,r){let i=xo(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(i))return i;let n=Tt(i),a=i.toLowerCase(),o=r?xo(r,"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"}): ${i}`);return i}function _f(e){let t=xo(e,"Verification typed receipt ref");if(!/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u.test(t))throw new Error("Verification receipt ref must identify a typed v3 receipt");return t}function In(e,t){return e<t?-1:e>t?1:0}function cl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ll(e,t,r){let i=new Set(t),n=Object.keys(e).filter(o=>!i.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${r} is missing field(s): ${a.join(", ")}`)}function MN(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function BN(e,t,r){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let i=`runtime/evidence/${t}/${r}.json`;if(e!==i)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function P$(e){let t=cl(e,"Native acceptance trace");if(ll(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"||!FN.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 r=xo(t.nativeRootRef,"Native root ref"),i=t.entries.map((o,s)=>{let c=cl(o,`Native acceptance trace entry ${s}`);if(ll(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=>_f(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(In))||u==="passed"&&(l.length===0||c.skippedReason!==null)||u==="failed"&&l.length===0&&c.skippedReason===null||u==="missing"&&(l.length>0||c.skippedReason!==null))throw new Error(`Native acceptance trace entry ${s} evidence state is invalid`);return{acceptanceId:c.acceptanceId,status:u,kind:c.kind,source:xo(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Pf(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(i)!==JSON.stringify([...i].sort((o,s)=>In(o.acceptanceId,s.acceptanceId)))||new Set(i.map(o=>o.acceptanceId)).size!==i.length||t.total!==i.length||t.evidenced!==i.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==i.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let n={schema:"comet.native.acceptance-trace.v2",nativeRootRef:r,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:i},a=dr(t.traceHash,"Native acceptance trace hash");if(T(E$,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function VN(e){let t=cl(e,"Native partial allowance");if(ll(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(In))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let r={schema:"comet.native.partial-allowance.v1",change:qN(t.change),scopeHash:dr(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Pf(t.reason,"Partial allowance reason"),confirmedSummary:Pf(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:LN(t.sourceRevision),confirmedAt:MN(t.confirmedAt,"Native partial allowance timestamp")};if(r.reason!==t.reason||r.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let i=dr(t.allowanceHash,"Native partial allowance hash");if(T(x$,r)!==i)throw new Error("Native partial allowance content hash mismatch");return{...r,allowanceHash:i}}function Af(e){let t=cl(e,"Native verification evidence");if(ll(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 r=dr(t.implementationScopeHash,"Native verification implementation scope hash"),i=P$(t.acceptanceTrace),n=dr(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(i.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:dr(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(p=>_f(p));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(In)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(i.entries.flatMap(p=>p.evidenceRefs))].sort(In);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(p=>_f(p));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(In)))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:qN(t.change),sourceRevision:LN(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:dr(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:BN(t.implementationScopeRef,"scopes",r),implementationScopeHash:r,reportRef:R$(t.reportRef,"Native verification report ref"),reportHash:dr(t.reportHash,"Native verification report hash"),acceptanceTrace:i,partialAllowanceRef:o===null?null:BN(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:MN(t.createdAt,"Native verification timestamp")},d=dr(t.envelopeHash,"Native verification envelope hash");if(T(C$,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}var FN,E$,x$,C$,ul=I(()=>{"use strict";ue();Ri();Ra();Ii();FN=/^[a-f0-9]{64}$/u,E$="comet.native.acceptance-trace.v2",x$="comet.native.partial-allowance.v1",C$="comet.native.verification-evidence.v2"});import WN from"node:path";function Qr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Zr(e,t,r,i=[]){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 pr(e,t){if(typeof e!="string"||!A$.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ke(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function YN(e,t){let r=Ke(e,t);if(r<1)throw new Error(`${t} must be a positive integer`);return r}function UN(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(!Number.isFinite(r.getTime())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function D$(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>$$||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 r=WN.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||WN.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function B$(e){let t=Qr(e,"Native check receipt checker");Zr(t,["policy","version","hash","limits"],"Native check receipt checker");let r=Qr(t.limits,"Native check receipt limits");if(Zr(r,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==Tn||t.version!==If||t.hash!==GN||r.maxFiles!==We.maxFiles||r.maxFileBytes!==We.maxFileBytes||r.maxTotalBytes!==We.maxTotalBytes||r.maxIssues!==We.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:Tn,version:If,hash:GN,limits:{...We}}}function F$(e){let t=Qr(e,"Native check receipt contract");return Zr(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:pr(t.expectedHash,"Native check expected contract hash"),beforeHash:pr(t.beforeHash,"Native check before contract hash"),afterHash:pr(t.afterHash,"Native check after contract hash")}}function L$(e){let t=Qr(e,"Native check receipt implementation");return Zr(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:pr(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:pr(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:pr(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:pr(t.afterSnapshotHash,"Native check after snapshot hash")}}function q$(e,t){let r=Qr(e,`Native check batch ${t}`);Zr(r,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let i={filesSelected:Ke(r.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:Ke(r.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:Ke(r.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:Ke(r.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:Ke(r.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:Ke(r.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(i.filesSelected>We.maxFiles||i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.bytesScanned>We.maxTotalBytes||i.recordedIssueCount>i.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return i}function M$(e){let t=Qr(e,"Native check receipt counts");Zr(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let r={filesSelected:Ke(t.filesSelected,"Native check filesSelected"),filesScanned:Ke(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:Ke(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:Ke(t.bytesScanned,"Native check bytesScanned"),issueCount:Ke(t.issueCount,"Native check issueCount"),recordedIssueCount:Ke(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(q$):(()=>{throw new Error("Native check receipt batches must be an array")})()}},i=r.batches;if(i!==void 0){if(i.length===0)throw new Error("Native check receipt batches must not be empty");let n=i.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({...r,batches:void 0}))throw new Error("Native check receipt batch totals are inconsistent")}if(r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.recordedIssueCount>r.issueCount||r.recordedIssueCount>We.maxIssues||i===void 0&&(r.filesScanned+r.binaryFilesSkipped>We.maxFiles||r.bytesScanned>We.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return r}function V$(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||JN.indexOf(e.kind)-JN.indexOf(t.kind)}function W$(e){if(!Array.isArray(e)||e.length>We.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((i,n)=>{let a=Qr(i,`Native check issue ${n}`);if(Zr(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!O$.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:D$(a.path,`Native check issue ${n} path`),line:YN(a.line,`Native check issue ${n} line`),kind:a.kind}}),r=[...t].sort(V$);if(JSON.stringify(r)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function z$(e){if(!Array.isArray(e)||e.some(i=>typeof i!="string"||!H$.has(i)))throw new Error("Native check receipt stale reasons are invalid");let t=e,r=KN.filter(i=>t.includes(i));if(new Set(t).size!==t.length||JSON.stringify(r)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function G$(e){return T(j$,e)}function XN(e){let t=Qr(e,"Native check receipt");if(Zr(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==zN)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!I$.test(t.change))throw new Error("Native check receipt change name is invalid");let r=YN(t.sourceRevision,"Native check source revision"),i=B$(t.checker),n=F$(t.contract),a=L$(t.implementation),o=G$({change:t.change,sourceRevision:r,checkerHash:i.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(pr(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=UN(t.startedAt,"Native check receipt startedAt"),c=UN(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=M$(t.counts),u=W$(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=z$(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let p=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==p)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.batches===void 0&&l.filesSelected>We.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>We.maxFiles&&!u.some(h=>h.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let f={schema:zN,change:t.change,sourceRevision:r,checker:i,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},m=pr(t.receiptHash,"Native check receipt content hash");if(T(_$,f)!==m)throw new Error("Native check receipt content hash mismatch");return{...f,receiptHash:m}}var zN,_$,Tn,If,We,A$,I$,T$,j$,$$,GN,O$,JN,KN,H$,Tf=I(()=>{"use strict";ue();zN="comet.native.check-receipt.v1",_$="comet.native.check-receipt.v1",Tn="scoped-text-safety",If=1,We=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),A$=/^[a-f0-9]{64}$/u,I$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,T$="comet.native.checker-policy.v1",j$="comet.native.check-input.v1",$$=2048,GN=T(T$,{policy:Tn,version:If,limits:We,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),O$=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),JN=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],KN=["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"],H$=new Set(KN)});function jn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Error(`${t} must be a plain object`);return e}function ei(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function fr(e,t){if(typeof e!="string"||!K$.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ct(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let r=ct(e).trim();if(!r||r.length>Z$||r!==e.trim())throw new Error(`${t} is invalid`);return r}function jf(e,t){let r=Ct(e,t),i=new Date(r);if(Number.isNaN(i.getTime())||i.toISOString()!==r)throw new Error(`${t} must be a canonical timestamp`);return r}function Co(e,t,r=Ct,i=!1,n=e0){if(!Array.isArray(e)||e.length>n||!i&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>r(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function r0(e,t){if(typeof e!="string"||!Y$.test(e))throw new Error(`${t} is invalid`);return e}function i0(e){let t=jn(e,"Native verification receipt bindings");if(ei(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!X$.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:fr(t.contractHash,"Native verification receipt contract hash"),scopeHash:fr(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:fr(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:fr(t.artifactHash,"Native verification receipt artifact hash")}}function n0(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=Q$.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function a0(e,t,r,i){let n=jn(t,`Native ${e} evidence`);if(e==="automated-check"){if(ei(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=jf(n.startedAt,"Native automated-check start time"),o=jf(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(r==="passed"&&n.exitCode!==0||r==="failed"&&n.exitCode===0||r==="passed"&&(n.timedOut||n.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=jn(n.worktree,"Native automated-check worktree");if(ei(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=jn(n.afterFence,"Native automated-check after fence");if(ei(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(r==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:Ct(n.executable,"Native automated-check executable"),args:Co(n.args,"Native automated-check arguments",Ct,!0),cwd:Ct(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:Ct(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:fr(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:fr(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:fr(n.outputHash,"Native automated-check output hash"),outputSummary:Ct(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){ei(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=n0(n.checkReceiptRef);if(fr(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:Co(n.subjects,"Native static inspection subjects",Ct,i==="required-check"),rule:Ct(n.rule,"Native static inspection rule"),resultSummary:Ct(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return ei(n,["steps","observations"],"Native manual-evidence evidence"),{steps:Co(n.steps,"Native manual evidence steps"),observations:Co(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function o0(e){let t=jn(e,"Native verification receipt");if(ei(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 r=t.kind,i=t.role,n=t.status,a=Ct(t.actor,"Native verification receipt actor"),o=Co(t.acceptanceIds,"Native receipt acceptance IDs",r0,i==="required-check",t0).sort();if(i==="required-check"&&o.length!==0||i==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(i==="required-check"&&r!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:$f,kind:r,role:i,status:n,bindings:i0(t.bindings),acceptanceIds:o,actor:a,issuedAt:jf(t.issuedAt,"Native verification receipt issue time"),evidence:a0(r,t.evidence,n,i)};if(i==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==Tn||s.actor!==`native-runtime:${Tn}`))throw new Error("Native required check policy identity is invalid");return s}function QN(e){let t=jn(e,"Native verification receipt");if(ei(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==$f)throw new Error("Native verification receipt schema is invalid");let{receiptHash:r,...i}=t,n=o0(i),a=fr(t.receiptHash,"Native verification receipt hash");if(T(J$,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function Of(e){return T(U$,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,r)=>t.path.localeCompare(r.path)||t.kind.localeCompare(r.kind)))}var $f,J$,U$,K$,Y$,X$,Q$,Z$,e0,t0,Ro=I(()=>{"use strict";ue();Tf();Ri();$f="comet.native.verification-receipt.v3",J$=$f,U$="comet.native.declared-artifacts.v1",K$=/^[a-f0-9]{64}$/u,Y$=/^acceptance-[a-f0-9]{64}$/u,X$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Q$=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,Z$=4096,e0=256,t0=1024});import{createHash as s0}from"node:crypto";import{promises as Rt}from"node:fs";import Gt from"node:path";function Hf(e,t){let r=Gt.relative(e,t);return r===""||!Gt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Gt.sep}`)}function c0(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function dl(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Qe(r,i)?G(r,i):G(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function ZN(e){let t=await Rt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await Rt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function l0(e,t){let r=Gt.resolve(e),i=Gt.resolve(t);if(!Hf(r,i))throw new Error("Native evidence path is outside its change");let n=[await ZN(r)],a=r;for(let o of Gt.relative(r,i).split(Gt.sep).filter(Boolean)){a=Gt.join(a,o);let s=await ZN(a);if(!Hf(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function eb(e){for(let t of e){let r=await Rt.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!c0(t,r)||await Rt.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function u0(e,t,r={}){let i=await l0(t,Gt.dirname(e));await r.afterParentChainCaptured?.();let n=await Rt.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await Rt.realpath(e);if(!Hf(i[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await Rt.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),Rt.lstat(e),Rt.realpath(e)]);if(await eb(i),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!dl(s,n)||!dl(s,c))throw new Error("Native evidence document changed while opening");if(s.size>$n)throw new Error(`Native evidence document exceeds ${$n} bytes`);await r.afterOpen?.();let u=[],d=0,p=Buffer.allocUnsafe(64*1024);for(;;){let v=$n+1-d,g=await o.read(p,0,Math.min(p.length,v),null);if(g.bytesRead===0)break;if(d+=g.bytesRead,d>$n)throw new Error(`Native evidence document exceeds ${$n} bytes`);u.push(Buffer.from(p.subarray(0,g.bytesRead)))}await r.beforeFinalCheck?.();let[f,m,h]=await Promise.all([o.stat(),Rt.lstat(e),Rt.realpath(e)]);if(await eb(i),!m.isFile()||m.isSymbolicLink()||h!==a||!dl(s,f)||!dl(s,m))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function ib(e,t){if(!rb.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}async function d0(e,t,r,i,n){if(!rb.test(r))throw new Error("Native report evidence hash is invalid");let a=await Ti({paths:e,name:t,kind:"reports",hash:r,hooks:i,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!==r||typeof o.content!="string"||s0("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==r)throw new Error("Native report evidence does not match its hash");return o.content}function On(e,t){let r=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!r||r[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return r[2]}function p0(e,t,r,i,n){let a=ib(r,i);return n?Gt.join(n,...a.split("/")):Or(Y(e,t),a)}async function Ti(e){let t=p0(e.paths,e.name,e.kind,e.hash,e.changeDir),r=e.changeDir??we(e.paths,t);return await K(r,t),u0(t,r,e.hooks)}function tb(e,t){return ol(e,t)}function f0(e,t){let r=sl(e);if(r.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return r}function h0(e,t,r){let i=VN(e);if(i.change!==t||i.allowanceHash!==r)throw new Error("Native partial allowance ref/hash/change mismatch");return i}function m0(e,t,r){let i=Af(e);if(i.change!==t||i.envelopeHash!==r)throw new Error("Native verification evidence ref/hash/change mismatch");return i}async function v0(e,t,r,i=!1,n){let a=await pl(e,t,r.implementationScopeRef,void 0,n);if(i&&await d0(e,t,r.reportHash,void 0,n),a.scopeHash!==r.implementationScopeHash||a.contractHash!==r.contractHash||(a.complete?"complete":"partial")!==r.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(r.partialAllowanceRef===null)return;let o=await nb(e,t,r.partialAllowanceRef,void 0,n);if(o.allowanceHash!==r.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=r.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function Po(e,t,r,i,n){let a=On(r,"scopes"),o=f0(await Ti({paths:e,name:t,kind:"scopes",hash:a,hooks:i,changeDir:n}),a),s=On(o.baselineProjectionRef,"snapshots"),c=On(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([Ti({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>tb(d,s)),Ti({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>tb(d,c))]);return HN({baseline:l,current:u,scope:o})}async function pl(e,t,r,i,n){return(await Po(e,t,r,i,n)).scope}async function nb(e,t,r,i,n){let a=On(r,"allowances");return h0(await Ti({paths:e,name:t,kind:"allowances",hash:a,hooks:i,changeDir:n}),t,a)}async function _o(e,t,r,i,n){let a=On(r,"receipts"),o=QN(await Ti({paths:e,name:t,kind:"receipts",hash:a,hooks:i,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function Hn(e,t,r,i,n){let a=On(r,"verifications"),o=m0(await Ti({paths:e,name:t,kind:"verifications",hash:a,hooks:i,changeDir:n}),t,a);return await v0(e,t,o,!1,n),o}var rb,$n,TG,ti=I(()=>{"use strict";ae();U();jt();Ii();ul();Ro();rb=/^[a-f0-9]{64}$/u,$n=Ai,TG=3*$n});import vr from"node:path";import{realpathSync as eD}from"node:fs";Hi();Di();import{execFileSync as SS}from"child_process";import ES from"fs";import ni from"path";import{AsyncLocalStorage as Ih}from"node:async_hooks";Gn();var ai=new Ih,Th=new Ih;function jh(e){return ai.getStore()?e():ai.run(new Map,e)}function xS(e){let t=ai.getStore();for(let r of e)t?.set(wr(r.root),e);return e}function Jn(e,t){return zn(()=>SS("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim())}function Un(e,t){return wr(e)===wr(t)}function wr(e){let t=ni.resolve(e);try{let r=ES.realpathSync.native(t);return process.platform==="win32"?r.toLowerCase():r}catch{return process.platform==="win32"?t.toLowerCase():t}}function ve(e){try{let t=Th.getStore()?.get(wr(e)),r=ai.getStore()?.get(t??wr(e));if(r){let c=Kn(t??e,r);if(c)return c;if(r.length===0)return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}let i=ni.resolve(Jn(e,["rev-parse","--show-toplevel"])),n=ai.getStore()?.get(wr(i))??$h(e),a=Kn(i,n);if(ai.getStore()&&a)return a;let o=n[0]?.root??i,s=null;try{s=Jn(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!Un(i,o),currentWorktreeRoot:i,primaryWorktreeRoot:o,currentBranch:s}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function Go(e){try{let t=ai.getStore()?.get(Th.getStore()?.get(wr(e))??wr(e));return t?t.map(r=>({...r})):(Jn(e,["rev-parse","--is-inside-work-tree"]),$h(e))}catch{return[]}}function $h(e){let t=CS(Jn(e,["worktree","list","--porcelain","-z"]));return xS(t),t.map(r=>({...r}))}function CS(e){let t=e.split("\0"),r=[],i=null;for(let n of t)n.startsWith("worktree ")?(i&&r.push(i),i={root:ni.resolve(n.slice(9)),branch:null,detached:!1}):i&&n.startsWith("branch refs/heads/")?i.branch=n.slice(18):i&&n==="detached"&&(i.detached=!0);return i&&r.push(i),r}function yr(e){return Go(e).map(t=>t.root)}function Kn(e,t){let r=t.find(a=>Un(ni.resolve(a.root),ni.resolve(e)));if(!r)return null;let i=ni.resolve(t[0].root),n=ni.resolve(r.root);return{isGitWorktree:!0,isSecondaryWorktree:!Un(i,n),currentWorktreeRoot:n,primaryWorktreeRoot:i,currentBranch:r.branch}}function Yt(e,t){try{let r=Jn(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}ue();var Bp=Kt(It(),1);import{promises as vy}from"fs";import Vr from"path";et();ae();pi();Je();Se();U();wt();yn();import{createHash as CI}from"crypto";import RI from"path";var at=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"});Se();U();import{constants as Pc,promises as bt}from"node:fs";import kt from"node:path";import{TextDecoder as bI}from"node:util";import gI from"path";en();Tr();var aI=Kt(It(),1);en();Tr();er();er();Zi();Md();en();er();var A1=4*1024*1024;import{AsyncLocalStorage as oI}from"node:async_hooks";var sI=new oI;function cI(){let e=sI.getStore();return e?.active?e:null}function lI(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function Yw(e,t){return(...r)=>{let i=cI();if(i===null)return t(...r);let n=lI(`async:${e}`,r),a=i.entries.get(n);if(a)return a.value;let o=t(...r).catch(s=>{throw i.entries.get(n)?.value===o&&i.entries.delete(n),s});return i.entries.set(n,{value:o}),o}}Zi();var H1=Yw("hookWritePolicy",async e=>(await Bd(e))?.hook??{allow_paths:[]});ja();import uI from"node:path";var Rc="comet.selection.v2",Qw=16*1024;function Ap(e){return uI.join(e,".comet","current-change.json")}function dI(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Xw(e){return e===null||typeof e=="string"}function pI(e){let t;try{t=JSON.parse(e)}catch(r){throw new Error(`current change selection contains invalid JSON: ${r instanceof Error?r.message:String(r)}`,{cause:r})}if(!dI(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&&!Xw(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Rc,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Rc)throw new Error(`current change selection schema must be ${Rc}`);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(!Xw(t.branch))throw new Error("current change selection branch must be a string or null");if(t.workflow==="native"&&t.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:t,legacy:!1}}async function Ip(e){let t;try{let i=Ap(e),{bytes:n}=await Xi(i,Qw,{label:"current change selection"});t=n.toString("utf8")}catch(i){if(i.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${i instanceof Error?i.message:String(i)}`,{cause:i})}return{status:"selected",...pI(t)}}Fd();Pa();var Zw=(e,t)=>{let r=e[t];return r==null?null:String(r)};function Za(e,t){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return r}function Qa(e,t){let r=Za(e,t);if(gI.isAbsolute(r)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(r)||r.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return r}function wI(e){let t=e.run_retries??"{}",r;try{r=typeof t=="string"?JSON.parse(t):t}catch(i){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:i})}if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let i of Object.values(r))if(!Number.isInteger(i)||Number(i)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return r}function ey(e){if(!e.run_id)return null;let t=Za(e,"run_id"),r=Za(e,"skill"),i=Za(e,"skill_version"),n=Za(e,"skill_hash"),a=Qa(e,"pending_ref"),o=Qa(e,"trajectory_ref"),s=Qa(e,"context_ref"),c=Qa(e,"artifacts_ref"),l=Qa(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:r,skillVersion:i,skillHash:n,orchestration:e.orchestration,currentStep:Zw(e,"current_step"),iteration:u,pending:Zw(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:wI(e)}}var FM=Number.MAX_SAFE_INTEGER;var yI=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function NI(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)},r=ey(t);if(!r)throw new Error("Invalid Run state: runId must be a non-empty string");return r}function Tp(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Run state: stored value must be an object");let t=e,r=Object.keys(t).find(i=>!yI.has(i));if(r)throw new Error(`Invalid Run state: unknown field ${r}`);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 NI(t)}ae();jt();var Nn={runStateBytes:Number.MAX_SAFE_INTEGER,trajectoryBytes:Number.MAX_SAFE_INTEGER,trajectoryEvents:4096,trajectoryEventBytes:Number.MAX_SAFE_INTEGER,checkpointBytes:Number.MAX_SAFE_INTEGER,pendingActionBytes:Number.MAX_SAFE_INTEGER,contextBytes:Number.MAX_SAFE_INTEGER,artifactsBytes:Number.MAX_SAFE_INTEGER};function Ac(e,t){let r=kt.relative(e,t);return r===""||!kt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${kt.sep}`)}function kI(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function _c(e,t){return G({...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 SI(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Ic(e,t,r){let i=at[t];if(r!==void 0&&r!==i)throw new Error(`Native Run ${t} ref must be ${i}`);let n=kt.resolve(e),a=kt.resolve(n,...i.slice(8).split("/"));if(!Ac(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function ty(e){let t=await bt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await bt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function EI(e,t){let r=kt.resolve(e),i=kt.resolve(t);if(!Ac(r,i))throw new Error("Native Run path is outside its change");let n=[await ty(r)],a=r;for(let o of kt.relative(r,i).split(kt.sep).filter(Boolean)){a=kt.join(a,o);let s;try{s=await ty(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!Ac(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function ry(e){for(let t of e){let r=await bt.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!SI(t,r)||await bt.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function xI(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function Tc(e,t,r,i,n){let a=await EI(e,kt.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await bt.lstat(t)}catch(d){if(d.code==="ENOENT")return null;throw d}if(!o.isFile()||o.isSymbolicLink())throw new Error(`${i} must be a regular file`);if(o.size>r)throw new Error(`${i} exceeds ${r} bytes`);let s=kI(o),c=await bt.realpath(t);if(!Ac(a[0].realPath,c))throw new Error(`${i} resolves outside its change`);let l=process.platform==="win32"?Pc.O_RDONLY:Pc.O_RDONLY|Pc.O_NOFOLLOW|Pc.O_NONBLOCK,u;try{u=await bt.open(t,l)}catch(d){throw new Error(`${i} changed while opening`,{cause:d})}try{let[d,p,f]=await Promise.all([u.stat(),bt.lstat(t),bt.realpath(t)]);if(await ry(a),!d.isFile()||!p.isFile()||p.isSymbolicLink()||f!==c||!_c(s,d)||!_c(s,p))throw new Error(`${i} changed while opening`);await n?.afterOpen?.();let m=await xI(u,r,i);await n?.beforeFinalCheck?.();let[h,v,g]=await Promise.all([u.stat(),bt.lstat(t),bt.realpath(t)]);if(await ry(a),!v.isFile()||v.isSymbolicLink()||g!==c||!_c(s,h)||!_c(s,v))throw new Error(`${i} changed while reading`);let b;try{b=new bI("utf-8",{fatal:!0}).decode(m)}catch(k){throw new Error(`${i} is not valid UTF-8`,{cause:k})}return{text:b,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}function iy(e,t){try{return JSON.parse(e)}catch(r){throw new Error(`${t} contains invalid JSON`,{cause:r})}}function jp(e){return Tp(e)}async function bn(e,t){let r=Ic(e,"stateRef"),i=await Tc(e,r,Nn.runStateBytes,"Native Run state",t);return i?Tp(iy(i.text,"Native Run state")):null}async function Ni(e,t,r){let i=Ic(e,"trajectoryRef",t),n=await Tc(e,i,Nn.trajectoryBytes,"Native Run trajectory",r);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>Nn.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Nn.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 ny(e,t,r){return(await Tc(e,Ic(e,"trajectoryRef",t),Nn.trajectoryBytes,"Native Run trajectory",r))?.text??null}async function jc(e,t,r){let i=await Tc(e,Ic(e,"checkpointRef",t),Nn.checkpointBytes,"Native Run checkpoint",r);return i?iy(i.text,"Native Run checkpoint"):null}var PI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function $p(e){return CI("sha256").update(e).digest("hex")}function _I(e,t){if(!PI.test(t))throw new Error(`Invalid Native change name: ${t}`);return RI.join(Y(e,t),"trajectory.jsonl")}function AI(e){let t=e.split(/\n/u),r=0;for(let i=0;i<t.length;i+=1){let n=t[i].endsWith("\r")?t[i].slice(0,-1):t[i];if(n.length!==0){r=i+1;try{JSON.parse(n)}catch(a){return{status:"invalid",line:i+1,message:a.message}}}}return{status:"valid",count:r}}function II(e,t){if(/Unexpected end|Unterminated string/iu.test(e.message))return!0;let r=/position (\d+)/iu.exec(e.message)?.[1];return r!==void 0&&Number(r)>=Math.max(0,t.length-1)}function TI(e,t){let r=t.lastIndexOf(10),i=t.subarray(0,r+1),n=AI(i.toString("utf8"));if(n.status==="invalid")return{status:"invalid",file:e,line:n.line,message:n.message};if(r===t.length-1)return{status:"clean",file:e};let a=t.subarray(r+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(`
175
- `)])}catch(d){if(!II(d,o))return{status:"invalid",file:e,line:s,message:d.message};c="incomplete-json",l=i}return{inspection:{status:"repairable",file:e,reason:c,line:s,originalHash:$p(t),targetHash:$p(l),tailHash:$p(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function jI(e,t){let r=_I(e,t);await K(we(e,r),r);let i=Y(e,t),n=await ny(i,at.trajectoryRef);return n===null?{status:"clean",file:r}:TI(r,Buffer.from(n))}async function ay(e,t){let r=await jI(e,t);return"inspection"in r?r.inspection:r}import{createHash as $I}from"node:crypto";import{promises as $c}from"node:fs";import ar from"node:path";ae();et();Se();U();var eo=/^[a-f0-9]{64}$/u,oy=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,OI=16*1024,Hp=process.platform,HI=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function kn(e){return HI.has(e)}function uy(e,t){let r=ar.relative(e,t);return ar.isAbsolute(r)||r===".."||r.startsWith(`..${ar.sep}`)?null:r.replaceAll("\\","/")||"."}function dy(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function py(e,t){if(e.length===0||dy(e)||e.includes("\\")||ar.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let r=ar.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function Dp(e,t){return $I("sha256").update(`${e}
176
- ${t}`).digest("hex")}async function sy(e,t){let r=await $c.realpath(t),i=await $c.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Hp==="win32"?ar.normalize(r).toLowerCase():r;return Dp(e,`${n}
176
+ ${Xn(r)}`;e.update(`${Buffer.byteLength(i,"utf8")}:`),e.update(i)}function R$(e){if(So(e)<=Ii)return e;let t=[...e.entries],r=[...e.omitted],i=e.omittedCount,n=e.omissionOverflow?.count??0,a=HN("sha256");a.update(`${y$}
177
+ `),e.omissionOverflow&&Yr(a,"existing-overflow",e.omissionOverflow);let o=(p,f)=>{f||(i+=1),n+=1,Yr(a,"omission",p)},s=p=>{i+=1,n+=1,Yr(a,"entry",p)},c=()=>{for(let p=r.length-1;p>=0;p-=1){let f=r[p];if(!(f.reason==="git-enumeration-limit"||f.reason==="git-selection-changed"||f.reason==="physical-enumeration-limit"||f.reason==="physical-selection-changed"))return r.splice(p,1),f}return null},l=()=>({...e,complete:i===0,entries:t,omitted:r,omittedCount:i,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:n}}),u=l();for(;So(u)>Ii;){if(r.filter(f=>f.reason!=="git-enumeration-limit"&&f.reason!=="git-selection-changed"&&f.reason!=="physical-enumeration-limit"&&f.reason!=="physical-selection-changed").length>0){let f=Math.max(1,Math.ceil(r.length/4));for(let m=0;m<f;m+=1){let h=c();if(h===null)break;o(h,!0)}}else if(t.length>0){let f=Math.max(1,Math.ceil(t.length/4));for(let m of t.splice(-f))s(m)}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 xf(e){let t=Ni(e),r=t.entries.map((n,a)=>S$(n,`Snapshot entry ${a}`));if(r.sort(x$),new Set(r.map(n=>n.path)).size!==r.length)throw new Error("Snapshot entries must not contain duplicate paths");let i=t.omitted.map((n,a)=>E$(n,`Snapshot omission ${a}`));return i.sort(C$),R$({schema:DN,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:r,omitted:i,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:{ref:t.omissionOverflow.ref,hash:t.omissionOverflow.hash,count:t.omissionOverflow.count}}:{}})}function Eo(e){let t=new Map;for(let[r,i]of e.entries()){if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${r} kind is invalid`);let n={path:Xr(i.path,`Declared artifact ${r} path`),kind:i.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((r,i)=>Ce(r.path,i.path)||Ce(r.kind,i.kind))}function xo(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function AN(e){return e?{hash:e.hash,size:e.size}:null}function Pf(e,t,r){let i=0,n=0;for(;i<e.entries.length||n<t.entries.length;){let a=e.entries[i],o=t.entries[n],s=a===void 0?1:o===void 0?-1:Ce(a.path,o.path),c=s<=0?a:void 0,l=s>=0?o:void 0;if(s<=0&&(i+=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&&r({path:u,kind:c?l?"modified":"removed":"added",before:AN(c),after:AN(l)})}}function LN(e,t){return{...e,attributedTo:t.filter(r=>xo(r,e.path))}}function _f(e){let t=Eo(e.declaredArtifacts),r=[];return Pf(e.baseline,e.current,i=>{r.push(LN(i,t))}),r}function ur(e,t){return{id:`scope:${T(g$,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function P$(e,t){let r=t.omitted.map(i=>ur({kind:"snapshot-omission",source:e,path:i.path,evidence:{reason:i.reason,size:i.size,type:i.type}},`${e} snapshot omitted ${i.path}: ${i.reason}`));return t.complete||r.push(ur({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&r.push(ur({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`)),r}function IN(e,t){return P$(e,{...t,omitted:[]}).filter(r=>r.kind!=="snapshot-omission")}function Cf(e,t){return Ce(e.kind,t.kind)||Ce(e.source,t.source)||k$(e.path,t.path)||Ce(e.id,t.id)}function _$(e){return[...new Map(e.map(r=>[r.id,r])).values()].sort(Cf)}function qN(e){return[...new Set(e.map((t,r)=>Xr(t,`Git path ${r}`)))].sort(Ce)}function TN(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 A$(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 MN(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=qN(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:TN(e.baseCommit,"Native external drift base commit"),targetBranch:A$(e.targetBranch,"Native external drift target branch"),targetCommit:TN(e.targetCommit,"Native external drift target commit"),paths:t}}function VN(e){if(typeof e.contractHash!="string"||!Rf.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:Eo(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:qN(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:MN(e.externalDrift)}}}function I$(e,t,r,i,n){let a=[],o=i===void 0?null:new Set(i),s=[],c=[],l=0,u=!1,d=0,p=0;return Pf(e,t,f=>{let m=r.some(h=>xo(h,f.path));if(d+=1,c.push(f.path),!m&&!n?.has(f.path)&&(p+=1),o?.has(f.path)&&s.push(f.path),!u&&a.length<N$){let h=LN(f,r),v=So(h);l+v<=Ii?(a.push(h),l+=v):u=!0}}),{candidates:a,gitPathsPresentInChanges:s,changePaths:c,totalChanges:d,totalUnattributed:p}}function WN(e,t){return ur({kind:"scope-detail-overflow",source:"implementation-scope",path:null,evidence:{changeCount:t.changes,hash:e,unattributedCount:t.unattributed,unresolvedCount:t.unresolved}},`Implementation scope summarized ${t.changes} additional change details and ${t.unresolved} unresolved details (${t.unattributed} unattributed); overflow hash ${e}`)}function T$(e){let t=/^Implementation scope summarized ([0-9]+) additional change details and ([0-9]+) unresolved details \(([0-9]+) unattributed\); overflow hash ([a-f0-9]{64})$/u.exec(e.reason);if(!t)throw new Error("Implementation scope detail overflow is invalid");let r={changes:In(Number(t[1]),"Scope overflow change count"),unresolved:In(Number(t[2]),"Scope overflow unresolved count"),unattributed:In(Number(t[3]),"Scope overflow unattributed count")},i=Ai(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(WN(i,r)))throw new Error("Implementation scope detail overflow is inconsistent");return{...r,hash:i}}function j$(e){let t=HN("sha256");t.update(`${w$}
178
+ `);let r=0;Pf(e.baseline,e.current,n=>{if(r>=e.detailedChangeCount){Yr(t,"change",n);let a=0;for(let o of e.declaredArtifacts)xo(o,n.path)&&(a+=1,Yr(t,"change-attribution",o));Yr(t,"change-end",{attributionCount:a}),a===0&&Yr(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}r+=1});let i=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)i>=e.detailedOmissionCount&&Yr(t,"snapshot-omission",{source:n,...o}),i+=1;return t.digest("hex")}function zN(e,t,r){let{contractHash:i,declaredArtifacts:n,noCodeReason:a}=r,o=I$(e,t,n,r.gitChangedPaths,r.externalDrift?new Set(r.externalDrift.paths):void 0);if(r.externalDrift){let S=new Set(r.externalDrift.paths),E=new Set(o.changePaths),y=r.externalDrift.paths.filter(C=>!E.has(C)||n.some(O=>xo(O,C)));if(y.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${y.slice(0,8).join(", ")}`);if(S.size!==r.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=T(bo,e),c=T(bo,t),l=[],u=new Set(r.externalDrift?.paths??[]);for(let[S,E]of[["baseline",e],["current",t]])for(let y of E.omitted){if(l.length>=b$)break;l.push(ur({kind:"snapshot-omission",source:S,path:y.path,evidence:{reason:y.reason,size:y.size,type:y.type}},`${S} snapshot omitted ${y.path}: ${y.reason}`))}let d=e.omitted.length+t.omitted.length,p=[...IN("baseline",e),...IN("current",t),...o.totalChanges===0&&a===null?[ur({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")]:[]],f=()=>{if(r.gitChangedPaths===void 0)return;let S=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:r.gitChangedPaths,pathsPresentInSnapshotChanges:r.gitChangedPaths.filter(E=>S.has(E)),pathsAbsentFromSnapshotChanges:r.gitChangedPaths.filter(E=>!S.has(E))}},m=S=>{let E=o.candidates.slice(0,S.detailedChangeCount),y=E.filter(se=>se.attributedTo.length===0&&!u.has(se.path)),C=o.totalChanges-E.length,O=o.totalUnattributed-y.length,j=d-S.detailedOmissionCount,Q=O+j,Pe=[...y.map(se=>ur({kind:"unattributed-change",source:"implementation-scope",path:se.path,evidence:{after:se.after,before:se.before,changeKind:se.kind}},`Changed path is not covered by a declared artifact: ${se.path}`)),...l.slice(0,S.detailedOmissionCount),...p,...Q>0?[WN(S.overflowHash,{changes:C,unattributed:O,unresolved:Q})]:[]],Z=_$(Pe),Pt=S.includeGitAdvisory?f():void 0;return{schema:Sf,contractHash:i,baselineProjectionRef:Ef(s),baselineProjectionHash:s,currentProjectionRef:Ef(c),currentProjectionHash:c,complete:Z.length===0,declaredArtifacts:n,changes:E,unattributed:y,unresolvedScopes:Z,noCodeReason:a,...Pt?{gitAdvisory:Pt}:{},...r.externalDrift?{externalDrift:r.externalDrift}:{}}},h=o.candidates.length,v=l.length,g=r.gitChangedPaths!==void 0,b="0".repeat(64);for(;;){let S=m({detailedChangeCount:h,detailedOmissionCount:v,includeGitAdvisory:g,overflowHash:b});if(So({...S,scopeHash:b})<=Ii)break;if(g){g=!1;continue}if(v>0){v-=Math.max(1,Math.ceil(v/4));continue}if(h>0){h-=Math.max(1,Math.ceil(h/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let N=o.totalChanges>h||d>v?j$({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:h,detailedOmissionCount:v}):b,x=m({detailedChangeCount:h,detailedOmissionCount:v,includeGitAdvisory:g,overflowHash:N}),w={...x,scopeHash:T(BN,x)};if(So(w)>Ii)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return w}function Af(e){let t=xf(e.baseline),r=xf(e.current),i=VN(e);return{authority:i,baseline:t,current:r,scope:zN(t,r,i)}}function Wt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function zt(e,t,r,i){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 Ai(e,t){if(typeof e!="string"||!Rf.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function jN(e,t,r){let i=Ef(t);if(e!==i)throw new Error(`${r} ref/hash mismatch`);return i}function ll(e,t){let r=Wt(e,"Native snapshot projection");if(zt(r,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),r.schema!==DN)throw new Error("Native snapshot projection schema is invalid");let i=Ni({schema:"comet.native.content-snapshot.v1",origin:r.origin,...r.capture===void 0?{}:{capture:r.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:r.complete,limits:r.limits,...r.policy===void 0?{}:{policy:r.policy},entries:r.entries,omitted:r.omitted,omittedCount:r.omittedCount,...r.omissionOverflow===void 0?{}:{omissionOverflow:r.omissionOverflow}}),n=xf(i);if(T(bo,r)!==T(bo,n))throw new Error("Native snapshot projection is not canonical");let a=T(bo,n);if(t!==void 0&&Ai(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function If(e,t){let r=Wt(e,`Declared artifact ${t}`);if(zt(r,["path","kind"],[],`Declared artifact ${t}`),r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:Xr(r.path,`Declared artifact ${t} path`),kind:r.kind}}function $N(e,t){if(e===null)return null;let r=Wt(e,t);return zt(r,["hash","size"],[],t),{hash:Ai(r.hash,`${t} hash`),size:In(r.size,`${t} size`)}}function ON(e,t){let r=Wt(e,`Implementation change ${t}`);if(zt(r,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),r.kind!=="added"&&r.kind!=="modified"&&r.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(r.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let i=r.attributedTo.map(If),n=Eo(i);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=$N(r.before,`Implementation change ${t} before`),o=$N(r.after,`Implementation change ${t} after`);if(r.kind==="added"&&(a!==null||o===null)||r.kind==="removed"&&(a===null||o!==null)||r.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(r.path,`Implementation change ${t} path`),kind:r.kind,before:a,after:o,attributedTo:i}}function O$(e,t){let r=Wt(e,`Unresolved scope ${t}`);zt(r,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let i=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof r.kind!="string"||!i.has(r.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(r.source!=="baseline"&&r.source!=="current"&&r.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof r.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(r.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(r.path!==null&&typeof r.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof r.reason!="string"||r.reason.length===0||r.reason.trim()!==r.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:r.id,kind:r.kind,source:r.source,path:r.path===null?null:r.kind==="snapshot-omission"?FN(r.path,`Unresolved scope ${t} path`):Xr(r.path,`Unresolved scope ${t} path`),reason:r.reason}}function ko(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of paths`);let r=e.map((n,a)=>Xr(n,`${t} ${a}`)),i=[...new Set(r)].sort(Ce);if(JSON.stringify(r)!==JSON.stringify(i))throw new Error(`${t} must be sorted and unique`);return r}function GN(e){let t=Wt(e,"Native implementation external drift");if(zt(t,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),t.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let r=ko(t.paths,"Native external drift paths");return MN({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:r})}function ul(e){let t=Wt(e,"Native implementation scope"),r=[...$$].filter(y=>y!=="gitAdvisory"&&y!=="externalDrift");if(zt(t,r,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==Sf)throw new Error("Native implementation scope schema is invalid");let i=Ai(t.contractHash,"Implementation scope contractHash"),n=Ai(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=jN(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=Ai(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=jN(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(If);if(JSON.stringify(c)!==JSON.stringify(Eo(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(ON),u=[...l].sort((y,C)=>Ce(y.path,C.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(y=>y.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(y=>`${y.kind}:${y.path}`));if(l.some(y=>y.attributedTo.some(C=>!d.has(`${C.kind}:${C.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(y=>JSON.stringify(y.attributedTo)!==JSON.stringify(c.filter(C=>xo(C,y.path)))))throw new Error("Implementation scope change attribution is inconsistent");let p=t.unattributed.map(ON),f=t.externalDrift===void 0?void 0:GN(t.externalDrift),m=new Set(f?.paths??[]),h=l.filter(y=>y.attributedTo.length===0&&!m.has(y.path));if(JSON.stringify(p)!==JSON.stringify(h))throw new Error("Implementation scope unattributed changes are inconsistent");let v=t.unresolvedScopes.map(O$),g=v.filter(y=>y.kind==="scope-detail-overflow");if(g.length>1)throw new Error("Implementation scope has multiple detail overflow records");let b=g[0]===void 0?null:T$(g[0]);if(b&&(b.changes+b.unresolved===0||b.unattributed>b.changes||b.unattributed>b.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let k=t.noCodeReason,N=[...h.map(y=>ur({kind:"unattributed-change",source:"implementation-scope",path:y.path,evidence:{after:y.after,before:y.before,changeKind:y.kind}},`Changed path is not covered by a declared artifact: ${y.path}`)),...l.length+(b?.changes??0)===0&&k===null?[ur({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")]:[]],x=v.filter(y=>y.kind==="unattributed-change"||y.kind==="missing-no-code-reason");if(JSON.stringify(v)!==JSON.stringify([...v].sort(Cf))||new Set(v.map(y=>y.id)).size!==v.length||JSON.stringify(x)!==JSON.stringify(N.sort(Cf))||t.complete!==(v.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 w;if(t.gitAdvisory!==void 0){let y=Wt(t.gitAdvisory,"Implementation scope Git advisory");if(zt(y,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),y.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let C=ko(y.changedPaths,"Git changed paths"),O=ko(y.pathsPresentInSnapshotChanges,"Git present paths"),j=ko(y.pathsAbsentFromSnapshotChanges,"Git absent paths"),Q=[...O,...j].sort(Ce);if(JSON.stringify(Q)!==JSON.stringify(C)||j.some(Pe=>l.some(Z=>Z.path===Pe)))throw new Error("Implementation scope Git advisory partition is invalid");w={advisoryOnly:!0,changedPaths:C,pathsPresentInSnapshotChanges:O,pathsAbsentFromSnapshotChanges:j}}let S={schema:Sf,contractHash:i,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:p,unresolvedScopes:v,noCodeReason:k,...w?{gitAdvisory:w}:{},...f?{externalDrift:f}:{}},E=Ai(t.scopeHash,"Implementation scope scopeHash");if(T(BN,S)!==E)throw new Error("Implementation scope content hash mismatch");return{...S,scopeHash:E}}function H$(e){let t=Wt(e,"Native implementation scope authority");if(zt(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 r=t.declaredArtifacts.map(If);if(JSON.stringify(r)!==JSON.stringify(Eo(r)))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 i;t.gitChangedPaths!==void 0&&(i=ko(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:GN(t.externalDrift),a=VN({contractHash:t.contractHash,declaredArtifacts:r,noCodeReason:t.noCodeReason,...i===void 0?{}:{gitChangedPaths:i},...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 Co(e){let t=Wt(e,"Native implementation scope bundle");zt(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let r=H$(t.authority),i=ll(t.baseline),n=ll(t.current),a=ul(t.scope),o=zN(i,n,r);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:r,baseline:i,current:n,scope:o}}function JN(e){let t=ul(e.scope);return Co({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{},...t.externalDrift?{externalDrift:t.externalDrift}:{}},baseline:e.baseline,current:e.current,scope:t})}var Sf,DN,bo,BN,g$,w$,y$,Rf,Ii,N$,b$,$$,Ti=I(()=>{"use strict";ue();Nn();Sf="comet.native.implementation-scope.v2",DN="comet.native.content-snapshot-projection.v1",bo="comet.native.content-snapshot-projection.v1",BN="comet.native.implementation-scope.v2",g$="comet.native.unresolved-scope-id.v1",w$="comet.native.scope-detail-overflow.v1",y$="comet.native.snapshot-projection-overflow.v2",Rf=/^[a-f0-9]{64}$/u,Ii=1024*1024,N$=128,b$=128;$$=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"])});import UN from"node:path";function dr(e,t){if(!YN.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function XN(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function QN(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 Tf(e,t,r=2e3){let i=ct(e).trim();if(i.length===0||i.length>r)throw new Error(`${t} must be between 1 and ${r} characters`);return i}function Ro(e,t){let r=UN.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(i=>{let n=i.codePointAt(0)??0;return n<=31||n===127})||UN.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function L$(e,t,r){let i=Ro(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(i))return i;let n=Tt(i),a=i.toLowerCase(),o=r?Ro(r,"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"}): ${i}`);return i}function jf(e){let t=Ro(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 Tn(e,t){return e<t?-1:e>t?1:0}function dl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function pl(e,t,r){let i=new Set(t),n=Object.keys(e).filter(o=>!i.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${r} is missing field(s): ${a.join(", ")}`)}function ZN(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function KN(e,t,r){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let i=`runtime/evidence/${t}/${r}.json`;if(e!==i)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function q$(e){let t=dl(e,"Native acceptance trace");if(pl(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"||!YN.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 r=Ro(t.nativeRootRef,"Native root ref"),i=t.entries.map((o,s)=>{let c=dl(o,`Native acceptance trace entry ${s}`);if(pl(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=>jf(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Tn))||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:Ro(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Tf(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(i)!==JSON.stringify([...i].sort((o,s)=>Tn(o.acceptanceId,s.acceptanceId)))||new Set(i.map(o=>o.acceptanceId)).size!==i.length||t.total!==i.length||t.evidenced!==i.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==i.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let n={schema:"comet.native.acceptance-trace.v2",nativeRootRef:r,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:i},a=dr(t.traceHash,"Native acceptance trace hash");if(T(D$,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function eb(e){let t=dl(e,"Native partial allowance");if(pl(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(Tn))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let r={schema:"comet.native.partial-allowance.v1",change:QN(t.change),scopeHash:dr(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Tf(t.reason,"Partial allowance reason"),confirmedSummary:Tf(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:XN(t.sourceRevision),confirmedAt:ZN(t.confirmedAt,"Native partial allowance timestamp")};if(r.reason!==t.reason||r.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let i=dr(t.allowanceHash,"Native partial allowance hash");if(T(B$,r)!==i)throw new Error("Native partial allowance content hash mismatch");return{...r,allowanceHash:i}}function $f(e){let t=dl(e,"Native verification evidence");if(pl(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 r=dr(t.implementationScopeHash,"Native verification implementation scope hash"),i=q$(t.acceptanceTrace),n=dr(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(i.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:dr(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(p=>jf(p));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(Tn)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(i.entries.flatMap(p=>p.evidenceRefs))].sort(Tn);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(p=>jf(p));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Tn)))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:QN(t.change),sourceRevision:XN(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:dr(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:KN(t.implementationScopeRef,"scopes",r),implementationScopeHash:r,reportRef:L$(t.reportRef,"Native verification report ref"),reportHash:dr(t.reportHash,"Native verification report hash"),acceptanceTrace:i,partialAllowanceRef:o===null?null:KN(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:ZN(t.createdAt,"Native verification timestamp")},d=dr(t.envelopeHash,"Native verification envelope hash");if(T(F$,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}var YN,D$,B$,F$,fl=I(()=>{"use strict";ue();Pi();Pa();Ti();YN=/^[a-f0-9]{64}$/u,D$="comet.native.acceptance-trace.v2",B$="comet.native.partial-allowance.v1",F$="comet.native.verification-evidence.v2"});import tb from"node:path";function Qr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Zr(e,t,r,i=[]){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 pr(e,t){if(typeof e!="string"||!V$.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ke(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function sb(e,t){let r=Ke(e,t);if(r<1)throw new Error(`${t} must be a positive integer`);return r}function ab(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(!Number.isFinite(r.getTime())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function Y$(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>J$||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 r=tb.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||tb.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function X$(e){let t=Qr(e,"Native check receipt checker");Zr(t,["policy","version","hash","limits"],"Native check receipt checker");let r=Qr(t.limits,"Native check receipt limits");if(Zr(r,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==jn||t.version!==Of||t.hash!==ib||r.maxFiles!==We.maxFiles||r.maxFileBytes!==We.maxFileBytes||r.maxTotalBytes!==We.maxTotalBytes||r.maxIssues!==We.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:jn,version:Of,hash:ib,limits:{...We}}}function Q$(e){let t=Qr(e,"Native check receipt contract");return Zr(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:pr(t.expectedHash,"Native check expected contract hash"),beforeHash:pr(t.beforeHash,"Native check before contract hash"),afterHash:pr(t.afterHash,"Native check after contract hash")}}function Z$(e){let t=Qr(e,"Native check receipt implementation");return Zr(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:pr(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:pr(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:pr(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:pr(t.afterSnapshotHash,"Native check after snapshot hash")}}function e0(e,t){let r=Qr(e,`Native check batch ${t}`);Zr(r,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let i={filesSelected:Ke(r.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:Ke(r.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:Ke(r.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:Ke(r.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:Ke(r.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:Ke(r.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(i.filesSelected>We.maxFiles||i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.bytesScanned>We.maxTotalBytes||i.recordedIssueCount>i.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return i}function t0(e){let t=Qr(e,"Native check receipt counts");Zr(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let r={filesSelected:Ke(t.filesSelected,"Native check filesSelected"),filesScanned:Ke(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:Ke(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:Ke(t.bytesScanned,"Native check bytesScanned"),issueCount:Ke(t.issueCount,"Native check issueCount"),recordedIssueCount:Ke(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(e0):(()=>{throw new Error("Native check receipt batches must be an array")})()}},i=r.batches;if(i!==void 0){if(i.length===0)throw new Error("Native check receipt batches must not be empty");let n=i.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({...r,batches:void 0}))throw new Error("Native check receipt batch totals are inconsistent")}if(r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.recordedIssueCount>r.issueCount||r.recordedIssueCount>We.maxIssues||i===void 0&&(r.filesScanned+r.binaryFilesSkipped>We.maxFiles||r.bytesScanned>We.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return r}function r0(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||nb.indexOf(e.kind)-nb.indexOf(t.kind)}function i0(e){if(!Array.isArray(e)||e.length>We.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((i,n)=>{let a=Qr(i,`Native check issue ${n}`);if(Zr(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!U$.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:Y$(a.path,`Native check issue ${n} path`),line:sb(a.line,`Native check issue ${n} line`),kind:a.kind}}),r=[...t].sort(r0);if(JSON.stringify(r)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function n0(e){if(!Array.isArray(e)||e.some(i=>typeof i!="string"||!K$.has(i)))throw new Error("Native check receipt stale reasons are invalid");let t=e,r=ob.filter(i=>t.includes(i));if(new Set(t).size!==t.length||JSON.stringify(r)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function a0(e){return T(G$,e)}function cb(e){let t=Qr(e,"Native check receipt");if(Zr(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==rb)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!W$.test(t.change))throw new Error("Native check receipt change name is invalid");let r=sb(t.sourceRevision,"Native check source revision"),i=X$(t.checker),n=Q$(t.contract),a=Z$(t.implementation),o=a0({change:t.change,sourceRevision:r,checkerHash:i.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(pr(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=ab(t.startedAt,"Native check receipt startedAt"),c=ab(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=t0(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=n0(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let p=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==p)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.batches===void 0&&l.filesSelected>We.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>We.maxFiles&&!u.some(h=>h.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let f={schema:rb,change:t.change,sourceRevision:r,checker:i,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},m=pr(t.receiptHash,"Native check receipt content hash");if(T(M$,f)!==m)throw new Error("Native check receipt content hash mismatch");return{...f,receiptHash:m}}var rb,M$,jn,Of,We,V$,W$,z$,G$,J$,ib,U$,nb,ob,K$,Hf=I(()=>{"use strict";ue();rb="comet.native.check-receipt.v1",M$="comet.native.check-receipt.v1",jn="scoped-text-safety",Of=1,We=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),V$=/^[a-f0-9]{64}$/u,W$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,z$="comet.native.checker-policy.v1",G$="comet.native.check-input.v1",J$=2048,ib=T(z$,{policy:jn,version:Of,limits:We,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),U$=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),nb=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],ob=["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"],K$=new Set(ob)});function $n(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Error(`${t} must be a plain object`);return e}function ei(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function fr(e,t){if(typeof e!="string"||!c0.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ct(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let r=ct(e).trim();if(!r||r.length>p0||r!==e.trim())throw new Error(`${t} is invalid`);return r}function Df(e,t){let r=Ct(e,t),i=new Date(r);if(Number.isNaN(i.getTime())||i.toISOString()!==r)throw new Error(`${t} must be a canonical timestamp`);return r}function Po(e,t,r=Ct,i=!1,n=f0){if(!Array.isArray(e)||e.length>n||!i&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>r(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function m0(e,t){if(typeof e!="string"||!l0.test(e))throw new Error(`${t} is invalid`);return e}function v0(e){let t=$n(e,"Native verification receipt bindings");if(ei(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!u0.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:fr(t.contractHash,"Native verification receipt contract hash"),scopeHash:fr(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:fr(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:fr(t.artifactHash,"Native verification receipt artifact hash")}}function g0(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=d0.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function w0(e,t,r,i){let n=$n(t,`Native ${e} evidence`);if(e==="automated-check"){if(ei(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=Df(n.startedAt,"Native automated-check start time"),o=Df(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(r==="passed"&&n.exitCode!==0||r==="failed"&&n.exitCode===0||r==="passed"&&(n.timedOut||n.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=$n(n.worktree,"Native automated-check worktree");if(ei(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=$n(n.afterFence,"Native automated-check after fence");if(ei(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(r==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:Ct(n.executable,"Native automated-check executable"),args:Po(n.args,"Native automated-check arguments",Ct,!0),cwd:Ct(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:Ct(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:fr(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:fr(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:fr(n.outputHash,"Native automated-check output hash"),outputSummary:Ct(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){ei(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=g0(n.checkReceiptRef);if(fr(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:Po(n.subjects,"Native static inspection subjects",Ct,i==="required-check"),rule:Ct(n.rule,"Native static inspection rule"),resultSummary:Ct(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return ei(n,["steps","observations"],"Native manual-evidence evidence"),{steps:Po(n.steps,"Native manual evidence steps"),observations:Po(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function y0(e){let t=$n(e,"Native verification receipt");if(ei(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 r=t.kind,i=t.role,n=t.status,a=Ct(t.actor,"Native verification receipt actor"),o=Po(t.acceptanceIds,"Native receipt acceptance IDs",m0,i==="required-check",h0).sort();if(i==="required-check"&&o.length!==0||i==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(i==="required-check"&&r!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:Bf,kind:r,role:i,status:n,bindings:v0(t.bindings),acceptanceIds:o,actor:a,issuedAt:Df(t.issuedAt,"Native verification receipt issue time"),evidence:w0(r,t.evidence,n,i)};if(i==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==jn||s.actor!==`native-runtime:${jn}`))throw new Error("Native required check policy identity is invalid");return s}function lb(e){let t=$n(e,"Native verification receipt");if(ei(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==Bf)throw new Error("Native verification receipt schema is invalid");let{receiptHash:r,...i}=t,n=y0(i),a=fr(t.receiptHash,"Native verification receipt hash");if(T(o0,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function Ff(e){return T(s0,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,r)=>t.path.localeCompare(r.path)||t.kind.localeCompare(r.kind)))}var Bf,o0,s0,c0,l0,u0,d0,p0,f0,h0,_o=I(()=>{"use strict";ue();Hf();Pi();Bf="comet.native.verification-receipt.v3",o0=Bf,s0="comet.native.declared-artifacts.v1",c0=/^[a-f0-9]{64}$/u,l0=/^acceptance-[a-f0-9]{64}$/u,u0=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,d0=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,p0=4096,f0=256,h0=1024});import{createHash as N0}from"node:crypto";import{promises as Rt}from"node:fs";import Gt from"node:path";function Lf(e,t){let r=Gt.relative(e,t);return r===""||!Gt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Gt.sep}`)}function b0(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function hl(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Qe(r,i)?G(r,i):G(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function ub(e){let t=await Rt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await Rt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function k0(e,t){let r=Gt.resolve(e),i=Gt.resolve(t);if(!Lf(r,i))throw new Error("Native evidence path is outside its change");let n=[await ub(r)],a=r;for(let o of Gt.relative(r,i).split(Gt.sep).filter(Boolean)){a=Gt.join(a,o);let s=await ub(a);if(!Lf(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function db(e){for(let t of e){let r=await Rt.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!b0(t,r)||await Rt.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function S0(e,t,r={}){let i=await k0(t,Gt.dirname(e));await r.afterParentChainCaptured?.();let n=await Rt.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await Rt.realpath(e);if(!Lf(i[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await Rt.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),Rt.lstat(e),Rt.realpath(e)]);if(await db(i),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!hl(s,n)||!hl(s,c))throw new Error("Native evidence document changed while opening");if(s.size>On)throw new Error(`Native evidence document exceeds ${On} bytes`);await r.afterOpen?.();let u=[],d=0,p=Buffer.allocUnsafe(64*1024);for(;;){let v=On+1-d,g=await o.read(p,0,Math.min(p.length,v),null);if(g.bytesRead===0)break;if(d+=g.bytesRead,d>On)throw new Error(`Native evidence document exceeds ${On} bytes`);u.push(Buffer.from(p.subarray(0,g.bytesRead)))}await r.beforeFinalCheck?.();let[f,m,h]=await Promise.all([o.stat(),Rt.lstat(e),Rt.realpath(e)]);if(await db(i),!m.isFile()||m.isSymbolicLink()||h!==a||!hl(s,f)||!hl(s,m))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function hb(e,t){if(!fb.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}async function E0(e,t,r,i,n){if(!fb.test(r))throw new Error("Native report evidence hash is invalid");let a=await ji({paths:e,name:t,kind:"reports",hash:r,hooks:i,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!==r||typeof o.content!="string"||N0("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==r)throw new Error("Native report evidence does not match its hash");return o.content}function Hn(e,t){let r=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!r||r[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return r[2]}function x0(e,t,r,i,n){let a=hb(r,i);return n?Gt.join(n,...a.split("/")):Or(Y(e,t),a)}async function ji(e){let t=x0(e.paths,e.name,e.kind,e.hash,e.changeDir),r=e.changeDir??we(e.paths,t);return await K(r,t),S0(t,r,e.hooks)}function pb(e,t){return ll(e,t)}function C0(e,t){let r=ul(e);if(r.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return r}function R0(e,t,r){let i=eb(e);if(i.change!==t||i.allowanceHash!==r)throw new Error("Native partial allowance ref/hash/change mismatch");return i}function P0(e,t,r){let i=$f(e);if(i.change!==t||i.envelopeHash!==r)throw new Error("Native verification evidence ref/hash/change mismatch");return i}async function _0(e,t,r,i=!1,n){let a=await ml(e,t,r.implementationScopeRef,void 0,n);if(i&&await E0(e,t,r.reportHash,void 0,n),a.scopeHash!==r.implementationScopeHash||a.contractHash!==r.contractHash||(a.complete?"complete":"partial")!==r.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(r.partialAllowanceRef===null)return;let o=await mb(e,t,r.partialAllowanceRef,void 0,n);if(o.allowanceHash!==r.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=r.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function Ao(e,t,r,i,n){let a=Hn(r,"scopes"),o=C0(await ji({paths:e,name:t,kind:"scopes",hash:a,hooks:i,changeDir:n}),a),s=Hn(o.baselineProjectionRef,"snapshots"),c=Hn(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([ji({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>pb(d,s)),ji({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>pb(d,c))]);return JN({baseline:l,current:u,scope:o})}async function ml(e,t,r,i,n){return(await Ao(e,t,r,i,n)).scope}async function mb(e,t,r,i,n){let a=Hn(r,"allowances");return R0(await ji({paths:e,name:t,kind:"allowances",hash:a,hooks:i,changeDir:n}),t,a)}async function Io(e,t,r,i,n){let a=Hn(r,"receipts"),o=lb(await ji({paths:e,name:t,kind:"receipts",hash:a,hooks:i,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function Dn(e,t,r,i,n){let a=Hn(r,"verifications"),o=P0(await ji({paths:e,name:t,kind:"verifications",hash:a,hooks:i,changeDir:n}),t,a);return await _0(e,t,o,!1,n),o}var fb,On,zG,ti=I(()=>{"use strict";ae();U();jt();Ti();fl();_o();fb=/^[a-f0-9]{64}$/u,On=Ii,zG=3*On});import vr from"node:path";import{realpathSync as fD}from"node:fs";Di();Bi();import{execFileSync as $S}from"child_process";import OS from"fs";import ni from"path";import{AsyncLocalStorage as Oh}from"node:async_hooks";Jn();var ai=new Oh,Hh=new Oh;function Dh(e){return ai.getStore()?e():ai.run(new Map,e)}function HS(e){let t=ai.getStore();for(let r of e)t?.set(wr(r.root),e);return e}function Un(e,t){return Gn(()=>$S("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim())}function Kn(e,t){return wr(e)===wr(t)}function wr(e){let t=ni.resolve(e);try{let r=OS.realpathSync.native(t);return process.platform==="win32"?r.toLowerCase():r}catch{return process.platform==="win32"?t.toLowerCase():t}}function ve(e){try{let t=Hh.getStore()?.get(wr(e)),r=ai.getStore()?.get(t??wr(e));if(r){let c=Yn(t??e,r);if(c)return c;if(r.length===0)return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}let i=ni.resolve(Un(e,["rev-parse","--show-toplevel"])),n=ai.getStore()?.get(wr(i))??Bh(e),a=Yn(i,n);if(ai.getStore()&&a)return a;let o=n[0]?.root??i,s=null;try{s=Un(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!Kn(i,o),currentWorktreeRoot:i,primaryWorktreeRoot:o,currentBranch:s}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function Uo(e){try{let t=ai.getStore()?.get(Hh.getStore()?.get(wr(e))??wr(e));return t?t.map(r=>({...r})):(Un(e,["rev-parse","--is-inside-work-tree"]),Bh(e))}catch{return[]}}function Bh(e){let t=DS(Un(e,["worktree","list","--porcelain","-z"]));return HS(t),t.map(r=>({...r}))}function DS(e){let t=e.split("\0"),r=[],i=null;for(let n of t)n.startsWith("worktree ")?(i&&r.push(i),i={root:ni.resolve(n.slice(9)),branch:null,detached:!1}):i&&n.startsWith("branch refs/heads/")?i.branch=n.slice(18):i&&n==="detached"&&(i.detached=!0);return i&&r.push(i),r}function yr(e){return Uo(e).map(t=>t.root)}function Yn(e,t){let r=t.find(a=>Kn(ni.resolve(a.root),ni.resolve(e)));if(!r)return null;let i=ni.resolve(t[0].root),n=ni.resolve(r.root);return{isGitWorktree:!0,isSecondaryWorktree:!Kn(i,n),currentWorktreeRoot:n,primaryWorktreeRoot:i,currentBranch:r.branch}}function Yt(e,t){try{let r=Un(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}ue();var Mp=Kt(It(),1);import{promises as Cy}from"fs";import Vr from"path";et();ae();fi();Je();Se();U();wt();Nn();import{createHash as BI}from"crypto";import FI from"path";var at=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"});Se();U();import{constants as Ac,promises as bt}from"node:fs";import kt from"node:path";import{TextDecoder as jI}from"node:util";import _I from"path";tn();Tr();var gI=Kt(It(),1);tn();Tr();er();er();en();Gd();tn();er();var V1=4*1024*1024;import{AsyncLocalStorage as wI}from"node:async_hooks";var yI=new wI;function NI(){let e=yI.getStore();return e?.active?e:null}function bI(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function oy(e,t){return(...r)=>{let i=NI();if(i===null)return t(...r);let n=bI(`async:${e}`,r),a=i.entries.get(n);if(a)return a.value;let o=t(...r).catch(s=>{throw i.entries.get(n)?.value===o&&i.entries.delete(n),s});return i.entries.set(n,{value:o}),o}}en();var K1=oy("hookWritePolicy",async e=>(await Md(e))?.hook??{allow_paths:[]});$a();import kI from"node:path";var _c="comet.selection.v2",cy=16*1024;function $p(e){return kI.join(e,".comet","current-change.json")}function SI(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function sy(e){return e===null||typeof e=="string"}function EI(e){let t;try{t=JSON.parse(e)}catch(r){throw new Error(`current change selection contains invalid JSON: ${r instanceof Error?r.message:String(r)}`,{cause:r})}if(!SI(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&&!sy(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:_c,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==_c)throw new Error(`current change selection schema must be ${_c}`);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(!sy(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 Op(e){let t;try{let i=$p(e),{bytes:n}=await Qi(i,cy,{label:"current change selection"});t=n.toString("utf8")}catch(i){if(i.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${i instanceof Error?i.message:String(i)}`,{cause:i})}return{status:"selected",...EI(t)}}Vd();_a();var ly=(e,t)=>{let r=e[t];return r==null?null:String(r)};function eo(e,t){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return r}function Za(e,t){let r=eo(e,t);if(_I.isAbsolute(r)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(r)||r.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return r}function AI(e){let t=e.run_retries??"{}",r;try{r=typeof t=="string"?JSON.parse(t):t}catch(i){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:i})}if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let i of Object.values(r))if(!Number.isInteger(i)||Number(i)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return r}function uy(e){if(!e.run_id)return null;let t=eo(e,"run_id"),r=eo(e,"skill"),i=eo(e,"skill_version"),n=eo(e,"skill_hash"),a=Za(e,"pending_ref"),o=Za(e,"trajectory_ref"),s=Za(e,"context_ref"),c=Za(e,"artifacts_ref"),l=Za(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:r,skillVersion:i,skillHash:n,orchestration:e.orchestration,currentStep:ly(e,"current_step"),iteration:u,pending:ly(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:AI(e)}}var QM=Number.MAX_SAFE_INTEGER;var II=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function TI(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)},r=uy(t);if(!r)throw new Error("Invalid Run state: runId must be a non-empty string");return r}function Hp(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Run state: stored value must be an object");let t=e,r=Object.keys(t).find(i=>!II.has(i));if(r)throw new Error(`Invalid Run state: unknown field ${r}`);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 TI(t)}ae();jt();var bn={runStateBytes:Number.MAX_SAFE_INTEGER,trajectoryBytes:Number.MAX_SAFE_INTEGER,trajectoryEvents:4096,trajectoryEventBytes:Number.MAX_SAFE_INTEGER,checkpointBytes:Number.MAX_SAFE_INTEGER,pendingActionBytes:Number.MAX_SAFE_INTEGER,contextBytes:Number.MAX_SAFE_INTEGER,artifactsBytes:Number.MAX_SAFE_INTEGER};function Tc(e,t){let r=kt.relative(e,t);return r===""||!kt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${kt.sep}`)}function $I(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Ic(e,t){return G({...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 OI(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function jc(e,t,r){let i=at[t];if(r!==void 0&&r!==i)throw new Error(`Native Run ${t} ref must be ${i}`);let n=kt.resolve(e),a=kt.resolve(n,...i.slice(8).split("/"));if(!Tc(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function dy(e){let t=await bt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await bt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function HI(e,t){let r=kt.resolve(e),i=kt.resolve(t);if(!Tc(r,i))throw new Error("Native Run path is outside its change");let n=[await dy(r)],a=r;for(let o of kt.relative(r,i).split(kt.sep).filter(Boolean)){a=kt.join(a,o);let s;try{s=await dy(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!Tc(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function py(e){for(let t of e){let r=await bt.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!OI(t,r)||await bt.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function DI(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function $c(e,t,r,i,n){let a=await HI(e,kt.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await bt.lstat(t)}catch(d){if(d.code==="ENOENT")return null;throw d}if(!o.isFile()||o.isSymbolicLink())throw new Error(`${i} must be a regular file`);if(o.size>r)throw new Error(`${i} exceeds ${r} bytes`);let s=$I(o),c=await bt.realpath(t);if(!Tc(a[0].realPath,c))throw new Error(`${i} resolves outside its change`);let l=process.platform==="win32"?Ac.O_RDONLY:Ac.O_RDONLY|Ac.O_NOFOLLOW|Ac.O_NONBLOCK,u;try{u=await bt.open(t,l)}catch(d){throw new Error(`${i} changed while opening`,{cause:d})}try{let[d,p,f]=await Promise.all([u.stat(),bt.lstat(t),bt.realpath(t)]);if(await py(a),!d.isFile()||!p.isFile()||p.isSymbolicLink()||f!==c||!Ic(s,d)||!Ic(s,p))throw new Error(`${i} changed while opening`);await n?.afterOpen?.();let m=await DI(u,r,i);await n?.beforeFinalCheck?.();let[h,v,g]=await Promise.all([u.stat(),bt.lstat(t),bt.realpath(t)]);if(await py(a),!v.isFile()||v.isSymbolicLink()||g!==c||!Ic(s,h)||!Ic(s,v))throw new Error(`${i} changed while reading`);let b;try{b=new jI("utf-8",{fatal:!0}).decode(m)}catch(k){throw new Error(`${i} is not valid UTF-8`,{cause:k})}return{text:b,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}function fy(e,t){try{return JSON.parse(e)}catch(r){throw new Error(`${t} contains invalid JSON`,{cause:r})}}function Dp(e){return Hp(e)}async function kn(e,t){let r=jc(e,"stateRef"),i=await $c(e,r,bn.runStateBytes,"Native Run state",t);return i?Hp(fy(i.text,"Native Run state")):null}async function bi(e,t,r){let i=jc(e,"trajectoryRef",t),n=await $c(e,i,bn.trajectoryBytes,"Native Run trajectory",r);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>bn.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${bn.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 hy(e,t,r){return(await $c(e,jc(e,"trajectoryRef",t),bn.trajectoryBytes,"Native Run trajectory",r))?.text??null}async function Oc(e,t,r){let i=await $c(e,jc(e,"checkpointRef",t),bn.checkpointBytes,"Native Run checkpoint",r);return i?fy(i.text,"Native Run checkpoint"):null}var LI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Bp(e){return BI("sha256").update(e).digest("hex")}function qI(e,t){if(!LI.test(t))throw new Error(`Invalid Native change name: ${t}`);return FI.join(Y(e,t),"trajectory.jsonl")}function MI(e){let t=e.split(/\n/u),r=0;for(let i=0;i<t.length;i+=1){let n=t[i].endsWith("\r")?t[i].slice(0,-1):t[i];if(n.length!==0){r=i+1;try{JSON.parse(n)}catch(a){return{status:"invalid",line:i+1,message:a.message}}}}return{status:"valid",count:r}}function VI(e,t){if(/Unexpected end|Unterminated string/iu.test(e.message))return!0;let r=/position (\d+)/iu.exec(e.message)?.[1];return r!==void 0&&Number(r)>=Math.max(0,t.length-1)}function WI(e,t){let r=t.lastIndexOf(10),i=t.subarray(0,r+1),n=MI(i.toString("utf8"));if(n.status==="invalid")return{status:"invalid",file:e,line:n.line,message:n.message};if(r===t.length-1)return{status:"clean",file:e};let a=t.subarray(r+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(`
179
+ `)])}catch(d){if(!VI(d,o))return{status:"invalid",file:e,line:s,message:d.message};c="incomplete-json",l=i}return{inspection:{status:"repairable",file:e,reason:c,line:s,originalHash:Bp(t),targetHash:Bp(l),tailHash:Bp(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function zI(e,t){let r=qI(e,t);await K(we(e,r),r);let i=Y(e,t),n=await hy(i,at.trajectoryRef);return n===null?{status:"clean",file:r}:WI(r,Buffer.from(n))}async function my(e,t){let r=await zI(e,t);return"inspection"in r?r.inspection:r}import{createHash as GI}from"node:crypto";import{promises as Hc}from"node:fs";import ar from"node:path";ae();et();Se();U();var to=/^[a-f0-9]{64}$/u,vy=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,JI=16*1024,Lp=process.platform,UI=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function Sn(e){return UI.has(e)}function Ny(e,t){let r=ar.relative(e,t);return ar.isAbsolute(r)||r===".."||r.startsWith(`..${ar.sep}`)?null:r.replaceAll("\\","/")||"."}function by(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function ky(e,t){if(e.length===0||by(e)||e.includes("\\")||ar.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let r=ar.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function qp(e,t){return GI("sha256").update(`${e}
180
+ ${t}`).digest("hex")}async function gy(e,t){let r=await Hc.realpath(t),i=await Hc.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Lp==="win32"?ar.normalize(r).toLowerCase():r;return qp(e,`${n}
177
181
  ${i.dev}
178
182
  ${i.ino}
179
- ${i.birthtimeMs}`)}async function cy(e,t){let r=await $c.realpath(t),i=await $c.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Hp==="win32"?ar.normalize(r).toLowerCase():r;return Dp(e,n)}function DI(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 Op(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||dy(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function fy(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Op(e.changeBranch,"Native workspace change branch"),Op(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 BI(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,r=new Set(["provider","baseCommit","targetBranch","targetCommit"]),i=Object.keys(t).filter(n=>!r.has(n));if(i.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${i.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!oy.test(t.baseCommit)||typeof t.targetCommit!="string"||!oy.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");Op(t.targetBranch,"Native workspace Git target branch")}function Oc(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,r=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),i=Object.keys(t).filter(o=>!r.has(o));if(i.length>0)throw new Error(`Native workspace identity has unknown field(s): ${i.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!eo.test(String(t.projectRootId))||!eo.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");DI(t.capturedAt),py(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&&!eo.test(String(t.projectRootPathId))||a&&!eo.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!eo.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&BI(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(fy(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 FI(e,t){return ar.join(Y(e,t),"workspace.json")}function LI(e,t){let r=FI(e,t),i=we(e,r),n=uy(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:py(n,"Native workspace file ref")}}async function qI(e,t){try{let r=LI(e,t),i=await ne({root:r.root,ref:r.ref,maxBytes:OI});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function to(e,t){let r=ve(e.projectRoot),i={projectRoot:ar.resolve(e.projectRoot),currentBranch:r.currentBranch,isSecondaryWorktree:r.isSecondaryWorktree};try{let n=await or(e,t);if(n===null)return{...i,bindingState:"missing",isolation:null,changeBranch:null,targetBranch:null,finish:null};if(n.schema!=="comet.native.workspace.v3")return{...i,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:n.git?.targetBranch??null,finish:null};let a=await Sn({paths:e,identity:n});return{...i,bindingState:a.state==="aligned"?"aligned":"drifted",isolation:n.isolation,changeBranch:n.changeBranch,targetBranch:n.targetBranch,finish:n.finish}}catch{return{...i,bindingState:"invalid",isolation:null,changeBranch:null,targetBranch:null,finish:null}}}async function MI(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=uy(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let r=ve(e.paths.projectRoot),i=r.isGitWorktree?Yt(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??r.currentBranch,a=n==null?null:Yt(e.paths.projectRoot,n),o=i!==null&&n!==null&&n!==void 0&&a!==null?{provider:"git",baseCommit:i,targetBranch:n,targetCommit:a}:void 0,[s,c,l,u]=await Promise.all([sy("comet.native.workspace-project-root.v2",e.paths.projectRoot),sy("comet.native.workspace-native-root.v2",e.paths.nativeRoot),cy("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),cy("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&&fy(e.binding);let p={capturedAt:d,capturedRevision:e.revision,nativeRootRef:t,projectRootId:s,nativeRootId:c,projectRootPathId:l,nativeRootPathId:u,...o?{git:o}:{},...e.sessionId?{sessionHash:Dp("comet.native.workspace-session.v2",`${s}
183
+ ${i.birthtimeMs}`)}async function wy(e,t){let r=await Hc.realpath(t),i=await Hc.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Lp==="win32"?ar.normalize(r).toLowerCase():r;return qp(e,n)}function KI(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 Fp(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||by(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function Sy(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Fp(e.changeBranch,"Native workspace change branch"),Fp(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 YI(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,r=new Set(["provider","baseCommit","targetBranch","targetCommit"]),i=Object.keys(t).filter(n=>!r.has(n));if(i.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${i.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!vy.test(t.baseCommit)||typeof t.targetCommit!="string"||!vy.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");Fp(t.targetBranch,"Native workspace Git target branch")}function Dc(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,r=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),i=Object.keys(t).filter(o=>!r.has(o));if(i.length>0)throw new Error(`Native workspace identity has unknown field(s): ${i.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!to.test(String(t.projectRootId))||!to.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");KI(t.capturedAt),ky(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&&!to.test(String(t.projectRootPathId))||a&&!to.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!to.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&YI(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(Sy(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 XI(e,t){return ar.join(Y(e,t),"workspace.json")}function QI(e,t){let r=XI(e,t),i=we(e,r),n=Ny(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:ky(n,"Native workspace file ref")}}async function ZI(e,t){try{let r=QI(e,t),i=await ne({root:r.root,ref:r.ref,maxBytes:JI});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function ro(e,t){let r=ve(e.projectRoot),i={projectRoot:ar.resolve(e.projectRoot),currentBranch:r.currentBranch,isSecondaryWorktree:r.isSecondaryWorktree};try{let n=await or(e,t);if(n===null)return{...i,bindingState:"missing",isolation:null,changeBranch:null,targetBranch:null,finish:null};if(n.schema!=="comet.native.workspace.v3")return{...i,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:n.git?.targetBranch??null,finish:null};let a=await En({paths:e,identity:n});return{...i,bindingState:a.state==="aligned"?"aligned":"drifted",isolation:n.isolation,changeBranch:n.changeBranch,targetBranch:n.targetBranch,finish:n.finish}}catch{return{...i,bindingState:"invalid",isolation:null,changeBranch:null,targetBranch:null,finish:null}}}async function eT(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=Ny(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let r=ve(e.paths.projectRoot),i=r.isGitWorktree?Yt(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??r.currentBranch,a=n==null?null:Yt(e.paths.projectRoot,n),o=i!==null&&n!==null&&n!==void 0&&a!==null?{provider:"git",baseCommit:i,targetBranch:n,targetCommit:a}:void 0,[s,c,l,u]=await Promise.all([gy("comet.native.workspace-project-root.v2",e.paths.projectRoot),gy("comet.native.workspace-native-root.v2",e.paths.nativeRoot),wy("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),wy("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&&Sy(e.binding);let p={capturedAt:d,capturedRevision:e.revision,nativeRootRef:t,projectRootId:s,nativeRootId:c,projectRootPathId:l,nativeRootPathId:u,...o?{git:o}:{},...e.sessionId?{sessionHash:qp("comet.native.workspace-session.v2",`${s}
180
184
  ${c}
181
- ${e.sessionId}`)}:{}},f=e.binding?{schema:"comet.native.workspace.v3",...p,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...p};return Oc(f),f}async function or(e,t){let r=await qI(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(Oc(r),r)}async function Hc(e){Oc(e.identity);let t=await MI({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),r=[],i=[];return t.nativeRootRef!==e.identity.nativeRootRef&&r.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&r.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&r.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&r.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&r.push("native-root-legacy-identity")),Hp==="win32"&&r.length>0&&r.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?i.push("workspace-inspection-unavailable"):r.length>0&&i.push("workspace-root-changed"),{state:i.length===0?"aligned":i.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:i,driftComponents:r}}async function Sn(e){if(Oc(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 Hc(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let r=ve(e.paths.projectRoot);return e.identity.changeBranch===null?r.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}:r.isGitWorktree?r.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 ${r.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!r.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 hy(e,t){let r=await or(e,t);if(r===null)return null;let i=await Sn({paths:e,identity:r});if(i.state==="drifted")throw new Error(`${i.code}: ${i.message}`);return r}Fa();cc();cc();var Dc=class extends Error{constructor(r,i,n){super(`Native change ${r} revision conflict: expected ${i}, actual ${n}`);this.change=r;this.expectedRevision=i;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},ro=class extends Error{constructor(r,i){super(`Native working directory already contains active change${i.length===1?"":"s"} ${i.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=r;this.activeChanges=i;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},Bc=class extends Error{constructor(r,i,n,a,o,s=null,c=null){super(`Native change ${r} baseline is incomplete (${i} omitted entr${i===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=r;this.omittedCount=i;this.omittedByReason=n;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},FV=Ks("en");function Ne(e,t){sn(t);let r=Vr.join(e.changesDir,t);if(!q(e.changesDir,r))throw new Error("Native change path escaped");return r}async function Fc(e,t){let r=Y(e,t),i=Vr.join(r,"schema-migration.json");await K(q(e.runtimeDir,i)?e.runtimeDir:e.nativeRoot,i);try{return await vy.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function gy(e,t){let r=Y(e,t),i=Vr.join(r,"checkpoint-journal.json");await K(q(e.runtimeDir,i)?e.runtimeDir:e.nativeRoot,i);try{return await vy.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function wy(e,t=Vr.dirname(e)){let r=Vr.relative(t,e).split(Vr.sep).join("/"),i=await ne({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,Bp.parseDocument)(i.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function Fp(e,t){let r=Vr.join(Ne(e,t),Dt);await K(e.nativeRoot,r);let i=sc(await wy(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await Fc(e,t)?{status:"migration-required",schema:i.schema,minimumRuntimeVersion:i.minimumRuntimeVersion,state:i.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(i.status==="current"&&i.state&&await zI(e,i.state),i)}async function yy(e,t){let r=Vr.join(Ne(e,t),Dt);await K(e.nativeRoot,r);let i=sc(await wy(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}async function zI(e,t){if(await Cc(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function sr(e,t){let r=await Fp(e,t);if(r.status==="migration-required")throw new on(t,r.schema);if(r.status==="runtime-incompatible"||!r.state)throw new ir(r.schema,r.minimumRuntimeVersion);return await hy(e,t),r.state}Je();import{promises as xH}from"fs";pi();import{promises as Lp}from"fs";import by from"path";et();Lt();U();var qp=["outcome","scope","nonGoals","acceptanceExamples"],Ny=[...qp,"constraints","decisions","openQuestions","verificationExpectations"],GI=["acceptanceEvidence","commandsAndResults","skippedChecks","specConsistency","knownLimitationsAndRisks","conclusion"],JI=new Set(["nonGoals","decisions","openQuestions"]),io=class extends Error{constructor(r,i,n){super(r);this.findings=i;this.change=n;this.name="NativeDocumentConstraintError"}findings;change},ky={maxFileBytes:Sd};function Sy(e){let t=new Map,r=null,i=[],n=()=>{r!==null&&t.set(r,i.join(`
182
- `).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(n(),r=o[1].trim(),i=[]):r!==null&&i.push(a)}return n(),t}async function UI(e,t){let r=by.resolve(e,...t.split(/[\\/]/u));if(!q(e,r))throw new Error(`Artifact escapes Native change: ${t}`);let i=await Lp.realpath(e),n=await Lp.realpath(r);if(!q(i,n))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await Lp.stat(n)).isFile())throw new Error(`Artifact is not a file: ${t}`);return n}function no(e){return{valid:e.length===0,findings:e}}function Ey(e){let t=[],r=0;for(;r<e.length;){let i=e.indexOf("<!--",r);if(i<0){t.push(e.slice(r));break}t.push(e.slice(r,i));let n=e.indexOf("-->",i+4);if(n<0){t.push(e.slice(i));break}r=n+3}return t.join("")}function KI(e){return Ey(e).trim()}function Mp(e){let t=KI(e).split(/\r?\n/u),r=[],i=!1;for(let n of t){if(/^\s*(?:```|~~~)/u.test(n)){i=!i;continue}!i&&/^\s*#{1,6}\s*$/u.test(n)||!i&&/^\s*#{1,6}\s+/u.test(n)||!i&&/^\s*(?:[-*+]\s*|\d+[.)]\s*)$/u.test(n)||r.push(n)}return r.join(`
183
- `).trim()}function YI(e){let t=Mp(e).replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/gmu,"").replace(/[*_`>#\x5b\x5d()]/gu," ").replace(/\s+/gu," ").trim().toLocaleLowerCase("en-US");return/^(?:none|n\/a|not applicable|no(?:ne)?(?:\s+at\s+this\s+time)?|no\s+(?:additional\s+)?(?:non-goals?|decisions?|open\s+questions?|questions?)|无|无相关事项|没有(?:额外)?(?:非目标|决定|待解决问题)|不适用|暂无)[.!。;;::,,、 -]*$/iu.test(t)}function XI(e){let t=Mp(e).replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/gmu,"").replace(/\s+/gu," ").trim();if(t.length===0)return!1;let r=t.replace(/[*_`]/gu,"").replace(/^\s*>+\s?/gmu,"").replace(/\s+/gu," ").trim();if(/^(?:<[^>\r\n]+>|\{\{[^}\r\n]+\}\})[.!。;;::,,、 -]*$/iu.test(r))return!0;let i=t.replace(/[*_`>#\x5b\x5d()]/gu," ").replace(/\s+/gu," ").trim();return/^(?:(?:todo|tbd|fixme)(?:\s*[::-]\s*.+)?|fill(?:\s+this\s+in)?(?:\s*[::-]\s*.+)?|placeholder(?:\s*[::-]\s*.+)?|待填写\S*|待补充\S*|<[^>]+>|\{\{[^}]+\}\})[.!。;;::,,、 -]*$/iu.test(i)}function xy(e){let t=new Set(["blocker","blocking","coverage","decision","open_question","question","requirement","requirements","source","source_coverage","state","status","决策","来源","覆盖","问题","状态","需求","阻塞"]),r=null;for(let i of e.split(/\r?\n/u)){let n=i.match(/^\s*(`{3,}|~{3,})/u);if(n){let s=n[1]?.[0];r===null?r=s:r===s&&(r=null);continue}if(r!==null)continue;let a=i.trim();if(/^(?:[-*+]\s+|\d+[.)]\s+)(?:\[[ xX]\]\s+)?\[blocking\](?=$|[\s::—-])/iu.test(a)||a.includes("|")&&a.split("|").some(s=>/^\s*\[blocking\](?=$|[\s::—-])/iu.test(s)))return!0;let o=a.match(/^([\p{L}\p{N}_./-]+)\s*[::]\s*\[blocking\](?=$|[\s::—-])/iu);if(o){let s=o[1]?.toLocaleLowerCase("en-US")??"";if(t.has(s)||/[./_-]/u.test(s))return!0}}return!1}async function Lc(e,t,r={}){let i=[],n;try{n=(await ne({root:e,ref:t,maxBytes:ky.maxFileBytes})).text}catch(s){return no([{code:"brief-missing",message:s.message,path:t}])}let a=new Map;for(let[s,c]of Sy(n))a.set(Us(s)??s,c);for(let s of r.compact?qp:Ny)a.has(s)||i.push({code:"brief-section-missing",message:`Missing brief section: ${s}`,path:t});let o=r.strict?Ny.filter(s=>!r.compact||a.has(s)):qp;for(let s of o){let c=a.get(s)??"";Mp(c).length===0?i.push({code:"brief-section-empty",message:`Brief section is empty: ${s}`,path:t}):XI(c)?i.push({code:"brief-section-placeholder",message:`Brief section contains only template placeholder content: ${s}`,path:t}):r.strict&&!JI.has(s)&&YI(c)&&i.push({code:"brief-section-empty",message:`Brief section must describe the confirmed work instead of declaring no items: ${s}`,path:t})}return xy(n)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),no(i)}async function Vp(e,t){let r=[],i;try{i=(await ne({root:e,ref:t,maxBytes:ky.maxFileBytes})).text}catch(a){return no([{code:"verification-missing",message:a.message,path:t}])}let n=new Map;for(let[a,o]of Sy(i))n.set(Rg(a)??a,o);for(let a of GI)n.has(a)?(n.get(a)??"").length===0&&r.push({code:"verification-section-empty",message:`Verification section is empty: ${a}`,path:t}):r.push({code:"verification-section-missing",message:`Missing verification section: ${a}`,path:t});return no(r)}function ao(e,t){return by.join(e.specsDir,t,"spec.md")}async function Cy(e,t){let r=[],i=Ne(e,t.name);for(let n of t.spec_changes){let a=ao(e,n.capability),o=null;try{await K(e.nativeRoot,a),o=await bp(a)}catch(s){if(s.code!=="ENOENT"){r.push({code:"spec-canonical-unsafe",message:s.message,path:a});continue}}if(n.operation==="create"&&o!==null&&r.push({code:"spec-create-exists",message:`Canonical spec already exists: ${n.capability}`,path:a}),n.operation!=="create"&&o===null&&r.push({code:"spec-base-missing",message:`Canonical spec is missing: ${n.capability}`,path:a}),n.operation!=="create"&&o!==null&&o!==n.base_hash&&r.push({code:"spec-base-conflict",message:`Canonical spec changed for ${n.capability}: expected ${n.base_hash}, actual ${o}`,path:a}),n.source)try{await UI(i,n.source)}catch(s){r.push({code:"spec-source-invalid",message:s.message,path:n.source})}}return no(r)}Va();ue();et();Va();ue();import Ry from"node:path";var QI="comet.native.contract.v1",ZI="comet.native.acceptance-set.v1",Py=/^[a-f0-9]{64}$/u,oo={maxAcceptanceCriteria:Ma.maxCriteria};function _y(e,t){let r=Ry.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(i=>{let n=i.codePointAt(0)??0;return n<=31||n===127})||Ry.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized project-relative ref`);return e}function Ay(e){return T("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
184
- `))}function eT(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(Py))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(Py))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=_y(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:Ay(e.markdown)},markdown:e.markdown}}function tT(e,t){return Iy(e.id,t.id)}function Iy(e,t){return e<t?-1:e>t?1:0}function Ty(e){let t=_y(e.briefSource??"brief.md","Native brief source"),r=e.specs.map(eT).sort((d,p)=>Iy(d.snapshot.capability,p.snapshot.capability)),i=r.map(({snapshot:d})=>d.capability);if(new Set(i).size!==i.length)throw new Error("Native contract contains duplicate capabilities");let n=[t,...r.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=ap(e.briefMarkdown,t,oo.maxAcceptanceCriteria);for(let{snapshot:d,markdown:p}of r)p===null||d.source===null||(a.push(...op(p,d.source,oo.maxAcceptanceCriteria-a.length)),a.push(...sw(p,d.source,oo.maxAcceptanceCriteria-a.length)));if(a.sort(tT),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>oo.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${oo.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:Ay(e.briefMarkdown)},c=r.map(({snapshot:d})=>d),l=T(ZI,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:T(QI,u)}}var rT={maxSpecs:64};async function En(e){if(e.specChanges.length>rT.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await ne({root:e.changeDir,ref:e.briefRef,maxBytes:null}),r=t.size,i=[];for(let n of e.specChanges){if(n.operation==="remove"){i.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 ne({root:e.changeDir,ref:n.source,maxBytes:null});r+=a.size,i.push({capability:n.capability,operation:n.operation,source:a.ref,baseHash:n.base_hash,markdown:a.text})}return{contract:Ty({briefSource:t.ref,briefMarkdown:t.text,specs:i}),sourceCount:i.filter(n=>n.source!==null).length+1,totalBytes:r}}Je();Se();import{promises as hT}from"node:fs";import Kp from"node:path";ot();import{promises as sT}from"node:fs";ae();za();import jy from"node:path";function so(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function co(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function De(e,t,r=!1){if(typeof e!="string"||!r&&e.length===0)throw new Error(`${t} must be ${r?"a string":"a non-empty string"}`);return e}function xn(e,t){return e===null?null:De(e,t)}function Cn(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function cT(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 lT(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Rn(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function zp(e,t){if(e===null)return null;let r=De(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function uT(e,t){let r=De(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function Gp(e,t){let r=De(e,t);if(!jy.isAbsolute(r))throw new Error(`${t} must be absolute`);return jy.resolve(r)}function dT(e,t){let r=`Native local checks[${t}]`,i=so(e,r);if(co(i,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log","activeProcess","evidence","evidenceDigest"]),r),!Array.isArray(i.argv)||i.argv.length===0)throw new Error(`${r}.argv must be a non-empty array`);let n=i.argv.map((u,d)=>De(u,`${r}.argv[${d}]`,!0)),a=Rn(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=zp(i.startedAt,`${r}.startedAt`),s=zp(i.completedAt,`${r}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${r} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${r} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${r} completed check requires startedAt and completedAt`);let c=Cn(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);let l;if(Object.hasOwn(i,"activeProcess"))if(i.activeProcess===null)l=null;else{let u=so(i.activeProcess,`${r}.activeProcess`),d=Rn(u.status,["starting","running"],`${r}.activeProcess.status`);if(co(u,new Set(["status","pid","identity"]),`${r}.activeProcess`),d==="starting"){if(Object.hasOwn(u,"pid")||Object.hasOwn(u,"identity"))throw new Error(`${r}.activeProcess starting state cannot contain process identity`);l={status:"starting"}}else l={status:"running",pid:Cn(u.pid,`${r}.activeProcess.pid`,1),...Object.hasOwn(u,"identity")?{identity:De(u.identity,`${r}.activeProcess.identity`)}:{}}}return{id:De(i.id,`${r}.id`),name:De(i.name,`${r}.name`),operationId:De(i.operationId,`${r}.operationId`),status:a,repeatable:lT(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:Cn(i.executionCount,`${r}.executionCount`),argv:n,cwd:Gp(i.cwd,`${r}.cwd`),exitCode:cT(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:De(i.log,`${r}.log`),...Object.hasOwn(i,"activeProcess")?{activeProcess:l}:{},...Object.hasOwn(i,"evidence")?{evidence:Rn(i.evidence,["runtime"],`${r}.evidence`)}:{},...Object.hasOwn(i,"evidenceDigest")?{evidenceDigest:De(i.evidenceDigest,`${r}.evidenceDigest`)}:{}}}function pT(e){let t="Native local execution state",r=so(e,t);if(co(r,new Set(["schema","change","basedOnStateVersion","candidateId","inputFingerprint","inputFingerprintGate","candidateInputFingerprintGate","workspace","execution","checks"]),t),r.schema!==pc)throw new Error(`Native local execution schema must be ${pc}`);let i=so(r.workspace,"Native local workspace");co(i,new Set(["projectRoot","worktreeRoot","branch","machineId"]),"Native local workspace");let n=null;if(r.execution!==null){let o=so(r.execution,"Native local execution");co(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds","verifierStartedAt","ownerPid","ownerIdentity"]),"Native local execution");let s=zp(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:De(o.operationId,"Native local execution.operationId"),stage:Rn(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Rn(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:xn(o.executionId,"Native local execution.executionId"),status:Rn(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Cn(o.requestCheckRounds,"Native local execution.requestCheckRounds"),...Object.hasOwn(o,"verifierStartedAt")?{verifierStartedAt:uT(o.verifierStartedAt,"Native local execution.verifierStartedAt")}:{},...Object.hasOwn(o,"ownerPid")?{ownerPid:Cn(o.ownerPid,"Native local execution.ownerPid",1)}:{},...Object.hasOwn(o,"ownerIdentity")?{ownerIdentity:De(o.ownerIdentity,"Native local execution.ownerIdentity")}:{}}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(dT);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:pc,change:De(r.change,"Native local change"),basedOnStateVersion:Cn(r.basedOnStateVersion,"Native local basedOnStateVersion",1),...Object.hasOwn(r,"candidateId")?{candidateId:xn(r.candidateId,"Native local candidateId")}:{},...Object.hasOwn(r,"inputFingerprint")?{inputFingerprint:xn(r.inputFingerprint,"Native local inputFingerprint")}:{},...Object.hasOwn(r,"inputFingerprintGate")?{inputFingerprintGate:xn(r.inputFingerprintGate,"Native local inputFingerprintGate")}:{},...Object.hasOwn(r,"candidateInputFingerprintGate")?{candidateInputFingerprintGate:xn(r.candidateInputFingerprintGate,"Native local candidateInputFingerprintGate")}:{},workspace:{projectRoot:Gp(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Gp(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:xn(i.branch,"Native local workspace.branch"),...Object.hasOwn(i,"machineId")?{machineId:De(i.machineId,"Native local workspace.machineId")}:{}},execution:n,checks:a}}async function qc(e){let t;try{t=await sT.readFile(e,"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}let r;try{r=JSON.parse(t)}catch(i){throw new Error(`Native local execution state is invalid JSON: ${i.message}`,{cause:i})}return pT(r)}function Jp(e,t){let r=t?.execution;if(!(e.phase!=="verify"||e.status!=="active"||e.loop.next_action!=="await-verifier-result"||e.builder_handoff?.candidate_id===void 0||e.builder_handoff?.candidate_id===null||t===null||t.change!==e.name||t.basedOnStateVersion!==e.state_version||t.candidateId!==e.builder_handoff.candidate_id||r==null||r.stage!=="verifying"||r.actor!=="verifier"||r.status!=="running"||r.executionId===null))return r.executionId}function Up(e,t){if(Jp(e,t)!==void 0)return t.execution.verifierStartedAt!=null||t.execution.requestCheckRounds>0?"confirmed":"unconfirmed"}gt();U();var $y=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Oy="comet-state.yaml",Hy="state.json";function bi(e,t){if(!$y.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=Kp.join(e.changesDir,t);if(!q(e.changesDir,r))throw new Error("Native change path escaped");return r}function Mc(e,t){return Kp.join(bi(e,t),Oy)}function Wr(e,t){return Kp.join(vt(e,t),Hy)}async function Vc(e,t){try{let r=await hT.readFile(Mc(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}async function St(e,t){return Br(Mc(e,t))}async function Yp(e){let t=await St(e.paths,e.name),r=Wr(e.paths,e.name);try{let i=await qc(r);return i===null?{state:t,local:null,localStatus:"missing"}:i.change!==t.name||i.basedOnStateVersion!==t.state_version?{state:t,local:null,localStatus:"stale"}:{state:t,local:i,localStatus:"available"}}catch(i){return i.code==="ENOENT"?{state:t,local:null,localStatus:"missing"}:{state:t,local:null,localStatus:"invalid"}}}function ef(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Ei=ef();function Wy(e){Ei=e}var ki={exec:()=>null};function Pn(e){let t=[];return r=>{let i=Math.max(0,Math.min(3,r-1)),n=t[i];return n||(n=e(i),t[i]=n),n}}function M(e,t=""){let r=typeof e=="string"?e:e.source,i={replace:(n,a)=>{let o=typeof a=="string"?a:a.source;return o=o.replace(xe.caret,"$1"),r=r.replace(n,o),i},getRegex:()=>new RegExp(r,t)};return i}var mT=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),xe={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:Pn(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:Pn(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:Pn(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:Pn(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:Pn(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:Pn(e=>new RegExp(`^ {0,${e}}>`))},vT=/^(?:[ \t]*(?:\n|$))+/,gT=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,wT=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,po=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,yT=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,tf=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,zy=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Gy=M(zy).replace(/bull/g,tf).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),NT=M(zy).replace(/bull/g,tf).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),rf=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,bT=/^[^\n]+/,nf=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,kT=M(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",nf).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),ST=M(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,tf).getRegex(),Uc="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",af=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,ET=M("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",af).replace("tag",Uc).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Jy=e=>M(rf).replace("hr",po).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",e).replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Uc).getRegex(),xT=Jy(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),CT=Jy(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),RT=M(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",CT).getRegex(),of={blockquote:RT,code:gT,def:kT,fences:wT,heading:yT,hr:po,html:ET,lheading:Gy,list:ST,newline:vT,paragraph:xT,table:ki,text:bT},Dy=M("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",po).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Uc).getRegex(),PT={...of,lheading:NT,table:Dy,paragraph:M(rf).replace("hr",po).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Dy).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Uc).getRegex()},_T={...of,html:M(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",af).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:ki,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:M(rf).replace("hr",po).replace("heading",` *#{1,6} *[^
185
- ]`).replace("lheading",Gy).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},AT=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,IT=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Uy=/^( {2,}|\\)\n(?!\s*$)/,TT=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,cr=/[\p{P}\p{S}]/u,_n=/[\s\p{P}\p{S}]/u,fo=/[^\s\p{P}\p{S}]/u,jT=M(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,_n).getRegex(),$T=/[\p{Pi}\p{Ps}"']/u,Ky=/(?!~)[\p{P}\p{S}]/u,OT=/(?!~)[\s\p{P}\p{S}]/u,HT=/(?:[^\s\p{P}\p{S}]|~)/u,DT=M(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",mT?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Yy=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,BT=M(Yy,"u").replace(/punct/g,cr).getRegex(),FT=M(Yy,"u").replace(/punct/g,Ky).getRegex(),LT=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,qT=M(LT,"u").replace(/openQuote/g,$T).replace(/punct/g,cr).getRegex(),Xy="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",MT=M(Xy,"gu").replace(/notPunctSpace/g,fo).replace(/punctSpace/g,_n).replace(/punct/g,cr).getRegex(),VT=M(Xy,"gu").replace(/notPunctSpace/g,HT).replace(/punctSpace/g,OT).replace(/punct/g,Ky).getRegex(),WT="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",zT=M(WT,"gu").replace(/notPunctSpace/g,fo).replace(/punctSpace/g,_n).replace(/punct/g,cr).getRegex(),GT=M("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,fo).replace(/punctSpace/g,_n).replace(/punct/g,cr).getRegex(),JT="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",UT=M(JT,"gu").replace(/notPunctSpace/g,fo).replace(/punctSpace/g,_n).replace(/punct/g,cr).getRegex(),KT=M(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,cr).getRegex(),YT="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",XT=M(YT,"gu").replace(/notPunctSpace/g,fo).replace(/punctSpace/g,_n).replace(/punct/g,cr).getRegex(),QT=M(/\\(punct)/,"gu").replace(/punct/g,cr).getRegex(),ZT=M(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),ej=M(af).replace("(?:-->|$)","-->").getRegex(),tj=M("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",ej).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),zc=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,rj=M(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",zc).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Qy=M(/^!?\[(label)\]\[(ref)\]/).replace("label",zc).replace("ref",nf).getRegex(),Zy=M(/^!?\[(ref)\](?:\[\])?/).replace("ref",nf).getRegex(),ij=M("reflink|nolink(?!\\()","g").replace("reflink",Qy).replace("nolink",Zy).getRegex(),By=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,sf={_backpedal:ki,anyPunctuation:QT,autolink:ZT,blockSkip:DT,br:Uy,code:IT,del:ki,delLDelim:ki,delRDelim:ki,emStrongLDelim:BT,emStrongRDelimAst:MT,emStrongRDelimUnd:GT,escape:AT,link:rj,nolink:Zy,punctuation:jT,reflink:Qy,reflinkSearch:ij,tag:tj,text:TT,url:ki},nj={...sf,emStrongLDelim:qT,emStrongRDelimAst:zT,emStrongRDelimUnd:UT,link:M(/^!?\[(label)\]\((.*?)\)/).replace("label",zc).getRegex(),reflink:M(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",zc).getRegex()},Xp={...sf,emStrongRDelimAst:VT,emStrongLDelim:FT,delLDelim:KT,delRDelim:XT,url:M(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",By).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:M(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",By).getRegex()},aj={...Xp,br:M(Uy).replace("{2,}","*").getRegex(),text:M(Xp.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Wc={normal:of,gfm:PT,pedantic:_T},lo={normal:sf,gfm:Xp,breaks:aj,pedantic:nj},oj={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Fy=e=>oj[e];function Mt(e,t){if(t){if(xe.escapeTest.test(e))return e.replace(xe.escapeReplace,Fy)}else if(xe.escapeTestNoEncode.test(e))return e.replace(xe.escapeReplaceNoEncode,Fy);return e}function Ly(e){try{e=encodeURI(e).replace(xe.percentDecode,"%")}catch{return null}return e}function qy(e,t){let r=e.replace(xe.findPipe,(a,o,s)=>{let c=!1,l=o;for(;--l>=0&&s[l]==="\\";)c=!c;return c?"|":" |"}),i=r.split(xe.splitPipe),n=0;if(i[0].trim()||i.shift(),i.length>0&&!i.at(-1)?.trim()&&i.pop(),t)if(i.length>t)i.splice(t);else for(;i.length<t;)i.push("");for(;n<i.length;n++)i[n]=i[n].trim().replace(xe.slashPipe,"|");return i}function zr(e,t,r){let i=e.length;if(i===0)return"";let n=0;for(;n<i;){let a=e.charAt(i-n-1);if(a===t&&!r)n++;else if(a!==t&&r)n++;else break}return e.slice(0,i-n)}function My(e){let t=e.split(`
185
+ ${e.sessionId}`)}:{}},f=e.binding?{schema:"comet.native.workspace.v3",...p,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...p};return Dc(f),f}async function or(e,t){let r=await ZI(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(Dc(r),r)}async function Bc(e){Dc(e.identity);let t=await eT({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),r=[],i=[];return t.nativeRootRef!==e.identity.nativeRootRef&&r.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&r.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&r.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&r.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&r.push("native-root-legacy-identity")),Lp==="win32"&&r.length>0&&r.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?i.push("workspace-inspection-unavailable"):r.length>0&&i.push("workspace-root-changed"),{state:i.length===0?"aligned":i.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:i,driftComponents:r}}async function En(e){if(Dc(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 Bc(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let r=ve(e.paths.projectRoot);return e.identity.changeBranch===null?r.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}:r.isGitWorktree?r.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 ${r.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!r.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 Ey(e,t){let r=await or(e,t);if(r===null)return null;let i=await En({paths:e,identity:r});if(i.state==="drifted")throw new Error(`${i.code}: ${i.message}`);return r}La();uc();uc();var Fc=class extends Error{constructor(r,i,n){super(`Native change ${r} revision conflict: expected ${i}, actual ${n}`);this.change=r;this.expectedRevision=i;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},io=class extends Error{constructor(r,i){super(`Native working directory already contains active change${i.length===1?"":"s"} ${i.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=r;this.activeChanges=i;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},Lc=class extends Error{constructor(r,i,n,a,o,s=null,c=null){super(`Native change ${r} baseline is incomplete (${i} omitted entr${i===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=r;this.omittedCount=i;this.omittedByReason=n;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},QV=Xs("en");function Ne(e,t){cn(t);let r=Vr.join(e.changesDir,t);if(!q(e.changesDir,r))throw new Error("Native change path escaped");return r}async function qc(e,t){let r=Y(e,t),i=Vr.join(r,"schema-migration.json");await K(q(e.runtimeDir,i)?e.runtimeDir:e.nativeRoot,i);try{return await Cy.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Ry(e,t){let r=Y(e,t),i=Vr.join(r,"checkpoint-journal.json");await K(q(e.runtimeDir,i)?e.runtimeDir:e.nativeRoot,i);try{return await Cy.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Py(e,t=Vr.dirname(e)){let r=Vr.relative(t,e).split(Vr.sep).join("/"),i=await ne({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,Mp.parseDocument)(i.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function Vp(e,t){let r=Vr.join(Ne(e,t),Dt);await K(e.nativeRoot,r);let i=lc(await Py(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await qc(e,t)?{status:"migration-required",schema:i.schema,minimumRuntimeVersion:i.minimumRuntimeVersion,state:i.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(i.status==="current"&&i.state&&await iT(e,i.state),i)}async function _y(e,t){let r=Vr.join(Ne(e,t),Dt);await K(e.nativeRoot,r);let i=lc(await Py(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}async function iT(e,t){if(await Pc(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function sr(e,t){let r=await Vp(e,t);if(r.status==="migration-required")throw new sn(t,r.schema);if(r.status==="runtime-incompatible"||!r.state)throw new ir(r.schema,r.minimumRuntimeVersion);return await Ey(e,t),r.state}Je();import{promises as BH}from"fs";fi();import{promises as Wp}from"fs";import Iy from"path";et();Lt();U();var zp=["outcome","scope","nonGoals","acceptanceExamples"],Ay=[...zp,"constraints","decisions","openQuestions","verificationExpectations"],nT=["acceptanceEvidence","commandsAndResults","skippedChecks","specConsistency","knownLimitationsAndRisks","conclusion"],aT=new Set(["nonGoals","decisions","openQuestions"]),no=class extends Error{constructor(r,i,n){super(r);this.findings=i;this.change=n;this.name="NativeDocumentConstraintError"}findings;change},Ty={maxFileBytes:Cd};function jy(e){let t=new Map,r=null,i=[],n={marker:null,length:0},a=()=>{r!==null&&t.set(r,i.join(`
186
+ `).trim())};for(let o of e.split(/\r?\n/u)){let c=oo(o,n)===null&&n.marker===null?/^# ([^#].*)$/u.exec(o):null;c?(a(),r=c[1].trim(),i=[]):r!==null&&i.push(o)}return a(),t}async function oT(e,t){let r=Iy.resolve(e,...t.split(/[\\/]/u));if(!q(e,r))throw new Error(`Artifact escapes Native change: ${t}`);let i=await Wp.realpath(e),n=await Wp.realpath(r);if(!q(i,n))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await Wp.stat(n)).isFile())throw new Error(`Artifact is not a file: ${t}`);return n}function ao(e){return{valid:e.length===0,findings:e}}function $y(e){let t=[],r=0;for(;r<e.length;){let i=e.indexOf("<!--",r);if(i<0){t.push(e.slice(r));break}t.push(e.slice(r,i));let n=e.indexOf("-->",i+4);if(n<0){t.push(e.slice(i));break}r=n+3}return t.join("")}function Gp(e){return $y(e).trim()}function Mc(e){let t=Gp(e).split(/\r?\n/u),r=[],i={marker:null,length:0};for(let n of t)oo(n,i)===null&&(i.marker===null&&/^\s*#{1,6}\s*$/u.test(n)||i.marker===null&&/^\s*#{1,6}\s+/u.test(n)||i.marker===null&&/^\s*(?:[-*+]\s*|\d+[.)]\s*)$/u.test(n)||r.push(n));return r.join(`
187
+ `).trim()}function sT(e){let t=Mc(e).replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/gmu,"").replace(/[*_`>#\x5b\x5d()]/gu," ").replace(/\s+/gu," ").trim().toLocaleLowerCase("en-US");return/^(?:none|n\/a|not applicable|no(?:ne)?(?:\s+at\s+this\s+time)?|no\s+(?:additional\s+)?(?:non-goals?|decisions?|open\s+questions?|questions?)|无|无相关事项|没有(?:额外)?(?:非目标|决定|待解决问题)|不适用|暂无)[.!。;;::,,、 -]*$/iu.test(t)}function Oy(e){let t=Mc(e).replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/gmu,"").replace(/\s+/gu," ").trim();if(t.length===0)return!1;let r=t.replace(/[*_`]/gu,"").replace(/^\s*>+\s?/gmu,"").replace(/\s+/gu," ").trim();if(/^(?:<[^>\r\n]+>|\{\{[^}\r\n]+\}\})[.!。;;::,,、 -]*$/iu.test(r))return!0;let i=t.replace(/[*_`>#\x5b\x5d()]/gu," ").replace(/\s+/gu," ").trim();return/^(?:(?:todo|tbd|fixme)(?:\s*[::-]\s*.+)?|fill(?:\s+this\s+in)?(?:\s*[::-]\s*.+)?|placeholder(?:\s*[::-]\s*.+)?|待填写\S*|待补充\S*|<[^>]+>|\{\{[^}]+\}\})[.!。;;::,,、 -]*$/iu.test(i)}function Hy(e){let t=new Set(["blocker","blocking","coverage","decision","open_question","question","requirement","requirements","source","source_coverage","state","status","决策","来源","覆盖","问题","状态","需求","阻塞"]),r={marker:null,length:0};for(let i of e.split(/\r?\n/u)){if(oo(i,r)!==null||r.marker!==null)continue;let n=i.trim();if(/^(?:[-*+]\s+|\d+[.)]\s+)(?:\[[ xX]\]\s+)?\[blocking\](?=$|[\s::—-])/iu.test(n)||n.includes("|")&&n.split("|").some(o=>/^\s*\[blocking\](?=$|[\s::—-])/iu.test(o)))return!0;let a=n.match(/^([\p{L}\p{N}_./-]+)\s*[::]\s*\[blocking\](?=$|[\s::—-])/iu);if(a){let o=a[1]?.toLocaleLowerCase("en-US")??"";if(t.has(o)||/[./_-]/u.test(o))return!0}}return!1}function oo(e,t){let r=/^ {0,3}(`{3,}|~{3,})/u.exec(e);if(r===null)return null;let i=r[1]??"",n=i[0];return t.marker===null?(t.marker=n,t.length=i.length,"opened"):n===t.marker&&i.length>=t.length&&e.trim()===i?(t.marker=null,t.length=0,"closed"):null}function cT(e){let t=Gp(e).split(/\r?\n/u),r={marker:null,length:0},i=-1;for(let n=0;n<t.length;n+=1){let a=t[n]??"";if(oo(a,r)!==null||r.marker!==null)continue;let o=/^##\s+(.+)$/u.exec(a);if(o!==null){if(i===-1){Hg(o[1]??"")&&(i=n+1);continue}return t.slice(i,n).join(`
188
+ `)}}return i===-1?null:t.slice(i).join(`
189
+ `)}function lT(e){let t=new Map,r=null,i=[],n={marker:null,length:0},a=()=>{r!==null&&t.set(r,i.join(`
190
+ `).trim())};for(let o of Gp(e).split(/\r?\n/u)){if(oo(o,n)!==null){r!==null&&i.push(o);continue}let s=n.marker===null?/^###\s+(.+)$/u.exec(o):null;s!==null?(a(),r=Dg(s[1]??""),i=[]):r!==null&&i.push(o)}return a(),t}function uT(e,t){let r=[],i=cT(e);if(i===null)return r.push({code:"brief-structure-missing",message:'Brief scope must include a "## Directory structure"/「## 目录结构」 section with the subsections Created/新建, Modified/修改, Deleted/删除, and Not created/明确不建',path:t}),r;let n=lT(i),a=[];for(let o of Hd){let s=n.get(o);(s===void 0||Mc(s).length===0||Oy(s))&&a.push(Og(o))}return a.length>0&&r.push({code:"brief-structure-subsection-missing",message:`Brief directory structure subsections are missing or empty: ${a.join(", ")}. Keep every heading and write "None"/「无」 when there is no content`,path:t}),r}async function Vc(e,t,r={}){let i=[],n;try{n=(await ne({root:e,ref:t,maxBytes:Ty.maxFileBytes})).text}catch(s){return ao([{code:"brief-missing",message:s.message,path:t}])}let a=new Map;for(let[s,c]of jy(n))a.set(Ys(s)??s,c);for(let s of r.compact?zp:Ay)a.has(s)||i.push({code:"brief-section-missing",message:`Missing brief section: ${s}`,path:t});let o=r.strict?Ay.filter(s=>!r.compact||a.has(s)):zp;for(let s of o){let c=a.get(s)??"";Mc(c).length===0?i.push({code:"brief-section-empty",message:`Brief section is empty: ${s}`,path:t}):Oy(c)?i.push({code:"brief-section-placeholder",message:`Brief section contains only template placeholder content: ${s}`,path:t}):r.strict&&!aT.has(s)&&sT(c)&&i.push({code:"brief-section-empty",message:`Brief section must describe the confirmed work instead of declaring no items: ${s}`,path:t})}return r.strict&&r.structure&&i.push(...uT(a.get("scope")??"",t)),Hy(n)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),ao(i)}async function Jp(e,t){let r=[],i;try{i=(await ne({root:e,ref:t,maxBytes:Ty.maxFileBytes})).text}catch(a){return ao([{code:"verification-missing",message:a.message,path:t}])}let n=new Map;for(let[a,o]of jy(i))n.set($g(a)??a,o);for(let a of nT)n.has(a)?(n.get(a)??"").length===0&&r.push({code:"verification-section-empty",message:`Verification section is empty: ${a}`,path:t}):r.push({code:"verification-section-missing",message:`Missing verification section: ${a}`,path:t});return ao(r)}function so(e,t){return Iy.join(e.specsDir,t,"spec.md")}async function Dy(e,t){let r=[],i=Ne(e,t.name);for(let n of t.spec_changes){let a=so(e,n.capability),o=null;try{await K(e.nativeRoot,a),o=await xp(a)}catch(s){if(s.code!=="ENOENT"){r.push({code:"spec-canonical-unsafe",message:s.message,path:a});continue}}if(n.operation==="create"&&o!==null&&r.push({code:"spec-create-exists",message:`Canonical spec already exists: ${n.capability}`,path:a}),n.operation!=="create"&&o===null&&r.push({code:"spec-base-missing",message:`Canonical spec is missing: ${n.capability}`,path:a}),n.operation!=="create"&&o!==null&&o!==n.base_hash&&r.push({code:"spec-base-conflict",message:`Canonical spec changed for ${n.capability}: expected ${n.base_hash}, actual ${o}`,path:a}),n.source)try{await oT(i,n.source)}catch(s){r.push({code:"spec-source-invalid",message:s.message,path:n.source})}}return ao(r)}Wa();ue();et();Wa();ue();import By from"node:path";var dT="comet.native.contract.v1",pT="comet.native.acceptance-set.v1",Fy=/^[a-f0-9]{64}$/u,co={maxAcceptanceCriteria:Va.maxCriteria};function Ly(e,t){let r=By.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(i=>{let n=i.codePointAt(0)??0;return n<=31||n===127})||By.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized project-relative ref`);return e}function qy(e){return T("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
191
+ `))}function fT(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(Fy))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(Fy))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=Ly(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:qy(e.markdown)},markdown:e.markdown}}function hT(e,t){return My(e.id,t.id)}function My(e,t){return e<t?-1:e>t?1:0}function Vy(e){let t=Ly(e.briefSource??"brief.md","Native brief source"),r=e.specs.map(fT).sort((d,p)=>My(d.snapshot.capability,p.snapshot.capability)),i=r.map(({snapshot:d})=>d.capability);if(new Set(i).size!==i.length)throw new Error("Native contract contains duplicate capabilities");let n=[t,...r.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=lp(e.briefMarkdown,t,co.maxAcceptanceCriteria);for(let{snapshot:d,markdown:p}of r)p===null||d.source===null||(a.push(...up(p,d.source,co.maxAcceptanceCriteria-a.length)),a.push(...gw(p,d.source,co.maxAcceptanceCriteria-a.length)));if(a.sort(hT),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>co.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${co.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:qy(e.briefMarkdown)},c=r.map(({snapshot:d})=>d),l=T(pT,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:T(dT,u)}}var mT={maxSpecs:64};async function xn(e){if(e.specChanges.length>mT.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await ne({root:e.changeDir,ref:e.briefRef,maxBytes:null}),r=t.size,i=[];for(let n of e.specChanges){if(n.operation==="remove"){i.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 ne({root:e.changeDir,ref:n.source,maxBytes:null});r+=a.size,i.push({capability:n.capability,operation:n.operation,source:a.ref,baseHash:n.base_hash,markdown:a.text})}return{contract:Vy({briefSource:t.ref,briefMarkdown:t.text,specs:i}),sourceCount:i.filter(n=>n.source!==null).length+1,totalBytes:r}}Je();Se();import{promises as RT}from"node:fs";import Zp from"node:path";ot();import{promises as NT}from"node:fs";ae();Ga();import Wy from"node:path";function lo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function uo(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function De(e,t,r=!1){if(typeof e!="string"||!r&&e.length===0)throw new Error(`${t} must be ${r?"a string":"a non-empty string"}`);return e}function Cn(e,t){return e===null?null:De(e,t)}function Rn(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function bT(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 kT(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Pn(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Kp(e,t){if(e===null)return null;let r=De(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function ST(e,t){let r=De(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function Yp(e,t){let r=De(e,t);if(!Wy.isAbsolute(r))throw new Error(`${t} must be absolute`);return Wy.resolve(r)}function ET(e,t){let r=`Native local checks[${t}]`,i=lo(e,r);if(uo(i,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log","activeProcess","evidence","evidenceDigest"]),r),!Array.isArray(i.argv)||i.argv.length===0)throw new Error(`${r}.argv must be a non-empty array`);let n=i.argv.map((u,d)=>De(u,`${r}.argv[${d}]`,!0)),a=Pn(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=Kp(i.startedAt,`${r}.startedAt`),s=Kp(i.completedAt,`${r}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${r} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${r} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${r} completed check requires startedAt and completedAt`);let c=Rn(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);let l;if(Object.hasOwn(i,"activeProcess"))if(i.activeProcess===null)l=null;else{let u=lo(i.activeProcess,`${r}.activeProcess`),d=Pn(u.status,["starting","running"],`${r}.activeProcess.status`);if(uo(u,new Set(["status","pid","identity"]),`${r}.activeProcess`),d==="starting"){if(Object.hasOwn(u,"pid")||Object.hasOwn(u,"identity"))throw new Error(`${r}.activeProcess starting state cannot contain process identity`);l={status:"starting"}}else l={status:"running",pid:Rn(u.pid,`${r}.activeProcess.pid`,1),...Object.hasOwn(u,"identity")?{identity:De(u.identity,`${r}.activeProcess.identity`)}:{}}}return{id:De(i.id,`${r}.id`),name:De(i.name,`${r}.name`),operationId:De(i.operationId,`${r}.operationId`),status:a,repeatable:kT(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:Rn(i.executionCount,`${r}.executionCount`),argv:n,cwd:Yp(i.cwd,`${r}.cwd`),exitCode:bT(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:De(i.log,`${r}.log`),...Object.hasOwn(i,"activeProcess")?{activeProcess:l}:{},...Object.hasOwn(i,"evidence")?{evidence:Pn(i.evidence,["runtime"],`${r}.evidence`)}:{},...Object.hasOwn(i,"evidenceDigest")?{evidenceDigest:De(i.evidenceDigest,`${r}.evidenceDigest`)}:{}}}function xT(e){let t="Native local execution state",r=lo(e,t);if(uo(r,new Set(["schema","change","basedOnStateVersion","candidateId","inputFingerprint","inputFingerprintGate","candidateInputFingerprintGate","workspace","execution","checks"]),t),r.schema!==hc)throw new Error(`Native local execution schema must be ${hc}`);let i=lo(r.workspace,"Native local workspace");uo(i,new Set(["projectRoot","worktreeRoot","branch","machineId"]),"Native local workspace");let n=null;if(r.execution!==null){let o=lo(r.execution,"Native local execution");uo(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds","verifierStartedAt","ownerPid","ownerIdentity"]),"Native local execution");let s=Kp(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:De(o.operationId,"Native local execution.operationId"),stage:Pn(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Pn(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Cn(o.executionId,"Native local execution.executionId"),status:Pn(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Rn(o.requestCheckRounds,"Native local execution.requestCheckRounds"),...Object.hasOwn(o,"verifierStartedAt")?{verifierStartedAt:ST(o.verifierStartedAt,"Native local execution.verifierStartedAt")}:{},...Object.hasOwn(o,"ownerPid")?{ownerPid:Rn(o.ownerPid,"Native local execution.ownerPid",1)}:{},...Object.hasOwn(o,"ownerIdentity")?{ownerIdentity:De(o.ownerIdentity,"Native local execution.ownerIdentity")}:{}}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(ET);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:hc,change:De(r.change,"Native local change"),basedOnStateVersion:Rn(r.basedOnStateVersion,"Native local basedOnStateVersion",1),...Object.hasOwn(r,"candidateId")?{candidateId:Cn(r.candidateId,"Native local candidateId")}:{},...Object.hasOwn(r,"inputFingerprint")?{inputFingerprint:Cn(r.inputFingerprint,"Native local inputFingerprint")}:{},...Object.hasOwn(r,"inputFingerprintGate")?{inputFingerprintGate:Cn(r.inputFingerprintGate,"Native local inputFingerprintGate")}:{},...Object.hasOwn(r,"candidateInputFingerprintGate")?{candidateInputFingerprintGate:Cn(r.candidateInputFingerprintGate,"Native local candidateInputFingerprintGate")}:{},workspace:{projectRoot:Yp(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Yp(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Cn(i.branch,"Native local workspace.branch"),...Object.hasOwn(i,"machineId")?{machineId:De(i.machineId,"Native local workspace.machineId")}:{}},execution:n,checks:a}}async function Wc(e){let t;try{t=await NT.readFile(e,"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}let r;try{r=JSON.parse(t)}catch(i){throw new Error(`Native local execution state is invalid JSON: ${i.message}`,{cause:i})}return xT(r)}function Xp(e,t){let r=t?.execution;if(!(e.phase!=="verify"||e.status!=="active"||e.loop.next_action!=="await-verifier-result"||e.builder_handoff?.candidate_id===void 0||e.builder_handoff?.candidate_id===null||t===null||t.change!==e.name||t.basedOnStateVersion!==e.state_version||t.candidateId!==e.builder_handoff.candidate_id||r==null||r.stage!=="verifying"||r.actor!=="verifier"||r.status!=="running"||r.executionId===null))return r.executionId}function Qp(e,t){if(Xp(e,t)!==void 0)return t.execution.verifierStartedAt!=null||t.execution.requestCheckRounds>0?"confirmed":"unconfirmed"}gt();U();var zy=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Gy="comet-state.yaml",Jy="state.json";function ki(e,t){if(!zy.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=Zp.join(e.changesDir,t);if(!q(e.changesDir,r))throw new Error("Native change path escaped");return r}function zc(e,t){return Zp.join(ki(e,t),Gy)}function Wr(e,t){return Zp.join(vt(e,t),Jy)}async function Gc(e,t){try{let r=await RT.readFile(zc(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}async function St(e,t){return Br(zc(e,t))}async function ef(e){let t=await St(e.paths,e.name),r=Wr(e.paths,e.name);try{let i=await Wc(r);return i===null?{state:t,local:null,localStatus:"missing"}:i.change!==t.name||i.basedOnStateVersion!==t.state_version?{state:t,local:null,localStatus:"stale"}:{state:t,local:i,localStatus:"available"}}catch(i){return i.code==="ENOENT"?{state:t,local:null,localStatus:"missing"}:{state:t,local:null,localStatus:"invalid"}}}function af(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var xi=af();function tN(e){xi=e}var Si={exec:()=>null};function _n(e){let t=[];return r=>{let i=Math.max(0,Math.min(3,r-1)),n=t[i];return n||(n=e(i),t[i]=n),n}}function M(e,t=""){let r=typeof e=="string"?e:e.source,i={replace:(n,a)=>{let o=typeof a=="string"?a:a.source;return o=o.replace(xe.caret,"$1"),r=r.replace(n,o),i},getRegex:()=>new RegExp(r,t)};return i}var PT=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),xe={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:_n(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:_n(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:_n(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:_n(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:_n(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:_n(e=>new RegExp(`^ {0,${e}}>`))},_T=/^(?:[ \t]*(?:\n|$))+/,AT=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,IT=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,ho=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,TT=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,of=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,rN=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,iN=M(rN).replace(/bull/g,of).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),jT=M(rN).replace(/bull/g,of).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),sf=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,$T=/^[^\n]+/,cf=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,OT=M(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",cf).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),HT=M(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,of).getRegex(),Xc="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",lf=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,DT=M("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",lf).replace("tag",Xc).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),nN=e=>M(sf).replace("hr",ho).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",e).replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Xc).getRegex(),BT=nN(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),FT=nN(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),LT=M(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",FT).getRegex(),uf={blockquote:LT,code:AT,def:OT,fences:IT,heading:TT,hr:ho,html:DT,lheading:iN,list:HT,newline:_T,paragraph:BT,table:Si,text:$T},Uy=M("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",ho).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Xc).getRegex(),qT={...uf,lheading:jT,table:Uy,paragraph:M(sf).replace("hr",ho).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Uy).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Xc).getRegex()},MT={...uf,html:M(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",lf).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Si,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:M(sf).replace("hr",ho).replace("heading",` *#{1,6} *[^
192
+ ]`).replace("lheading",iN).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},VT=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,WT=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,aN=/^( {2,}|\\)\n(?!\s*$)/,zT=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,cr=/[\p{P}\p{S}]/u,An=/[\s\p{P}\p{S}]/u,mo=/[^\s\p{P}\p{S}]/u,GT=M(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,An).getRegex(),JT=/[\p{Pi}\p{Ps}"']/u,oN=/(?!~)[\p{P}\p{S}]/u,UT=/(?!~)[\s\p{P}\p{S}]/u,KT=/(?:[^\s\p{P}\p{S}]|~)/u,YT=M(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",PT?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),sN=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,XT=M(sN,"u").replace(/punct/g,cr).getRegex(),QT=M(sN,"u").replace(/punct/g,oN).getRegex(),ZT=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,ej=M(ZT,"u").replace(/openQuote/g,JT).replace(/punct/g,cr).getRegex(),cN="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",tj=M(cN,"gu").replace(/notPunctSpace/g,mo).replace(/punctSpace/g,An).replace(/punct/g,cr).getRegex(),rj=M(cN,"gu").replace(/notPunctSpace/g,KT).replace(/punctSpace/g,UT).replace(/punct/g,oN).getRegex(),ij="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",nj=M(ij,"gu").replace(/notPunctSpace/g,mo).replace(/punctSpace/g,An).replace(/punct/g,cr).getRegex(),aj=M("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,mo).replace(/punctSpace/g,An).replace(/punct/g,cr).getRegex(),oj="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",sj=M(oj,"gu").replace(/notPunctSpace/g,mo).replace(/punctSpace/g,An).replace(/punct/g,cr).getRegex(),cj=M(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,cr).getRegex(),lj="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",uj=M(lj,"gu").replace(/notPunctSpace/g,mo).replace(/punctSpace/g,An).replace(/punct/g,cr).getRegex(),dj=M(/\\(punct)/,"gu").replace(/punct/g,cr).getRegex(),pj=M(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),fj=M(lf).replace("(?:-->|$)","-->").getRegex(),hj=M("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",fj).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Uc=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,mj=M(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",Uc).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),lN=M(/^!?\[(label)\]\[(ref)\]/).replace("label",Uc).replace("ref",cf).getRegex(),uN=M(/^!?\[(ref)\](?:\[\])?/).replace("ref",cf).getRegex(),vj=M("reflink|nolink(?!\\()","g").replace("reflink",lN).replace("nolink",uN).getRegex(),Ky=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,df={_backpedal:Si,anyPunctuation:dj,autolink:pj,blockSkip:YT,br:aN,code:WT,del:Si,delLDelim:Si,delRDelim:Si,emStrongLDelim:XT,emStrongRDelimAst:tj,emStrongRDelimUnd:aj,escape:VT,link:mj,nolink:uN,punctuation:GT,reflink:lN,reflinkSearch:vj,tag:hj,text:zT,url:Si},gj={...df,emStrongLDelim:ej,emStrongRDelimAst:nj,emStrongRDelimUnd:sj,link:M(/^!?\[(label)\]\((.*?)\)/).replace("label",Uc).getRegex(),reflink:M(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Uc).getRegex()},tf={...df,emStrongRDelimAst:rj,emStrongLDelim:QT,delLDelim:cj,delRDelim:uj,url:M(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Ky).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:M(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Ky).getRegex()},wj={...tf,br:M(aN).replace("{2,}","*").getRegex(),text:M(tf.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Jc={normal:uf,gfm:qT,pedantic:MT},po={normal:df,gfm:tf,breaks:wj,pedantic:gj},yj={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Yy=e=>yj[e];function Mt(e,t){if(t){if(xe.escapeTest.test(e))return e.replace(xe.escapeReplace,Yy)}else if(xe.escapeTestNoEncode.test(e))return e.replace(xe.escapeReplaceNoEncode,Yy);return e}function Xy(e){try{e=encodeURI(e).replace(xe.percentDecode,"%")}catch{return null}return e}function Qy(e,t){let r=e.replace(xe.findPipe,(a,o,s)=>{let c=!1,l=o;for(;--l>=0&&s[l]==="\\";)c=!c;return c?"|":" |"}),i=r.split(xe.splitPipe),n=0;if(i[0].trim()||i.shift(),i.length>0&&!i.at(-1)?.trim()&&i.pop(),t)if(i.length>t)i.splice(t);else for(;i.length<t;)i.push("");for(;n<i.length;n++)i[n]=i[n].trim().replace(xe.slashPipe,"|");return i}function zr(e,t,r){let i=e.length;if(i===0)return"";let n=0;for(;n<i;){let a=e.charAt(i-n-1);if(a===t&&!r)n++;else if(a!==t&&r)n++;else break}return e.slice(0,i-n)}function Zy(e){let t=e.split(`
186
193
  `),r=t.length-1;for(;r>=0&&xe.blankLine.test(t[r]);)r--;return t.length-r<=2?e:t.slice(0,r+1).join(`
187
- `)}function sj(e,t){if(e.indexOf(t[1])===-1)return-1;let r=0;for(let i=0;i<e.length;i++)if(e[i]==="\\")i++;else if(e[i]===t[0])r++;else if(e[i]===t[1]&&(r--,r<0))return i;return r>0?-2:-1}function cj(e,t=0){let r=t,i="";for(let n of e)if(n===" "){let a=4-r%4;i+=" ".repeat(a),r+=a}else i+=n,r++;return i}function Vy(e,t,r,i,n){let a=t.href,o=t.title||null,s=e[1].replace(n.other.outputLinkReplace,"$1"),c=e[0].charAt(0)==="!";i.state.inLink=!0;let l=i.state.linkEmitted,u=i.state.inRawBlock;i.state.linkEmitted=!1;let d=i.inlineTokens(s),p=i.state.linkEmitted;if(i.state.linkEmitted=l,i.state.inLink=!1,!c){if(p){i.state.inRawBlock=u;return}i.state.linkEmitted=!0}return{type:c?"image":"link",raw:r,href:a,title:o,text:s,tokens:d}}function lj(e,t,r){let i=e.match(r.other.indentCodeCompensation);if(i===null)return t;let n=i[1];return t.split(`
194
+ `)}function Nj(e,t){if(e.indexOf(t[1])===-1)return-1;let r=0;for(let i=0;i<e.length;i++)if(e[i]==="\\")i++;else if(e[i]===t[0])r++;else if(e[i]===t[1]&&(r--,r<0))return i;return r>0?-2:-1}function bj(e,t=0){let r=t,i="";for(let n of e)if(n===" "){let a=4-r%4;i+=" ".repeat(a),r+=a}else i+=n,r++;return i}function eN(e,t,r,i,n){let a=t.href,o=t.title||null,s=e[1].replace(n.other.outputLinkReplace,"$1"),c=e[0].charAt(0)==="!";i.state.inLink=!0;let l=i.state.linkEmitted,u=i.state.inRawBlock;i.state.linkEmitted=!1;let d=i.inlineTokens(s),p=i.state.linkEmitted;if(i.state.linkEmitted=l,i.state.inLink=!1,!c){if(p){i.state.inRawBlock=u;return}i.state.linkEmitted=!0}return{type:c?"image":"link",raw:r,href:a,title:o,text:s,tokens:d}}function kj(e,t,r){let i=e.match(r.other.indentCodeCompensation);if(i===null)return t;let n=i[1];return t.split(`
188
195
  `).map(a=>{let o=a.match(r.other.beginningSpace);if(o===null)return a;let[s]=o;return s.length>=n.length?a.slice(n.length):a}).join(`
189
- `)}var Gc=class{options;rules;lexer;constructor(e){this.options=e||Ei}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let r=this.options.pedantic?t[0]:My(t[0]),i=r.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:r,codeBlockStyle:"indented",text:i}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let r=t[0],i=lj(r,t[3]||"",this.rules);return{type:"code",raw:r,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:i}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let r=t[2].trim();if(this.rules.other.endingHash.test(r)){let i=zr(r,"#");(this.options.pedantic||!i||this.rules.other.endingSpaceChar.test(i))&&(r=i.trim())}return{type:"heading",raw:zr(t[0],`
196
+ `)}var Kc=class{options;rules;lexer;constructor(e){this.options=e||xi}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let r=this.options.pedantic?t[0]:Zy(t[0]),i=r.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:r,codeBlockStyle:"indented",text:i}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let r=t[0],i=kj(r,t[3]||"",this.rules);return{type:"code",raw:r,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:i}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let r=t[2].trim();if(this.rules.other.endingHash.test(r)){let i=zr(r,"#");(this.options.pedantic||!i||this.rules.other.endingSpaceChar.test(i))&&(r=i.trim())}return{type:"heading",raw:zr(t[0],`
190
197
  `),depth:t[1].length,text:r,tokens:this.lexer.inline(r)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:zr(t[0],`
191
198
  `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let r=zr(t[0],`
192
199
  `).split(`
@@ -200,19 +207,19 @@ ${u}`:u;let d=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
200
207
  ${m}`,n=n.substring(0,n.length-f.text.length)+v.text;break}else if(p?.type==="list"){let f=p,m=f.raw+`
201
208
  `+r.join(`
202
209
  `),h=this.list(m);a[a.length-1]=h,i=i.substring(0,i.length-p.raw.length)+h.raw,n=n.substring(0,n.length-f.raw.length)+h.raw,r=m.substring(a.at(-1).raw.length).split(`
203
- `);continue}}return{type:"blockquote",raw:i,tokens:a,text:n}}}list(e){let t=this.rules.block.list.exec(e);if(t){let r=t[1].trim(),i=r.length>1,n={type:"list",raw:"",ordered:i,start:i?+r.slice(0,-1):"",loose:!1,items:[]};r=i?`\\d{1,9}\\${r.slice(-1)}`:`\\${r}`,this.options.pedantic&&(r=i?r:"[*+-]");let a=this.rules.other.listItemRegex(r),o=!1;for(;e;){let c=!1,l="",u="";if(!(t=a.exec(e))||this.rules.block.hr.test(e))break;l=t[0],e=e.substring(l.length);let d=cj(t[2].split(`
210
+ `);continue}}return{type:"blockquote",raw:i,tokens:a,text:n}}}list(e){let t=this.rules.block.list.exec(e);if(t){let r=t[1].trim(),i=r.length>1,n={type:"list",raw:"",ordered:i,start:i?+r.slice(0,-1):"",loose:!1,items:[]};r=i?`\\d{1,9}\\${r.slice(-1)}`:`\\${r}`,this.options.pedantic&&(r=i?r:"[*+-]");let a=this.rules.other.listItemRegex(r),o=!1;for(;e;){let c=!1,l="",u="";if(!(t=a.exec(e))||this.rules.block.hr.test(e))break;l=t[0],e=e.substring(l.length);let d=bj(t[2].split(`
204
211
  `,1)[0],t[1].length),p=e.split(`
205
212
  `,1)[0],f=!d.trim(),m=0;if(this.options.pedantic?(m=2,u=d.trimStart()):f?m=t[1].length+1:(m=d.search(this.rules.other.nonSpaceChar),m=m>4?1:m,u=d.slice(m),m+=t[1].length),f&&this.rules.other.blankLine.test(p)&&(l+=p+`
206
213
  `,e=e.substring(p.length+1),c=!0),!c){let h=this.rules.other.nextBulletRegex(m),v=this.rules.other.hrRegex(m),g=this.rules.other.fencesBeginRegex(m),b=this.rules.other.headingBeginRegex(m),k=this.rules.other.htmlBeginRegex(m),N=this.rules.other.blockquoteBeginRegex(m);for(;e;){let x=e.split(`
207
214
  `,1)[0],w;if(p=x,this.options.pedantic?(p=p.replace(this.rules.other.listReplaceNesting," "),w=p):w=p.replace(this.rules.other.tabCharGlobal," "),g.test(p)||b.test(p)||k.test(p)||N.test(p)||h.test(p)||v.test(p))break;if(w.search(this.rules.other.nonSpaceChar)>=m||!p.trim())u+=`
208
215
  `+w.slice(m);else{if(f||d.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||g.test(d)||b.test(d)||v.test(d))break;u+=`
209
216
  `+p}f=!p.trim(),l+=x+`
210
- `,e=e.substring(x.length+1),d=w.slice(m)}}n.loose||(o?n.loose=!0:this.rules.other.doubleBlankLine.test(l)&&(o=!0)),n.items.push({type:"list_item",raw:l,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),n.raw+=l}let s=n.items.at(-1);if(s)s.raw=s.raw.trimEnd(),s.text=s.text.trimEnd();else return;n.raw=n.raw.trimEnd();for(let c of n.items)if(this.lexer.state.top=!1,c.tokens=this.lexer.blockTokens(c.text,[]),!n.loose){let l=c.tokens.filter(d=>d.type==="space"),u=l.length>0&&l.some(d=>this.rules.other.anyLine.test(d.raw));n.loose=u}for(let c of n.items){let l=c.tokens[0];if(c.task&&(l?.type==="text"||l?.type==="paragraph")){c.text=c.text.replace(this.rules.other.listReplaceTask,""),l.raw=l.raw.replace(this.rules.other.listReplaceTask,""),l.text=l.text.replace(this.rules.other.listReplaceTask,"");for(let d=this.lexer.inlineQueue.length-1;d>=0;d--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[d].src)){this.lexer.inlineQueue[d].src=this.lexer.inlineQueue[d].src.replace(this.rules.other.listReplaceTask,"");break}let u=this.rules.other.listTaskCheckbox.exec(c.raw);if(u){let d={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};c.checked=d.checked,n.loose?c.tokens[0]&&["paragraph","text"].includes(c.tokens[0].type)&&"tokens"in c.tokens[0]&&c.tokens[0].tokens?(c.tokens[0].raw=d.raw+c.tokens[0].raw,c.tokens[0].text=d.raw+c.tokens[0].text,c.tokens[0].tokens.unshift(d)):c.tokens.unshift({type:"paragraph",raw:d.raw,text:d.raw,tokens:[d]}):c.tokens.unshift(d)}}else c.task&&(c.task=!1)}if(n.loose)for(let c of n.items){c.loose=!0;for(let l of c.tokens)l.type==="text"&&(l.type="paragraph")}return n}}html(e){let t=this.rules.block.html.exec(e);if(t){let r=My(t[0]);return{type:"html",block:!0,raw:r,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:r}}}def(e){let t=this.rules.block.def.exec(e);if(t){let r=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),i=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",n=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:r,raw:zr(t[0],`
211
- `),href:i,title:n}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let r=qy(t[1]),i=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),n=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
217
+ `,e=e.substring(x.length+1),d=w.slice(m)}}n.loose||(o?n.loose=!0:this.rules.other.doubleBlankLine.test(l)&&(o=!0)),n.items.push({type:"list_item",raw:l,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),n.raw+=l}let s=n.items.at(-1);if(s)s.raw=s.raw.trimEnd(),s.text=s.text.trimEnd();else return;n.raw=n.raw.trimEnd();for(let c of n.items)if(this.lexer.state.top=!1,c.tokens=this.lexer.blockTokens(c.text,[]),!n.loose){let l=c.tokens.filter(d=>d.type==="space"),u=l.length>0&&l.some(d=>this.rules.other.anyLine.test(d.raw));n.loose=u}for(let c of n.items){let l=c.tokens[0];if(c.task&&(l?.type==="text"||l?.type==="paragraph")){c.text=c.text.replace(this.rules.other.listReplaceTask,""),l.raw=l.raw.replace(this.rules.other.listReplaceTask,""),l.text=l.text.replace(this.rules.other.listReplaceTask,"");for(let d=this.lexer.inlineQueue.length-1;d>=0;d--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[d].src)){this.lexer.inlineQueue[d].src=this.lexer.inlineQueue[d].src.replace(this.rules.other.listReplaceTask,"");break}let u=this.rules.other.listTaskCheckbox.exec(c.raw);if(u){let d={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};c.checked=d.checked,n.loose?c.tokens[0]&&["paragraph","text"].includes(c.tokens[0].type)&&"tokens"in c.tokens[0]&&c.tokens[0].tokens?(c.tokens[0].raw=d.raw+c.tokens[0].raw,c.tokens[0].text=d.raw+c.tokens[0].text,c.tokens[0].tokens.unshift(d)):c.tokens.unshift({type:"paragraph",raw:d.raw,text:d.raw,tokens:[d]}):c.tokens.unshift(d)}}else c.task&&(c.task=!1)}if(n.loose)for(let c of n.items){c.loose=!0;for(let l of c.tokens)l.type==="text"&&(l.type="paragraph")}return n}}html(e){let t=this.rules.block.html.exec(e);if(t){let r=Zy(t[0]);return{type:"html",block:!0,raw:r,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:r}}}def(e){let t=this.rules.block.def.exec(e);if(t){let r=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),i=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",n=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:r,raw:zr(t[0],`
218
+ `),href:i,title:n}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let r=Qy(t[1]),i=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),n=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
212
219
  `):[],a={type:"table",raw:zr(t[0],`
213
- `),header:[],align:[],rows:[]};if(r.length===i.length){for(let o of i)this.rules.other.tableAlignRight.test(o)?a.align.push("right"):this.rules.other.tableAlignCenter.test(o)?a.align.push("center"):this.rules.other.tableAlignLeft.test(o)?a.align.push("left"):a.align.push(null);for(let o=0;o<r.length;o++)a.header.push({text:r[o],tokens:this.lexer.inline(r[o]),header:!0,align:a.align[o]});for(let o of n)a.rows.push(qy(o,a.header.length).map((s,c)=>({text:s,tokens:this.lexer.inline(s),header:!1,align:a.align[c]})));return a}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let r=t[1].trim();return{type:"heading",raw:zr(t[0],`
220
+ `),header:[],align:[],rows:[]};if(r.length===i.length){for(let o of i)this.rules.other.tableAlignRight.test(o)?a.align.push("right"):this.rules.other.tableAlignCenter.test(o)?a.align.push("center"):this.rules.other.tableAlignLeft.test(o)?a.align.push("left"):a.align.push(null);for(let o=0;o<r.length;o++)a.header.push({text:r[o],tokens:this.lexer.inline(r[o]),header:!0,align:a.align[o]});for(let o of n)a.rows.push(Qy(o,a.header.length).map((s,c)=>({text:s,tokens:this.lexer.inline(s),header:!1,align:a.align[c]})));return a}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let r=t[1].trim();return{type:"heading",raw:zr(t[0],`
214
221
  `),depth:t[2].charAt(0)==="="?1:2,text:r,tokens:this.lexer.inline(r)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let r=t[1].charAt(t[1].length-1)===`
215
- `?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:r,tokens:this.lexer.inline(r)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let r=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(r)){if(!this.rules.other.endAngleBracket.test(r))return;let a=zr(r.slice(0,-1),"\\");if((r.length-a.length)%2===0)return}else{let a=sj(t[2],"()");if(a===-2)return;if(a>-1){let o=(t[0].indexOf("!")===0?5:4)+t[1].length+a;t[2]=t[2].substring(0,a),t[0]=t[0].substring(0,o).trim(),t[3]=""}}let i=t[2],n="";if(this.options.pedantic){let a=this.rules.other.pedanticHrefTitle.exec(i);a&&(i=a[1],n=a[3])}else n=t[3]?t[3].slice(1,-1):"";return i=i.trim(),this.rules.other.startAngleBracket.test(i)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(r)?i=i.slice(1):i=i.slice(1,-1)),Vy(t,{href:i&&i.replace(this.rules.inline.anyPunctuation,"$1"),title:n&&n.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let r;if((r=this.rules.inline.reflink.exec(e))||(r=this.rules.inline.nolink.exec(e))){let i=(r[2]||r[1]).replace(this.rules.other.multipleSpaceGlobal," "),n=t[i.toLowerCase()];if(!n){let a=r[0].charAt(0);return{type:"text",raw:a,text:a}}return Vy(r,n,r[0],this.lexer,this.rules)}}emStrong(e,t,r=""){let i=this.rules.inline.emStrongLDelim.exec(e);if(!(!i||!i[1]&&!i[2]&&!i[3]&&!i[4]||i[4]&&r.match(this.rules.other.unicodeAlphaNumeric))&&(!(i[1]||i[3])||!r||this.rules.inline.punctuation.exec(r))){let n=[...i[0]].length-1,a,o,s=n,c=0,l=i[0][0],u=r===l,d=l==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(d.lastIndex=0,t=t.slice(-1*e.length+n);(i=d.exec(t))!==null;){if(a=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!a)continue;if(o=[...a].length,i[3]||i[4]){s+=o;continue}else if(i[5]||i[6]){if(n%3&&!((n+o)%3)){c+=o;continue}if(u)break}if(s-=o,s>0)continue;o=Math.min(o,o+s+c);let p=[...i[0]][0].length,f=e.slice(0,n+i.index+p+o);if(Math.min(n,o)%2){let h=f.slice(1,-1);return{type:"em",raw:f,text:h,tokens:this.lexer.inlineTokens(h)}}let m=f.slice(2,-2);return{type:"strong",raw:f,text:m,tokens:this.lexer.inlineTokens(m)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let r=t[2].replace(this.rules.other.newLineCharGlobal," "),i=this.rules.other.nonSpaceChar.test(r),n=this.rules.other.startingSpaceChar.test(r)&&this.rules.other.endingSpaceChar.test(r);return i&&n&&(r=r.substring(1,r.length-1)),{type:"codespan",raw:t[0],text:r}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,r=""){let i=this.rules.inline.delLDelim.exec(e);if(i&&(!i[1]||!r||this.rules.inline.punctuation.exec(r))){let n=[...i[0]].length-1,a,o,s=n,c=this.rules.inline.delRDelim;for(c.lastIndex=0,t=t.slice(-1*e.length+n);(i=c.exec(t))!==null;){if(a=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!a||(o=[...a].length,o!==n))continue;if(i[3]||i[4]){s+=o;continue}if(s-=o,s>0)continue;o=Math.min(o,o+s);let l=[...i[0]][0].length,u=e.slice(0,n+i.index+l+o),d=u.slice(n,-n);return{type:"del",raw:u,text:d,tokens:this.lexer.inlineTokens(d)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let r,i;return t[2]==="@"?(r=t[1],i="mailto:"+r):(r=t[1],i=r),{type:"link",raw:t[0],text:r,href:i,tokens:[{type:"text",raw:r,text:r}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let r,i;if(t[2]==="@")r=t[0],i="mailto:"+r;else{let n;do n=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(n!==t[0]);r=t[0],t[1]==="www."?i="http://"+t[0]:i=t[0]}return{type:"link",raw:t[0],text:r,href:i,tokens:[{type:"text",raw:r,text:r}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let r=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:r}}}},st=class Qp{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Ei,this.options.tokenizer=this.options.tokenizer||new Gc,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,linkEmitted:!1,top:!0};let r={other:xe,block:Wc.normal,inline:lo.normal};this.options.pedantic?(r.block=Wc.pedantic,r.inline=lo.pedantic):this.options.gfm&&(r.block=Wc.gfm,this.options.breaks?r.inline=lo.breaks:r.inline=lo.gfm),this.tokenizer.rules=r}static get rules(){return{block:Wc,inline:lo}}static lex(t,r){return new Qp(r).lex(t)}static lexInline(t,r){return new Qp(r).inlineTokens(t)}lex(t){t=t.replace(xe.carriageReturn,`
222
+ `?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:r,tokens:this.lexer.inline(r)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let r=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(r)){if(!this.rules.other.endAngleBracket.test(r))return;let a=zr(r.slice(0,-1),"\\");if((r.length-a.length)%2===0)return}else{let a=Nj(t[2],"()");if(a===-2)return;if(a>-1){let o=(t[0].indexOf("!")===0?5:4)+t[1].length+a;t[2]=t[2].substring(0,a),t[0]=t[0].substring(0,o).trim(),t[3]=""}}let i=t[2],n="";if(this.options.pedantic){let a=this.rules.other.pedanticHrefTitle.exec(i);a&&(i=a[1],n=a[3])}else n=t[3]?t[3].slice(1,-1):"";return i=i.trim(),this.rules.other.startAngleBracket.test(i)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(r)?i=i.slice(1):i=i.slice(1,-1)),eN(t,{href:i&&i.replace(this.rules.inline.anyPunctuation,"$1"),title:n&&n.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let r;if((r=this.rules.inline.reflink.exec(e))||(r=this.rules.inline.nolink.exec(e))){let i=(r[2]||r[1]).replace(this.rules.other.multipleSpaceGlobal," "),n=t[i.toLowerCase()];if(!n){let a=r[0].charAt(0);return{type:"text",raw:a,text:a}}return eN(r,n,r[0],this.lexer,this.rules)}}emStrong(e,t,r=""){let i=this.rules.inline.emStrongLDelim.exec(e);if(!(!i||!i[1]&&!i[2]&&!i[3]&&!i[4]||i[4]&&r.match(this.rules.other.unicodeAlphaNumeric))&&(!(i[1]||i[3])||!r||this.rules.inline.punctuation.exec(r))){let n=[...i[0]].length-1,a,o,s=n,c=0,l=i[0][0],u=r===l,d=l==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(d.lastIndex=0,t=t.slice(-1*e.length+n);(i=d.exec(t))!==null;){if(a=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!a)continue;if(o=[...a].length,i[3]||i[4]){s+=o;continue}else if(i[5]||i[6]){if(n%3&&!((n+o)%3)){c+=o;continue}if(u)break}if(s-=o,s>0)continue;o=Math.min(o,o+s+c);let p=[...i[0]][0].length,f=e.slice(0,n+i.index+p+o);if(Math.min(n,o)%2){let h=f.slice(1,-1);return{type:"em",raw:f,text:h,tokens:this.lexer.inlineTokens(h)}}let m=f.slice(2,-2);return{type:"strong",raw:f,text:m,tokens:this.lexer.inlineTokens(m)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let r=t[2].replace(this.rules.other.newLineCharGlobal," "),i=this.rules.other.nonSpaceChar.test(r),n=this.rules.other.startingSpaceChar.test(r)&&this.rules.other.endingSpaceChar.test(r);return i&&n&&(r=r.substring(1,r.length-1)),{type:"codespan",raw:t[0],text:r}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,r=""){let i=this.rules.inline.delLDelim.exec(e);if(i&&(!i[1]||!r||this.rules.inline.punctuation.exec(r))){let n=[...i[0]].length-1,a,o,s=n,c=this.rules.inline.delRDelim;for(c.lastIndex=0,t=t.slice(-1*e.length+n);(i=c.exec(t))!==null;){if(a=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!a||(o=[...a].length,o!==n))continue;if(i[3]||i[4]){s+=o;continue}if(s-=o,s>0)continue;o=Math.min(o,o+s);let l=[...i[0]][0].length,u=e.slice(0,n+i.index+l+o),d=u.slice(n,-n);return{type:"del",raw:u,text:d,tokens:this.lexer.inlineTokens(d)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let r,i;return t[2]==="@"?(r=t[1],i="mailto:"+r):(r=t[1],i=r),{type:"link",raw:t[0],text:r,href:i,tokens:[{type:"text",raw:r,text:r}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let r,i;if(t[2]==="@")r=t[0],i="mailto:"+r;else{let n;do n=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(n!==t[0]);r=t[0],t[1]==="www."?i="http://"+t[0]:i=t[0]}return{type:"link",raw:t[0],text:r,href:i,tokens:[{type:"text",raw:r,text:r}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let r=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:r}}}},st=class rf{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||xi,this.options.tokenizer=this.options.tokenizer||new Kc,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,linkEmitted:!1,top:!0};let r={other:xe,block:Jc.normal,inline:po.normal};this.options.pedantic?(r.block=Jc.pedantic,r.inline=po.pedantic):this.options.gfm&&(r.block=Jc.gfm,this.options.breaks?r.inline=po.breaks:r.inline=po.gfm),this.tokenizer.rules=r}static get rules(){return{block:Jc,inline:po}}static lex(t,r){return new rf(r).lex(t)}static lexInline(t,r){return new rf(r).inlineTokens(t)}lex(t){t=t.replace(xe.carriageReturn,`
216
223
  `),this.blockTokens(t,this.tokens);for(let r=0;r<this.inlineQueue.length;r++){let i=this.inlineQueue[r];this.inlineTokens(i.src,i.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(t,r=[],i=!1){this.tokenizer.lexer=this,this.options.pedantic&&(t=t.replace(xe.tabCharGlobal," ").replace(xe.spaceLine,""));let n=1/0;for(;t;){if(t.length<n)n=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}let a;if(this.options.extensions?.block?.some(s=>(a=s.call({lexer:this},t,r))?(t=t.substring(a.raw.length),r.push(a),!0):!1))continue;if(a=this.tokenizer.space(t)){t=t.substring(a.raw.length);let s=r.at(-1);a.raw.length===1&&s!==void 0?s.raw+=`
217
224
  `:r.push(a);continue}if(a=this.tokenizer.code(t)){t=t.substring(a.raw.length);let s=r.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(`
218
225
  `)?"":`
@@ -226,7 +233,7 @@ ${m}`,n=n.substring(0,n.length-f.text.length)+v.text;break}else if(p?.type==="li
226
233
  `+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):r.push(a),i=o.length!==t.length,t=t.substring(a.raw.length);continue}if(a=this.tokenizer.text(t)){t=t.substring(a.raw.length);let s=r.at(-1);s?.type==="text"?(s.raw+=(s.raw.endsWith(`
227
234
  `)?"":`
228
235
  `)+a.raw,s.text+=`
229
- `+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):r.push(a);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,r}inline(t,r=[]){return this.inlineQueue.push({src:t,tokens:r}),r}linkInText(t){if(!t.includes("["))return!1;let r=this.tokenizer.rules.inline.link;for(let i of t.matchAll(this.tokenizer.rules.inline.blockSkip))if(r.test(i[0])&&t.charAt(i.index-1)!=="!")return!0;for(let i of t.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let n=i[0],a=n.lastIndexOf("[");if(!(n.charAt(0)==="!"||!Object.hasOwn(this.tokens.links,n.slice(a+1,-1)))&&!(a>1&&this.linkInText(n.slice(1,a-1))))return!0}return!1}inlineTokens(t,r=[]){this.tokenizer.lexer=this;let i=t;if(this.tokens.links&&t.includes("[")){let s=this.tokenizer.rules.inline.reflinkSearch,c=l=>{let u=l.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,l.slice(u+1,-1)))return l;if(u>1&&l.charAt(0)!=="!"){let d=l.slice(1,u-1);if(this.linkInText(d))return"["+d.replace(s,c)+"]["+"a".repeat(l.length-u-2)+"]"}return"["+"a".repeat(l.length-2)+"]"};i=i.replace(s,c)}i=i.replace(this.tokenizer.rules.inline.anyPunctuation,s=>"+".repeat(s.length)),i=i.replace(this.tokenizer.rules.inline.blockSkip,(s,c,l)=>{let u=l?l.length:0;return s.slice(0,u)+"["+"a".repeat(s.length-u-2)+"]"}),i=this.options.hooks?.emStrongMask?.call({lexer:this},i)??i;let n=!1,a="",o=1/0;for(;t;){if(t.length<o)o=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}n||(a=""),n=!1;let s;if(this.options.extensions?.inline?.some(l=>(s=l.call({lexer:this},t,r))?(t=t.substring(s.raw.length),r.push(s),!0):!1))continue;if(s=this.tokenizer.escape(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.tag(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.link(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(s.raw.length);let l=r.at(-1);s.type==="text"&&l?.type==="text"?(l.raw+=s.raw,l.text+=s.text):r.push(s);continue}if(s=this.tokenizer.emStrong(t,i,a)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.codespan(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.br(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.del(t,i,a)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.autolink(t)){t=t.substring(s.raw.length),r.push(s);continue}if(!this.state.inLink&&(s=this.tokenizer.url(t))){t=t.substring(s.raw.length),r.push(s);continue}let c=t;if(this.options.extensions?.startInline){let l=1/0,u=t.slice(1),d;this.options.extensions.startInline.forEach(p=>{d=p.call({lexer:this},u),typeof d=="number"&&d>=0&&(l=Math.min(l,d))}),l<1/0&&l>=0&&(c=t.substring(0,l+1))}if(s=this.tokenizer.inlineText(c)){t=t.substring(s.raw.length),s.raw.slice(-1)!=="_"&&(a=s.raw.slice(-1)),n=!0;let l=r.at(-1);l?.type==="text"?(l.raw+=s.raw,l.text+=s.text):r.push(s);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return r}infiniteLoopError(t){let r="Infinite loop on byte: "+t;if(this.options.silent)console.error(r);else throw new Error(r)}},Jc=class{options;parser;constructor(e){this.options=e||Ei}space(e){return""}code({text:e,lang:t,escaped:r}){let i=(t||"").match(xe.notSpaceStart)?.[0],n=e.replace(xe.endingNewline,"")+`
236
+ `+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):r.push(a);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,r}inline(t,r=[]){return this.inlineQueue.push({src:t,tokens:r}),r}linkInText(t){if(!t.includes("["))return!1;let r=this.tokenizer.rules.inline.link;for(let i of t.matchAll(this.tokenizer.rules.inline.blockSkip))if(r.test(i[0])&&t.charAt(i.index-1)!=="!")return!0;for(let i of t.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let n=i[0],a=n.lastIndexOf("[");if(!(n.charAt(0)==="!"||!Object.hasOwn(this.tokens.links,n.slice(a+1,-1)))&&!(a>1&&this.linkInText(n.slice(1,a-1))))return!0}return!1}inlineTokens(t,r=[]){this.tokenizer.lexer=this;let i=t;if(this.tokens.links&&t.includes("[")){let s=this.tokenizer.rules.inline.reflinkSearch,c=l=>{let u=l.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,l.slice(u+1,-1)))return l;if(u>1&&l.charAt(0)!=="!"){let d=l.slice(1,u-1);if(this.linkInText(d))return"["+d.replace(s,c)+"]["+"a".repeat(l.length-u-2)+"]"}return"["+"a".repeat(l.length-2)+"]"};i=i.replace(s,c)}i=i.replace(this.tokenizer.rules.inline.anyPunctuation,s=>"+".repeat(s.length)),i=i.replace(this.tokenizer.rules.inline.blockSkip,(s,c,l)=>{let u=l?l.length:0;return s.slice(0,u)+"["+"a".repeat(s.length-u-2)+"]"}),i=this.options.hooks?.emStrongMask?.call({lexer:this},i)??i;let n=!1,a="",o=1/0;for(;t;){if(t.length<o)o=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}n||(a=""),n=!1;let s;if(this.options.extensions?.inline?.some(l=>(s=l.call({lexer:this},t,r))?(t=t.substring(s.raw.length),r.push(s),!0):!1))continue;if(s=this.tokenizer.escape(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.tag(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.link(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(s.raw.length);let l=r.at(-1);s.type==="text"&&l?.type==="text"?(l.raw+=s.raw,l.text+=s.text):r.push(s);continue}if(s=this.tokenizer.emStrong(t,i,a)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.codespan(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.br(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.del(t,i,a)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.autolink(t)){t=t.substring(s.raw.length),r.push(s);continue}if(!this.state.inLink&&(s=this.tokenizer.url(t))){t=t.substring(s.raw.length),r.push(s);continue}let c=t;if(this.options.extensions?.startInline){let l=1/0,u=t.slice(1),d;this.options.extensions.startInline.forEach(p=>{d=p.call({lexer:this},u),typeof d=="number"&&d>=0&&(l=Math.min(l,d))}),l<1/0&&l>=0&&(c=t.substring(0,l+1))}if(s=this.tokenizer.inlineText(c)){t=t.substring(s.raw.length),s.raw.slice(-1)!=="_"&&(a=s.raw.slice(-1)),n=!0;let l=r.at(-1);l?.type==="text"?(l.raw+=s.raw,l.text+=s.text):r.push(s);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return r}infiniteLoopError(t){let r="Infinite loop on byte: "+t;if(this.options.silent)console.error(r);else throw new Error(r)}},Yc=class{options;parser;constructor(e){this.options=e||xi}space(e){return""}code({text:e,lang:t,escaped:r}){let i=(t||"").match(xe.notSpaceStart)?.[0],n=e.replace(xe.endingNewline,"")+`
230
237
  `;return i?'<pre><code class="language-'+Mt(i)+'">'+(r?n:Mt(n,!0))+`</code></pre>
231
238
  `:"<pre><code>"+(r?n:Mt(n,!0))+`</code></pre>
232
239
  `}blockquote({tokens:e}){return`<blockquote>
@@ -244,27 +251,27 @@ ${this.parser.parse(e)}</blockquote>
244
251
  `}tablerow({text:e}){return`<tr>
245
252
  ${e}</tr>
246
253
  `}tablecell(e){let t=this.parser.parseInline(e.tokens),r=e.header?"th":"td";return(e.align?`<${r} align="${e.align}">`:`<${r}>`)+t+`</${r}>
247
- `}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${Mt(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:r}){let i=this.parser.parseInline(r),n=Ly(e);if(n===null)return i;e=n;let a='<a href="'+e+'"';return t&&(a+=' title="'+Mt(t)+'"'),a+=">"+i+"</a>",a}image({href:e,title:t,text:r,tokens:i}){i&&(r=this.parser.parseInline(i,this.parser.textRenderer));let n=Ly(e);if(n===null)return Mt(r);e=n;let a=`<img src="${e}" alt="${Mt(r)}"`;return t&&(a+=` title="${Mt(t)}"`),a+=">",a}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:Mt(e.text)}},cf=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},Et=class Zp{options;renderer;textRenderer;constructor(t){this.options=t||Ei,this.options.renderer=this.options.renderer||new Jc,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new cf}static parse(t,r){return new Zp(r).parse(t)}static parseInline(t,r){return new Zp(r).parseInline(t)}parse(t){this.renderer.parser=this;let r="";for(let i=0;i<t.length;i++){let n=t[i];if(this.options.extensions?.renderers?.[n.type]){let o=n,s=this.options.extensions.renderers[o.type].call({parser:this},o);if(s!==!1||!["space","hr","heading","code","table","blockquote","list","checkbox","html","def","paragraph","text"].includes(o.type)){r+=s||"";continue}}let a=n;switch(a.type){case"space":{r+=this.renderer.space(a);break}case"hr":{r+=this.renderer.hr(a);break}case"heading":{r+=this.renderer.heading(a);break}case"code":{r+=this.renderer.code(a);break}case"table":{r+=this.renderer.table(a);break}case"blockquote":{r+=this.renderer.blockquote(a);break}case"list":{r+=this.renderer.list(a);break}case"checkbox":{r+=this.renderer.checkbox(a);break}case"html":{r+=this.renderer.html(a);break}case"def":{r+=this.renderer.def(a);break}case"paragraph":{r+=this.renderer.paragraph(a);break}case"text":{r+=this.renderer.text(a);break}default:{let o='Token with "'+a.type+'" type was not found.';if(this.options.silent)return console.error(o),"";throw new Error(o)}}}return r}parseInline(t,r=this.renderer){this.renderer.parser=this;let i="";for(let n=0;n<t.length;n++){let a=t[n];if(this.options.extensions?.renderers?.[a.type]){let s=this.options.extensions.renderers[a.type].call({parser:this},a);if(s!==!1||!["escape","html","link","image","checkbox","strong","em","codespan","br","del","text"].includes(a.type)){i+=s||"";continue}}let o=a;switch(o.type){case"escape":{i+=r.text(o);break}case"html":{i+=r.html(o);break}case"link":{i+=r.link(o);break}case"image":{i+=r.image(o);break}case"checkbox":{i+=r.checkbox(o);break}case"strong":{i+=r.strong(o);break}case"em":{i+=r.em(o);break}case"codespan":{i+=r.codespan(o);break}case"br":{i+=r.br(o);break}case"del":{i+=r.del(o);break}case"text":{i+=r.text(o);break}default:{let s='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(s),"";throw new Error(s)}}}return i}},uo=class{options;block;constructor(e){this.options=e||Ei}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?st.lex:st.lexInline}provideParser(e=this.block){return e?Et.parse:Et.parseInline}},uj=class{defaults=ef();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Et;Renderer=Jc;TextRenderer=cf;Lexer=st;Tokenizer=Gc;Hooks=uo;constructor(...e){this.use(...e)}walkTokens(e,t){let r=[];for(let i of e)switch(r=r.concat(t.call(this,i)),i.type){case"table":{let n=i;for(let a of n.header)r=r.concat(this.walkTokens(a.tokens,t));for(let a of n.rows)for(let o of a)r=r.concat(this.walkTokens(o.tokens,t));break}case"list":{let n=i;r=r.concat(this.walkTokens(n.items,t));break}default:{let n=i;this.defaults.extensions?.childTokens?.[n.type]?this.defaults.extensions.childTokens[n.type].forEach(a=>{let o=n[a].flat(1/0);r=r.concat(this.walkTokens(o,t))}):n.tokens&&(r=r.concat(this.walkTokens(n.tokens,t)))}}return r}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(r=>{let i={...r};if(i.async=this.defaults.async||i.async||!1,r.extensions&&(r.extensions.forEach(n=>{if(!n.name)throw new Error("extension name required");if("renderer"in n){let a=t.renderers[n.name];a?t.renderers[n.name]=function(...o){let s=n.renderer.apply(this,o);return s===!1&&(s=a.apply(this,o)),s}:t.renderers[n.name]=n.renderer}if("tokenizer"in n){if(!n.level||n.level!=="block"&&n.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let a=t[n.level];a?a.unshift(n.tokenizer):t[n.level]=[n.tokenizer],n.start&&(n.level==="block"?t.startBlock?t.startBlock.push(n.start):t.startBlock=[n.start]:n.level==="inline"&&(t.startInline?t.startInline.push(n.start):t.startInline=[n.start]))}"childTokens"in n&&n.childTokens&&(t.childTokens[n.name]=n.childTokens)}),i.extensions=t),r.renderer){let n=this.defaults.renderer||new Jc(this.defaults);for(let a in r.renderer){if(!(a in n))throw new Error(`renderer '${a}' does not exist`);if(["options","parser"].includes(a))continue;let o=a,s=r.renderer[o],c=n[o];n[o]=(...l)=>{let u=s.apply(n,l);return u===!1&&(u=c.apply(n,l)),u||""}}i.renderer=n}if(r.tokenizer){let n=this.defaults.tokenizer||new Gc(this.defaults);for(let a in r.tokenizer){if(!(a in n))throw new Error(`tokenizer '${a}' does not exist`);if(["options","rules","lexer"].includes(a))continue;let o=a,s=r.tokenizer[o],c=n[o];n[o]=(...l)=>{let u=s.apply(n,l);return u===!1&&(u=c.apply(n,l)),u}}i.tokenizer=n}if(r.hooks){let n=this.defaults.hooks||new uo;for(let a in r.hooks){if(!(a in n))throw new Error(`hook '${a}' does not exist`);if(["options","block"].includes(a))continue;let o=a,s=r.hooks[o],c=n[o];uo.passThroughHooks.has(a)?n[o]=l=>{if(this.defaults.async&&uo.passThroughHooksRespectAsync.has(a))return(async()=>{let d=await s.call(n,l);return c.call(n,d)})();let u=s.call(n,l);return c.call(n,u)}:n[o]=(...l)=>{if(this.defaults.async)return(async()=>{let d=await s.apply(n,l);return d===!1&&(d=await c.apply(n,l)),d})();let u=s.apply(n,l);return u===!1&&(u=c.apply(n,l)),u}}i.hooks=n}if(r.walkTokens){let n=this.defaults.walkTokens,a=r.walkTokens;i.walkTokens=function(o){let s=[];return s.push(a.call(this,o)),n&&(s=s.concat(n.call(this,o))),s}}this.defaults={...this.defaults,...i}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return st.lex(e,t??this.defaults)}parser(e,t){return Et.parse(e,t??this.defaults)}parseMarkdown(e){return(t,r)=>{let i={...r},n={...this.defaults,...i},a=this.onError(!!n.silent,!!n.async);if(this.defaults.async===!0&&i.async===!1)return a(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return a(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return a(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(n.hooks&&(n.hooks.options=n,n.hooks.block=e),n.async)return(async()=>{let o=n.hooks?await n.hooks.preprocess(t):t,s=await(n.hooks?await n.hooks.provideLexer(e):e?st.lex:st.lexInline)(o,n),c=n.hooks?await n.hooks.processAllTokens(s):s;n.walkTokens&&await Promise.all(this.walkTokens(c,n.walkTokens));let l=await(n.hooks?await n.hooks.provideParser(e):e?Et.parse:Et.parseInline)(c,n);return n.hooks?await n.hooks.postprocess(l):l})().catch(a);try{n.hooks&&(t=n.hooks.preprocess(t));let o=(n.hooks?n.hooks.provideLexer(e):e?st.lex:st.lexInline)(t,n);n.hooks&&(o=n.hooks.processAllTokens(o)),n.walkTokens&&this.walkTokens(o,n.walkTokens);let s=(n.hooks?n.hooks.provideParser(e):e?Et.parse:Et.parseInline)(o,n);return n.hooks&&(s=n.hooks.postprocess(s)),s}catch(o){return a(o)}}}onError(e,t){return r=>{if(r.message+=`
248
- Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error occurred:</p><pre>"+Mt(r.message+"",!0)+"</pre>";return t?Promise.resolve(i):i}if(t)return Promise.reject(r);throw r}}},Si=new uj;function X(e,t){return Si.parse(e,t)}X.options=X.setOptions=function(e){return Si.setOptions(e),X.defaults=Si.defaults,Wy(X.defaults),X};X.getDefaults=ef;X.defaults=Ei;function dj(...e){return Si.use(...e),X.defaults=Si.defaults,Wy(X.defaults),X}X.use=dj;X.walkTokens=function(e,t){return Si.walkTokens(e,t)};X.parseInline=Si.parseInline;X.Parser=Et;X.parser=Et.parse;X.Renderer=Jc;X.TextRenderer=cf;X.Lexer=st;X.lexer=st.lex;X.Tokenizer=Gc;X.Hooks=uo;X.parse=X;var NW=X.options,bW=X.setOptions,kW=X.walkTokens,SW=X.parseInline;var EW=Et.parse,xW=st.lex;ae();et();ue();var gN=Kt(It(),1);import{promises as Jj}from"node:fs";import xt from"node:path";ot();et();ue();Je();U();gt();Xc();Xc();Ci();Kr();ot();oc();ae();ue();rl();Se();U();pN();Ci();Kr();il();ot();Je();il();Da();U();var nl=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};function mf(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`}import Wj from"node:path";ot();Je();Se();Ci();Kr();async function al(e){let t=mf(e.parent),r=Yt(e.paths.projectRoot,t);if(!r)return null;let i=Yt(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=yr(e.paths.projectRoot).map(o=>Wj.resolve(o)).find(o=>ve(o).currentBranch===t);if(!n)return null;let a=el({parent:e.parent,targetBranch:e.targetBranch,targetCommit:i,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(r!==i){for(let o of a.children)o.status=o.dependsOn.length===0?"blocked":"pending",o.blocker=o.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;a.integration.headCommit=r}return df(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function vf(e,t){let r=xt.normalize(xt.resolve(e)),i=xt.normalize(xt.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function Uj(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let r=e.slice(t.index+t[0].length);return r.split(/^#\s+/mu,1)[0]??r}function Kj(e){let t=Uj(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let r=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),i=t.match(/\bChild\s+\d+\b/giu);return Math.max(r?.length??0,i?.length??0)>=2}async function gf(e){try{let t=await ne({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return Kj(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function wf(e){return T("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:r,text:i})=>({id:t,source:r,text:i})),children:e.children})}async function Yj(e){let t=yr(e.projectRoot);t.some(i=>vf(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>xt.resolve(n)))]){let n=await Te(i);n&&r.push({projectRoot:i,paths:await tr(i,n.native.artifact_root),parent:vf(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function Xj(e,t){let r=xt.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Br(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Qj(e,t){let r;try{r=await Jj.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=xt.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await Br(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function Zj(e,t,r){let i=xt.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${xt.sep}`))return null;let n=i.split(xt.sep).join("/");try{let a=(0,gN.parseDocument)(Ve(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:qe(a.toJS({mapAsMap:!1}))}catch{return null}}function e$(e,t,r){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==r||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${r??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function vN(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function wo(e){let t=xt.join(e.paths.changesDir,e.state.name),r=await gf(t),i=null,n;try{n=await Vt({changeDir:t,validation:Jr(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:g})=>g)}:{},policy:"advisory"})}catch(g){i=`Children contract cannot be read; restore children.yaml and confirm Shape: ${g.message}`,n=null}if(!n){let g=await Ue(e.paths,e.state.name,{diagnostics:!0});if(g){let b=tl(g);return{...b,...r?{coordinationChoiceRequired:!0}:{},confirmed:!1,readyChildren:[],allDone:!1,children:b.children.map(k=>({...k,message:i??"Children contract is missing; restore children.yaml and confirm Shape before continuing"}))}}if(i)throw new Error(i);return e.state.children_contract_hash?{...r?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:r?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null}let a=wf({acceptance:e.state.acceptance,children:n.contract}),o=e.state.workspace.change_branch,s=e.state.phase!=="shape"&&e.state.children_contract_hash===a&&!n.drift;if(n.contract.schema===Gr){let g=await Ue(e.paths,e.state.name,{diagnostics:!0});if(!g){let N=e.state.workspace.change_branch??e.state.workspace.target_branch;if(N){let x=await al({paths:e.paths,parent:e.state.name,targetBranch:N,contract:n.contract});x&&(g=x,await Ur(e.paths,x))}}if(g){let N=tl(g);return e.state.children_contract_hash!==a||n.drift?{...N,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:!1,readyChildren:[],allDone:!1,children:N.children.map(x=>({...x,message:n.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...N,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s&&N.confirmed}}let b=new Map(n.contract.children.map(N=>[N.name,N])),k=n.contract.children.map(N=>({name:N.name,summary:N.summary,dependsOn:[...N.depends_on],covers:[],status:s&&N.depends_on.every(x=>n.contract.children.filter(({name:w})=>w!==N.name).every(({name:w})=>w!==x))?"ready":"pending",phase:null,projectRoot:null,message:s?null:"Parent Shape confirmation is required"}));for(let N of k){if(N.status!=="ready")continue;b.get(N.name).depends_on.length>0&&(N.status="pending")}return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:k,readyChildren:k.filter(({status:N})=>N==="ready").map(({name:N})=>N),allDone:!1}}let c=await Yj(e.paths),l=new Set(n.contract.children.map(({name:g})=>g)),u=new Map,d=new Map;for(let g of c){let b=g.parent&&o?`refs/heads/${o}`:"HEAD";for(let k of await Qj(g,l)){let N={...k,source:g,committedState:Zj(g,k.file,b)};u.set(k.state.name,[...u.get(k.state.name)??[],N])}for(let k of l){let N=await Xj(g,k);N&&d.set(k,[...d.get(k)??[],{source:g,state:N}])}}let p=new Map;for(let g of n.contract.children){let b=(u.get(g.name)??[]).find(({source:x,committedState:w})=>x.parent&&w?.name===g.name&&vN(w,o));if(b){p.set(g.name,{kind:"done",phase:b.state.phase,projectRoot:b.source.projectRoot,message:null});continue}let k=u.get(g.name)?.[0];if(k){p.set(g.name,{kind:"blocked",phase:k.state.phase,projectRoot:k.source.projectRoot,message:`Native child ${g.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let N=d.get(g.name)??[];N.length>1?p.set(g.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${g.name} has multiple active workspace owners`}):N[0]&&p.set(g.name,e$(N[0].state,N[0].source,o))}let f=new Map(n.contract.children.map(g=>[g.name,g])),m=new Map,h=g=>{let b=m.get(g);if(b)return b;let k=f.get(g),x=k.depends_on.map(h).every(({status:O})=>O==="done"),w=p.get(g),S=w?.kind==="active"&&x?k.depends_on.filter(O=>!(u.get(O)??[]).some(({source:j,committedState:Q})=>vf(j.projectRoot,w.projectRoot)&&Q?.name===O&&vN(Q,o))):[],E,y=w?.message??null;w?.kind==="done"?(E=x?"done":"blocked",x||(y=`Native child ${g} was merged before its dependencies`)):w?.kind==="active"?(E=x&&S.length===0?"active":"blocked",x?S.length>0&&(y=`Native child ${g} does not include merged dependencies: ${S.join(", ")}`):y=`Native child ${g} started before its dependencies merged`):w?.kind==="blocked"?E="blocked":(E=s&&x?"ready":"pending",s||(y="Parent Shape confirmation is required"));let C={name:g,summary:k.summary,dependsOn:[...k.depends_on],covers:[...k.covers],status:E,phase:w?.phase??null,projectRoot:w?.projectRoot??null,message:y};return m.set(g,C),C},v=n.contract.children.map(({name:g})=>h(g));return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:v,readyChildren:v.filter(({status:g})=>g==="ready").map(({name:g})=>g),allDone:v.every(({status:g})=>g==="done")}}dc();gt();gi();ho();Qc();Se();sp();Xd();gt();gi();ae();pi();ho();U();pi();ti();Je();var ab=Kt(It(),1);er();var $G=new Set("a an and are as at be by for from in is it of on or that the this to with you your".split(" "));var LG=256*1024;gt();gi();Kr();var N0=Ks("en",{compact:!0});Je();Se();Ci();Kr();gt();gi();ot();oc();ue();import Dn from"node:path";ot();er();ae();var tU=8*1024*1024;rl();Se();gi();U();function S0(e,t){let r=Dn.relative(Dn.resolve(e),Dn.resolve(t));if(Dn.isAbsolute(r)||r===".."||r.startsWith(`..${Dn.sep}`))throw new Error("Native local check cwd escaped the project root");let i=r.length===0?".":r.split(Dn.sep).join("/");return dN(e,i),i}function lb(e,t=e.workspace.projectRoot){return e.checks.map(r=>{let[i,...n]=r.argv;if(!i)throw new Error(`Native local check ${r.id} has no executable`);return{id:r.id,name:r.name,executable:i,argv:n,cwdRef:S0(t,r.cwd),timeoutMs:r.timeoutMs,repeatable:r.repeatable}})}var EU=1024*1024*1024;Se();Qc();ho();Kr();Se();Kr();Se();wp();var m6=16*1024;async function ub(e){let t=await Ip(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(sn(t.selection.change),t.selection)}U();async function db(e,t){let r=[],i=Y(e,t.name),n=Or(i,at.stateRef),a;try{a=await bn(i)}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")&&r.push({code:"run-state-missing",message:"Native change references a missing Run state",path:n}),r;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&&r.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")&&r.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:n}),a.currentStep!==t.phase&&r.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:n});let o=Or(i,a.trajectoryRef),s=await ay(e,t.name);if(s.status==="repairable")return r.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}),r;if(s.status==="invalid")return r.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),r;let c;try{if(c=await Ni(i,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 r.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),r}let l=Or(i,a.checkpointRef);try{let u=await jc(i,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&r.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):r.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){r.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return r}yn();import W0 from"path";import{isDeepStrictEqual as zf}from"util";ae();Lt();Da();Se();U();wt();Ri();ue();ue();var Bn={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var E0=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function x0(e,t){return e<t?-1:e>t?1:0}function C0(e,t,r,i){if(!Array.isArray(e)||e.length>r||!i&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let n=e.map(a=>{if(typeof a!="string"||!E0.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(x0)}function Bf(e=[]){return C0(e,"Native repair failed check IDs",Bn.maxFailedCheckIds,!0)}function pb(e,t){let r=new Set(t);return e.every(i=>r.has(i))}function R0(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:pb(e.failedAcceptanceIds,t.failedAcceptanceIds)&&pb(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function Ff(e,t){let r=1,i=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if(R0(i,a))break;r+=1,i=a}return r}ul();Ii();function Lf(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 fb="repairStagnation",Ye={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 A0=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"],hb=["disposition","overrideSummaryHash","signatureHash"],T0=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],mb=12;function Mf(e,t){return e<t?-1:e>t?1:0}function vb(e,t,r){let i=Object.keys(e).sort(Mf);if(i.length!==t.length||i.some((n,a)=>n!==t[a]))throw new Error(`${r} fields are invalid`)}function hl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Error(`${t} must be a plain object`);return e}function $o(e,t){if(typeof e!="string"||!_0.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function j0(e){if(!Array.isArray(e)||e.length>Bn.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(Mf)}function gb(e){if(typeof e!="string"||e.length===0||e.length>Ye.maxRunIdCharacters||Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function qf(e,t,r,i,n=!1){if(r.nodes+=1,r.nodes>Ye.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Ye.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(`${i} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>Ye.maxTextCharacters&&(!n||e.length>Ye.maxEventDataCharacters))throw new Error(`${i} contains oversized text`);if(r.characters+=e.length,r.characters>Ye.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${i} contains a non-JSON value`);if(r.ancestors.has(e))throw new Error(`${i} contains a cycle`);r.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>Ye.maxArrayEntries)throw new Error(`${i} contains an oversized array`);e.forEach((s,c)=>qf(s,t+1,r,`${i}[${c}]`));return}let a=hl(e,i),o=Object.keys(a);if(o.length>Ye.maxObjectFields)throw new Error(`${i} contains too many fields`);for(let s of o){if(s.length===0||s.length>Ye.maxKeyCharacters)throw new Error(`${i} contains an invalid field name`);if(r.characters+=s.length,r.characters>Ye.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");qf(a[s],t+1,r,`${i}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{r.ancestors.delete(e)}}}function $0(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 O0(e,t,r){let i=hl(e,`Native repair trajectory event ${t+1}`);if(vb(i,I0,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(i.sequence)||i.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if($0(i.timestamp),typeof i.type!="string"||!A0.has(i.type))throw new Error("Native repair trajectory event type is invalid");if(gb(i.runId)!==r)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let n={nodes:0,characters:0,ancestors:new Set};return qf(i.data,0,n,"Native trajectory event data"),hl(i.data,"Native repair trajectory event data"),{event:i,dataNodes:n.nodes,dataCharacters:n.characters}}function Vf(e){let t=hl(e,"Native repair trajectory projection"),r=Object.keys(t).sort(Mf),i=r.length===hb.length&&r.every((l,u)=>l===hb[u]);i||vb(t,T0,"Native repair trajectory projection");let n=$o(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:$o(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(i)return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=$o(t.contractHash,"Native repair trajectory contract hash"),s=j0(t.failedAcceptanceIds),c=Bf(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 H0(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 D0(e,t){let r=t.filter(s=>s.kind==="failure"),i=r.length+1,n=e.maxVerifyFailures??mb;if(i>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=Ff({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},r),o=i>=n?"hard-stop":a<Bn.warningAtConsecutiveFailures?"continue":a<Bn.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function B0(e,t,r){let i=t.filter(a=>a.kind==="failure"),n=r?.maxVerifyFailures??mb;if(i.length>=n)throw new Error("Native repair trajectory cannot override a hard stop");if(r?.disposition!=="manual-stop"||r.signatureHash!==e.signatureHash||i.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 wb(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Ye.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=gb(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 r=[],i=null,n=null,a=null,o=0,s=0,c=0;for(let l=0;l<e.committedTrajectoryOffset;l+=1){let u=O0(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>Ye.maxTotalDataNodes||c>Ye.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let p=d.data,f=Object.hasOwn(p,"repairScopeHash")?$o(p.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(p,"implementationScopeHash")?$o(p.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(p,fb)){if(i?.contractHash===null&&d.type==="state_transitioned"&&p.previousPhase==="build"&&p.nextPhase==="verify"&&(f!==null&&n!==null&&f!==n||f===null&&(i?.disposition==="manual-stop"||i?.disposition==="hard-stop"))){r.length=0,i=null,n=f,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let m=Vf(p[fb]);if(H0(p,m),m.overrideSummaryHash===null)m.contractHash!==null&&a!==null&&m.contractHash!==a&&(r.length=0,o=0),m.contractHash!==null&&(a=m.contractHash),m.contractHash===null&&f!==null&&n!==null&&f!==n&&(r.length=0,o=0),f!==null&&(n=f),D0(m,r),o+=1,r.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:m.signatureHash,...m.contractHash===null?{}:{failedAcceptanceIds:[...m.failedAcceptanceIds],failedCheckIds:[...m.failedCheckIds]}});else{if(i?.contractHash===null&&f!==null&&n!==null&&f!==n)throw new Error("Native repair override cannot cross implementation scope progress");B0(m,r,i);let h=r.at(-1);if(!h||h.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");r.push({kind:"override",revision:d.sequence,iteration:h.iteration,signatureHash:m.signatureHash,summaryHash:m.overrideSummaryHash})}if(i=m,r.length>Bn.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:r,latestProjection:i}}function yb(e){return wb(e).history}function Nb(e){let t=wb(e).latestProjection;return t?{...t}:null}Lt();var Fn={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:[]},Wf=ee("comet-native-runtime:v3:scope-reopen"),F0=[{skillVersion:"3",skillHash:ee("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:ee("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:ee("comet-native-runtime:v1")}];function bb(e){return e.skillVersion===Fn.definition.metadata.version&&e.skillHash===Wf||F0.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}Lt();Lt();function kb(e){return ee(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}))}Fa();var Rb=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],z0=new Set(Rb),Pb=new Set([...Rb,"minimum_runtime_version","revision"]),G0=new Set([...Pb,"operation"]),Gf=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),J0=new Set([...Gf,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),Jf=class extends Error{constructor(r){super(`Native transition for ${r} requires doctor migration before recovery`);this.change=r;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function Kf(e,t){return W0.join(Y(e,t),"transition.json")}function vl(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function Yf(e,t){let r=Object.keys(e).find(i=>!t.has(i));if(r)throw new Error(`Native transition journal contains unknown field: ${r}`)}function ml(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Uf(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let r=e,i=Object.keys(r),n=i.find(u=>!J0.has(u)),a=[...Gf].find(u=>!Object.hasOwn(r,u)),o=Gf.size+(Object.hasOwn(r,"implementationScopeHash")?1:0)+(Object.hasOwn(r,"repairScopeHash")?1:0)+(Object.hasOwn(r,"repairStagnation")?1:0)+(Object.hasOwn(r,"returnToBuild")?1:0);if(n||a||i.length!==o)throw new Error(`Native transition journal event data keys are invalid${n?`: ${n}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(r.previousPhase)||!["shape","build","verify","archive"].includes(r.nextPhase))throw new Error("Native transition journal event phases are invalid");if(r.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if(r.returnToBuild!==void 0&&typeof r.returnToBuild!="boolean")throw new Error("Native transition journal returnToBuild flag is invalid");if(Lf(r.summary,"Native transition journal event summary"),ct(r.summary)!==r.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(r.artifacts)||r.artifacts.length>128||r.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(r.noCodeReason!==null&&(Lf(r.noCodeReason,"Native transition journal event no-code reason"),ct(r.noCodeReason)!==r.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(r.verificationResult!==null&&r.verificationResult!=="pass"&&r.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(r,"implementationScopeHash")?r.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||r.previousPhase!=="build"&&r.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(r,"repairStagnation")?Vf(r.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(r.previousPhase!=="verify"||r.nextPhase!=="build"||r.verificationResult!=="fail")||!u&&(r.previousPhase!=="build"||r.nextPhase!=="verify"||r.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(r,"repairScopeHash")?r.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||r.previousPhase!=="build"&&r.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:r.previousPhase,nextPhase:r.nextPhase,evidenceHash:t,summary:r.summary,artifacts:[...r.artifacts],noCodeReason:r.noCodeReason,verificationResult:r.verificationResult,...r.returnToBuild===!0?{returnToBuild:!0}:{},...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function U0(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let r=e,i=Object.keys(r),n=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(i.length===n.size&&i.every(a=>n.has(a))&&r.reason==="spec-rebase")return Uf({previousPhase:r.previousPhase,nextPhase:r.nextPhase,evidenceHash:r.evidenceHash,summary:r.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return Uf(e,t)}function Xf(e,t,r=!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 i=r?U0(e.eventData,e.evidenceHash):Uf(e.eventData,e.evidenceHash),n=jp(e.nextRun),a=e.previousRun===null?null:jp(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:i}}function Sb(e,t,r=!1){if(e.skill!==Fn.definition.metadata.name||(r?!bb(e):e.skillVersion!==Fn.definition.metadata.version||e.skillHash!==Wf)||e.orchestration!==Fn.definition.orchestration.mode||e.pendingRef!==at.pendingRef||e.trajectoryRef!==at.trajectoryRef||e.contextRef!==at.contextRef||e.artifactsRef!==at.artifactsRef||e.checkpointRef!==at.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function Eb(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 xb(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 Qf(e,t,r,i=!1,n="advance"){let{previousRun:a,nextRun:o}=r;if(Sb(o,"next Run",i||a!==null),xb(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(Sb(a,"previous Run",!0),xb(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(!zf(Eb(a),Eb(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function K0(e,t,r){return ee(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:r}))}function _b(e,t,r){return e.phase!=="shape"&&t.phase==="build"&&r.verificationResult===null?"spec-rebase":"advance"}function Cb(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function Zf(e,t,r,i,n=!1){let a=r.eventData,o=Cb(e),s=Cb(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(i==="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&&zf(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(i==="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&&zf(e.spec_changes,t.spec_changes),l=kb({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||r.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(i==="spec-rebase"){let c=K0(e.name,a.summary,t.spec_changes),l=ee(`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&&r.evidenceHash!==c||n&&r.evidenceHash!==c&&r.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 Y0(e,t){let r=vl(e);if(Yf(r,G0),r.schema!==nn)throw new Error(`Expected Native transition schema ${nn}`);let i=ml(r.minimum_runtime_version,"Native transition minimum_runtime_version");if(i>3)throw new Error(`Native transition requires runtime protocol ${i}; current protocol is ${3}`);if(i!==3)throw new Error(`Native transition ${nn} minimum_runtime_version must be ${3}`);let n=ml(r.revision,"Native transition revision");if(n!==1)throw new Error("Native transition journal revision must be 1");if(r.operation!=="advance"&&r.operation!=="spec-rebase"&&r.operation!=="evidence-retreat"&&r.operation!=="runtime-rebuild")throw new Error("Native transition journal operation is invalid");let a=Xf(r,t),o=Bt(r.previousState),s=Bt(r.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(Zf(o,s,a,r.operation),Qf(o,s,a,!1,r.operation),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:nn,minimum_runtime_version:3,revision:n,operation:r.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 r=vl(e);if(Yf(r,z0),r.schema!==Ba)throw new Error(`Expected Native transition schema ${Ba}`);let i=Xf(r,t,!0),n=hi(r.previousState),a=hi(r.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return Zf(n,a,i,_b(n,a,i.eventData),!0),Qf(n,a,i,!0),{schema:Ba,id:i.id,change:t,evidenceHash:i.evidenceHash,createdAt:i.createdAt,previousState:n,nextState:a,previousRun:i.previousRun,nextRun:i.nextRun,eventData:i.eventData}}function Q0(e,t){let r=vl(e);if(Yf(r,Pb),r.schema!==an)throw new Error(`Expected Native transition schema ${an}`);if(ml(r.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${an} minimum_runtime_version must be 2`);let n=ml(r.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=Xf(r,t,!0),o=mi(r.previousState),s=mi(r.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(Zf(o,s,a,_b(o,s,a.eventData),!0),Qf(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:an,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 Z0(e,t){let r=vl(e);if(r.schema===nn)return{status:"current",journal:Y0(r,t)};if(r.schema===Ba)return{status:"migration-required",journal:X0(r,t)};if(r.schema===an)return{status:"migration-required",journal:Q0(r,t)};throw new Error(`Unsupported Native transition journal schema: ${String(r.schema)}`)}async function eO(e,t){let r=Kf(e,t),i=we(e,r);await K(i,r);try{let n=await wi({root:i,file:r,maxBytes:null,label:`Native transition journal ${t}`});return Z0(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Ab(e,t){let r=await eO(e,t);if(!r)return null;if(r.status==="migration-required")throw new Jf(t);return r.journal}var tO=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function rO(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function iO(e){return e?e.map(rO).join(" "):null}function nO(e){if(e===null)return null;let t=e.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/gu);return!t||t[0]!=="comet"?null:t.map(r=>{if(r.startsWith('"')&&r.endsWith('"'))try{return JSON.parse(r)}catch{return r.slice(1,-1)}return r.startsWith("'")&&r.endsWith("'")?r.slice(1,-1):r})}function lt(e,t,r,i={}){return{input:e,flags:t,required:i.required??!0,placeholder:r,...i.choices?{choices:i.choices}:{},...i.repeatable?{repeatable:!0}:{},...i.alternativeGroup?{alternativeGroup:i.alternativeGroup}:{}}}function aO(e){return e.map(t=>lt(t,[],null))}function oO(e){let t=["comet","native","next",e.name,"--summary","<summary>"],r=[lt("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),r.push(lt("shared-understanding-confirmation",["--confirmed"],null)),{commandArgs:t,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:r};if(e.phase==="build"){t.push("--artifact","<project-relative-path>"),r.push(lt("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),lt("artifact-or-no-code-reason",["--no-code-reason"],"<reason>",{alternativeGroup:"build-evidence"}));let i=["summary","artifact-or-no-code-reason"];return e.approval!=="confirmed"&&(t.push("--confirmed"),i.push("shared-understanding-confirmation"),r.push(lt("shared-understanding-confirmation",["--confirmed"],null))),{commandArgs:t,requiredInputs:i,inputOptions:r}}return e.phase==="verify"?(t.push("--result","<pass|fail>","--report","<change-relative-path>"),r.push(lt("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),lt("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:r}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function Re(e,t){let r=t.commandArgs===void 0?nO(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?iO(r??null):t.command,commandArgs:r??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??aO(t.requiredInputs??[])}}function gl(e){let r=(e.findings??[]).filter(d=>!kn(d.code)),i=r.find(d=>d.requiresUserDecision),n=r.find(d=>d.repairCommand!==null||tO.test(d.code)),a=r.find(d=>d.code==="repair-iteration-limit"||d.code==="repair-override-exhausted"),o=r.find(d=>d.code==="repair-stagnation-stop"),s=r.find(d=>d.requiredAction==="return-to-bound-working-directory"||d.requiredAction==="repair-workspace-binding"),c=r.find(d=>d.code==="runtime-missing"),l=[...new Set(r.map(d=>d.requiredAction))].sort();if(e.done)return Re(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return Re(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[lt("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(i)return Re(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return Re(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return Re(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return Re(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[lt("summary",["--summary"],"<summary>")]});if(n)return Re(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 Re(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[lt("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return Re(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(r.length>0)return e.state.phase==="archive"?Re(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?Re(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):Re(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"),Re(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[lt("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):Re(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return Re(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=oO(e.state);return Re(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import Oo from"path";U();var Ib=8,sO={"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 cO(e){let t=sO[e];return t||(/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid)|transition-invalid)/u.test(e)?{severity:"error",requiredAction:"isolate-or-restore-native-runtime-from-a-trusted-copy",retry:"none",repair:"none"}:e.startsWith("brief-")?{severity:"error",requiredAction:"complete-brief",retry:"next",repair:"none"}:e.startsWith("spec-")?{severity:"error",requiredAction:"resolve-spec-state",retry:"next",repair:"none"}:e.startsWith("verification-")?{severity:"error",requiredAction:"complete-verification-evidence",retry:"next",repair:"none"}:e.startsWith("build-")?{severity:"error",requiredAction:"record-build-evidence",retry:"next",repair:"none"}:kn(e)?{severity:e==="workspace-inspection-unavailable"?"info":"warning",requiredAction:"inspect-workspace-advisory",retry:"status",repair:"none"}:{severity:"error",requiredAction:"resolve-finding",retry:"status",repair:"none"})}function lO(e,t,r){if(!r.path)return null;let i;if(Oo.isAbsolute(r.path)?i=Oo.resolve(r.path):/^(?:brief-|verification-|spec-source)/u.test(r.code)?i=Oo.resolve(Ne(e,t.name),...r.path.split(/[\\/]/u)):i=Oo.resolve(e.projectRoot,...r.path.split(/[\\/]/u)),!q(e.projectRoot,i))return null;let n=Oo.relative(e.projectRoot,i).replaceAll("\\","/");return n===""?".":n}function uO(e,t,r){return e==="next"?`comet native next ${t.name} --summary "<summary>"${r==="contract-changed-after-approval"||r==="shape-confirmation-required"||r==="approval-confirmation-required"?" --confirmed":""}`:e==="status"?`comet native status ${t.name} --details`:null}function eh(e){return e.findings.map(t=>{let r=cO(t.code);return{code:t.code,message:t.message,severity:r.severity,path:lO(e.paths,e.state,t),requiredAction:r.requiredAction,retryCommand:uO(r.retry,e.state,t.code),repairCommand:r.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,r)=>{let i={error:0,warning:1,info:2};return i[t.severity]-i[r.severity]||t.code.localeCompare(r.code)||(t.path??"").localeCompare(r.path??"")||t.message.localeCompare(r.message)})}function th(e){let t=[...new Set(e.map(r=>r.code))];return{total:e.length,errors:e.filter(r=>r.severity==="error").length,warnings:e.filter(r=>r.severity==="warning").length,info:e.filter(r=>r.severity==="info").length,requiresUserDecision:e.some(r=>r.requiresUserDecision),codes:t.slice(0,Ib),truncated:t.length>Ib}}ae();import Ln from"path";Lt();U();wt();Ra();Ri();var Ho={maxArtifacts:128},qn=/^[a-f0-9]{64}$/u;function wl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function yl(e,t,r){let i=new Set(t),n=Object.keys(e).filter(o=>!i.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${r} is missing field(s): ${a.join(", ")}`)}function ri(e,t,r=2e3){if(typeof e!="string"||e.length===0||e.length>r)throw new Error(`${t} must be a non-empty string of at most ${r} characters`);return e}function Tb(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function rh(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function dO(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||Ln.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let r=Ln.posix.normalize(t);if(r==="."||r===".."||r.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return r}function jb(e,t){return Ln.join(Y(e,t),"checkpoints","progress.json")}function Do(e,t){return Ln.join(Y(e,t),"checkpoint-journal.json")}function $b(e,t,r){if(!qn.test(r))throw new Error("Native checkpoint manifest hash is invalid");return Ln.join(Y(e,t),"checkpoints","manifests",`${r}.json`)}function pO(e){if(!qn.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function ih(e,t,r){let i=await wi({root:e,file:t,maxBytes:null,label:r});return JSON.parse(i.bytes.toString("utf8"))}function fO(e,t){let r=wl(e,`checkpoint manifest artifact ${t}`);yl(r,["path","hash","size"],`checkpoint manifest artifact ${t}`);let i=dO(ri(r.path,`checkpoint artifact ${t} path`,4096)),n=Tt(i);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${i}`);if(typeof r.hash!="string"||!qn.test(r.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:i,hash:r.hash,size:rh(r.size,`checkpoint artifact ${t} size`)}}function nh(e,t){let r=wl(e,"Native checkpoint manifest");if(yl(r,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),r.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(r.change!==t)throw new Error("Native checkpoint manifest change mismatch");if(!Array.isArray(r.artifacts))throw new Error("Native checkpoint manifest artifacts must be an array");if(r.artifacts.length>Ho.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let i=r.artifacts.map(fO),n=[...i].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(i)!==JSON.stringify(n))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(i.map(o=>o.path)).size!==i.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=rh(r.totalBytes,"checkpoint manifest totalBytes");if(i.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:i,totalBytes:a}}function Ob(e){return ee(JSON.stringify(nh(e,e.change)))}function Hb(e,t){let r=wl(e,"Native progress checkpoint");if(yl(r,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),r.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(r.change!==t)throw new Error("Native checkpoint change mismatch");let i=r.phase;if(i!=="shape"&&i!=="build"&&i!=="verify"&&i!=="archive")throw new Error("Native checkpoint phase is invalid");let n=Tb(r.previousRevision,"Native checkpoint previousRevision"),a=Tb(r.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=ri(r.manifestHash,"Native checkpoint manifestHash",64);if(!qn.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=pO(o);if(r.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=ri(r.inputHash,"Native checkpoint inputHash",64);if(!qn.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=ri(r.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=rh(r.artifactCount,"Native checkpoint artifactCount");if(u>Ho.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=ri(r.summary,"Native checkpoint summary"),p=ri(r.nextAction,"Native checkpoint nextAction");if(ct(d)!==d||ct(p)!==p)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:ri(r.id,"Native checkpoint id",128),change:t,phase:i,previousRevision:n,stateRevision:a,summary:d,nextAction:p,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function hO(e,t){let r=wl(e,"Native checkpoint journal");if(yl(r,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),r.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(r.change!==t)throw new Error("Native checkpoint journal change mismatch");let i=Bt(r.previousState),n=Bt(r.nextState),a=Hb(r.checkpoint,t),o=nh(r.manifest,t),s=ri(r.inputHash,"Native checkpoint journal inputHash",64),c=ee(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!qn.test(s)||s!==a.inputHash||s!==c||r.id!==a.id||r.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(i.name!==t||n.name!==t||n.revision!==i.revision+1||a.previousRevision!==i.revision||a.stateRevision!==n.revision||a.phase!==n.phase||a.manifestHash!==Ob(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:i,nextState:n,checkpoint:a,manifest:o}}async function mO(e,t,r){let i=Ln.resolve(e.projectRoot,...t.split("/"));if(!q(e.projectRoot,i)||q(e.nativeRoot,i)||q(e.runtimeDir,i))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=bd(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await yp({root:e.projectRoot,file:i,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot,e.runtimeDir],hooks:{afterParentChainCaptured:()=>r?.afterParentChainCaptured?.(t),afterOpen:()=>r?.afterOpen?.(t),beforeRead:()=>r?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function vO(e,t){let r=jb(e,t),i=we(e,r);await K(i,r);try{return Hb(await ih(i,r,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function gO(e,t,r){let i=$b(e,t,r),n=we(e,i);await K(n,i);let a=await ih(n,i,"Native checkpoint manifest"),o=nh(a,t);if(Db(e,o),Ob(o)!==r)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function ah(e,t){let r=Do(e,t),i=we(e,r);await K(i,r);try{let n=hO(await ih(i,r,"Native checkpoint journal"),t);return Db(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}function Db(e,t){for(let r of t.artifacts){let i=bd(e,r.path);if(i)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${i}): ${r.path}`)}}async function Bb(e){let t;try{t=await vO(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:jb(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let r=[],i=[];t.stateRevision!==e.stateRevision&&r.push("state-revision-changed");let n=null;try{n=await gO(e.paths,e.name,t.manifestHash);let a=ee(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 mO(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&r.push(`artifact-changed:${o.path}`)}catch{r.push(`artifact-unavailable:${o.path}`)}}catch(a){r.push("checkpoint-manifest-invalid"),i.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:$b(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:r.length===0?"fresh":"stale",reasons:r,findings:i}}var Fb=240,Lb=8,Nl=50;function qb(e){let t=Array.from(e);return t.length<=Fb?e:`${t.slice(0,Fb-1).join("")}…`}function wO(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function yO(e){let t=[...new Set(e.map(wO))],r={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,Lb),reasonCount:e.length,codesTruncated:t.length>Lb};return{inspection:r,inspectionDetails:{...r,reasons:e.slice(0,Nl),reasonsTruncated:e.length>Nl}}}async function Mb(e){let t=null;try{let s=await ah(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:Do(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:Do(e.paths,e.state.name)}}let r=await Bb({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),i=t?[t.code,...r.reasons]:r.reasons,n=yO(i);if(!r.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...r.findings]:r.findings,maxCheckpointArtifacts:Ho.maxArtifacts};let a={id:r.checkpoint.id,createdAt:r.checkpoint.createdAt,phase:r.checkpoint.phase,stateRevision:r.checkpoint.stateRevision,summary:qb(r.checkpoint.summary),nextAction:qb(r.checkpoint.nextAction),artifactCount:r.checkpoint.artifactCount},o=r.manifest?{...a,summary:r.checkpoint.summary,nextAction:r.checkpoint.nextAction,manifestHash:r.checkpoint.manifestHash,manifestRef:r.checkpoint.manifestRef,artifacts:r.manifest.artifacts,totalBytes:r.manifest.totalBytes}:null;return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...r.findings]:r.findings,maxCheckpointArtifacts:Ho.maxArtifacts}}import{promises as wH}from"node:fs";import sk from"node:path";ue();import Vb from"node:path";var NO="comet.native.archive-preflight.v1",bO="comet.native.archive-preflight.v1",kO="comet.native.archive-operation.v1",SO=/^[a-f0-9]{64}$/u,Wb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,EO=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function bl(e,t){return e<t?-1:e>t?1:0}function xO(e,t){if(typeof e!="string"||!SO.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function hr(e,t){return e===null?null:xO(e,t)}function CO(e,t){let r=Vb.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||Vb.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized Native-relative ref`);return e}function RO(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function PO(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,r]of[["change",e.changeBranch],["target",e.targetBranch]])if(r!==null&&(r.length===0||r.trim()!==r||Array.from(r).some(i=>{let n=i.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 r=hr(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),i=hr(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=hr(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&r!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&r===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:r,actualBaseHash:i,proposedHash:n}}function AO(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:hr(e.contractHash,"Native archive contract hash"),acceptanceHash:hr(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:hr(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:hr(e.reportHash,"Native archive report hash"),envelopeHash:hr(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:hr(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(r=>r===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 IO(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(i=>{if(typeof i!="string"||!EO.test(i))throw new Error(`Native archive preflight finding code is invalid: ${String(i)}`);return i}),r=[...new Set(t)].sort(bl);if(r.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return r}function TO(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 r of e.specs)r.actualBaseHash!==r.expectedBaseHash&&t.push("spec-base-conflict");return[...new Set(t)].sort(bl)}function zb(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)=>bl(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 r=t.map(l=>({...l,operationHash:T(kO,l)})),i=AO(e.evidence),n=PO(e.workspace),a=[...new Set([...IO(e.findingCodes??[]),...TO({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:i})])].sort(bl),o=RO(e.revision),s=CO(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:r,evidence:i,workspace:n,findingCodes:a};return{schema:NO,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:i.freshness,operationCount:r.length,operations:r,workspace:n,findingCodes:a,preflightHash:T(bO,c)}}et();ue();import{createHash as jO}from"node:crypto";import Gb from"node:path";var $O="comet.native.conflict-radar.v1",ze=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}),OO="comet.native.conflict-radar.v1",HO="comet.native.conflict-radar-signals.v1",DO=/^[a-f0-9]{64}$/u,Kb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,BO=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),FO=new Set(["capability","operation","baseHash"]),LO=new Set(["path","kind"]);function Mn(e,t){return e<t?-1:e>t?1:0}function oh(e){return Buffer.byteLength(e,"utf8")}function sh(e,t,r){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${r} must be an object`);let i=e,n=Object.keys(i).filter(a=>!t.has(a));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);return i}function ch(e,t,r){if(typeof e!="string"||e.length===0||e!==e.trim())throw new Error(`${t} must be a non-empty trimmed string`);if(oh(e)>r)throw new Error(`${t} exceeds its byte budget`);return e}function qO(e,t){let r=ch(e,t,ze.maxArtifactPathBytes),i=Gb.posix.normalize(r);if(r.includes("\\")||Array.from(r).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(r)||Gb.posix.isAbsolute(i)||r.split("/").includes("..")||i!==r||i==="."||r.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return r}function Yb(e,t){if(typeof e!="string"||!DO.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function MO(e,t){let r=sh(e,FO,t),i=ch(r.capability,`${t} capability`,ze.maxCapabilityBytes);if(!Kb.test(i))throw new Error(`${t} capability is invalid`);if(r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`${t} operation is invalid`);let n=r.baseHash===null?null:Yb(r.baseHash,`${t} canonical base hash`);if(r.operation==="create"&&n!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(r.operation!=="create"&&n===null)throw new Error(`${t} ${r.operation} operation requires a canonical base hash`);return{capability:i,operation:r.operation,baseHash:n}}function VO(e,t){let r=sh(e,LO,t);if(r.kind!=="file"&&r.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:qO(r.path,`${t} path`),kind:r.kind}}function WO(e,t){let r=sh(e,BO,`Conflict radar change ${t}`),i=ch(r.name,`Conflict radar change ${t} name`,ze.maxNameBytes);if(!Kb.test(i))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(r.revision)||r.revision<1)throw new Error(`Conflict radar change ${i} revision must be a positive safe integer`);if(!Array.isArray(r.specs))throw new Error(`Conflict radar change ${i} specs must be an array`);if(r.specs.length>ze.maxSpecsPerChange)throw new Error(`Conflict radar change ${i} exceeds the spec budget`);if(!Array.isArray(r.declaredArtifacts))throw new Error(`Conflict radar change ${i} declared artifacts must be an array`);if(r.declaredArtifacts.length>ze.maxArtifactsPerChange)throw new Error(`Conflict radar change ${i} exceeds the declared artifact budget`);let n=r.specs.map((c,l)=>MO(c,`Conflict radar change ${i} spec ${l}`)).sort((c,l)=>Mn(c.capability,l.capability));if(new Set(n.map(c=>c.capability)).size!==n.length)throw new Error(`Conflict radar change ${i} has duplicate capabilities`);let a=r.declaredArtifacts.map((c,l)=>VO(c,`Conflict radar change ${i} artifact ${l}`)).sort((c,l)=>Mn(c.path,l.path)||Mn(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${i} has duplicate or conflicting artifact paths`);let s=r.workspaceIdentityHash===void 0||r.workspaceIdentityHash===null?null:Yb(r.workspaceIdentityHash,`Conflict radar change ${i} workspace identity hash`);return{name:i,revision:r.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function zO(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>ze.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(WO).sort((n,a)=>Mn(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)>ze.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>ze.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function GO(e,t){let r=e.baseHash!==null&&e.baseHash===t.baseHash;return{kind:"capability",certainty:e.operation==="create"||t.operation==="create"||r?"definite-conflict":"possible-overlap",capability:e.capability,leftOperation:e.operation,rightOperation:t.operation,leftBaseHash:e.baseHash,rightBaseHash:t.baseHash}}function JO(e,t){let r=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),i=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),n=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!r&&!i&&!n?null:{kind:"artifact",certainty:n?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function UO(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function KO(e,t){let r=[],i=jO("sha256").update(`${HO}
249
- [`),n=0,a=!1,o=l=>{n>0&&i.update(","),i.update(Yn(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),r.length<ze.maxSignalsPerRelationship&&r.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(GO(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=JO(l,u);d&&o(d)}let c=a?"definite-conflict":n>0?"possible-overlap":"disjoint";return i.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:UO(e,t),signalCount:n,signalHash:i.digest("hex"),signals:r,signalsTruncated:r.length!==n}}function Jb(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function YO(e,t){return Jb(e.classification)-Jb(t.classification)||Mn(e.left,t.left)||Mn(e.right,t.right)}function Ub(e,t,r,i){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:$O,workspaceIdentityAdvisoryOnly:!0,changeCount:e.length,relationshipCount:t.length,counts:n,relationships:r,relationshipsTruncated:r.length!==t.length,omittedRelationshipCount:t.length-r.length,radarHash:i}}function Xb(e){let t=zO(e),r=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)r.push(KO(t[s],t[c]));r.sort(YO);let i=r.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=T(OO,{changes:t,relationships:i}),a=r.slice(0,ze.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=Ub(t,r,a,n);for(;a.length>0&&oh(JSON.stringify(o))>ze.maxSerializedBytes;)a=a.slice(0,-1),o=Ub(t,r,a,n);if(oh(JSON.stringify(o))>ze.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}ti();wt();var XO=4096;async function QO(e,t=ze.maxChanges){try{let r=await Ka({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:t});return await r.verify(),r.entries}catch(r){if(r.code==="ENOENT")return[];throw r}}async function Qb(e,t){let r=await sr(e,t),[i,n]=await Promise.all([r.implementation_scope?pl(e,t,r.implementation_scope):null,or(e,t).catch(()=>null)]);return{name:r.name,revision:r.revision,specs:r.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:i?.declaredArtifacts??[],workspaceIdentityHash:n?.nativeRootId??null}}async function kl(e,t,r={}){let n=(await QO(e,XO)).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 Qb(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await Qb(e,c).catch(d=>{if(r.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=Xb([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"]:[]]}}Je();U();Va();et();ti();yn();Ii();ul();import{execFile as lH}from"node:child_process";Hi();Gn();hf();import{promisify as uH}from"node:util";Se();ae();Tf();U();jt();import{constants as lh,promises as ut}from"node:fs";import Vn from"node:path";var eH=/^[a-f0-9]{64}$/u,tH=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u;function rH(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Sl(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Qe(r,i)?G(r,i):G(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function iH(e,t){let r=Vn.resolve(e),i=Vn.resolve(t);if(!q(r,i))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=r;for(let o of["",...Vn.relative(r,i).split(Vn.sep).filter(Boolean)]){o&&(a=Vn.join(a,o));let s=await ut.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await ut.realpath(a);if(n.length>0&&!q(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 ek(e){for(let t of e){let r=await ut.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!rH(t,r)||await ut.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function nH(e){if(!eH.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function aH(e){let t=tH.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function oH(e,t,r){return Or(Y(e,t),nH(r))}async function sH(e,t,r){let i=await iH(r,Vn.dirname(e)),n=await ut.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");let[a,o]=await Promise.all([ut.realpath(t),ut.realpath(e)]);if(!q(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":lh.O_RDONLY|lh.O_NOFOLLOW|lh.O_NONBLOCK,c=await ut.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(),ut.lstat(e),ut.realpath(e)]);if(await ek(i),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Sl(n,l)||!Sl(l,u))throw new Error("Native check receipt changed while opening");let p=[],f=0,m=Buffer.allocUnsafe(16*1024);for(;;){let b=await c.read(m,0,m.length,null);if(b.bytesRead===0)break;f+=b.bytesRead,p.push(Buffer.from(m.subarray(0,b.bytesRead)))}let[h,v,g]=await Promise.all([c.stat(),ut.lstat(e),ut.realpath(e)]);if(await ek(i),!v.isFile()||v.isSymbolicLink()||g!==o||!q(a,g)||!Sl(l,h)||!Sl(l,v))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(p,f).toString("utf8"))}finally{await c.close()}}async function tk(e,t,r){let i=aH(r),n=Y(e,t),a=oH(e,t,i),o=we(e,a);await K(o,a);let s=XN(await sH(a,n,o));if(s.change!==t||s.receiptHash!==i)throw new Error("Native check receipt ref/hash/change mismatch");return s}ti();Se();Ri();var Bo=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};yn();Ro();Ii();var R9=64*1024;var P9=3600*1e3;var _9=uH(lH);var dH=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function rk(e,t){let r=[];for(let i of dH){let n=e.bindings[i],a=t[i];n!==a&&r.push(`${i}: expected ${JSON.stringify(a)}, got ${JSON.stringify(n)}`)}return{ok:r.length===0,mismatches:r}}async function ik(e){if(e.receipt.kind!=="static-inspection")return null;let t=await tk(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}Ro();var ii=class extends Error{details;constructor(t){let r=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(i=>`${i.ref}${i.acceptanceId?`[${i.acceptanceId}]`:""} -> ${i.mismatches.join("; ")}`).join(" | ")}`;super(r),this.name="NativeVerificationReceiptBindingError",this.details=t}};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 fH(e){let t=pH(e.bundle.baseline),r=await _p(e.paths,t,{origin:"explicit",now:e.now});return Cf({baseline:t,current:r,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason,externalDrift:e.bundle.authority.externalDrift}).scope.currentProjectionHash}async function ak(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await Po(e.paths,e.state.name,e.state.implementation_scope),r=await En({changeDir:Ne(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),i=await fH({paths:e.paths,bundle:t,now:e.now}),n=[];return r.contract.contractHash!==t.scope.contractHash&&n.push("verification-contract-stale"),i!==t.scope.currentProjectionHash&&n.push("verification-implementation-stale"),{bundle:t,contract:r.contract,contractHash:r.contract.contractHash,acceptanceHash:r.contract.acceptanceHash,findingCodes:n}}async function ok(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await ak(e),r=[...new Set(t.findingCodes)].sort();return{freshness:r.length===0?"fresh":"stale",findingCodes:r}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"]}}}async function hH(e){let t=await ne({root:Ne(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:lw(t.text)}}function mH(e){let{receipt:t,implementationScope:r}=e,i=[],n=xf({baseline:r.baseline,current:r.current,declaredArtifacts:r.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!==r.scope.scopeHash||t.implementation.expectedSnapshotHash!==r.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==r.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==r.scope.currentProjectionHash||t.counts.filesSelected!==n.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==n.length||t.counts.bytesScanned!==a))&&i.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&i.push("verification-receipt-outcome-mismatch"),i}function vH(e){return{change:e.state.name,sourceRevision:e.sourceRevision??e.state.revision,contractHash:e.contractHash,scopeHash:e.implementationScope.scope.scopeHash,snapshotHash:e.implementationScope.scope.currentProjectionHash,artifactHash:Of(e.implementationScope.scope.declaredArtifacts)}}async function nk(e){let t=await _o(e.paths,e.state.name,e.ref),r=[];t.role!==e.role&&r.push(`role: expected ${e.role}, got ${t.role}`);let i=rk(t,e.expectedBindings);if(r.push(...i.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&r.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),r.length>0)throw new ii([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:r}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let n=await ik({paths:e.paths,state:e.state,receipt:t});if(n){let a=mH({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 gH(e){let t=vH({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),r=[];for(let i of e.requiredReceiptRefs){let n=await nk({...e,ref:i,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof ii)return r.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 i of e.trace.entries)if(i.status!=="missing")for(let n of i.evidenceRefs){let a=await nk({...e,result:i.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:i.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof ii)return r.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(i.status==="failed"&&a.status==="passed")throw new Error("Native failed acceptance evidence must reference a non-passing receipt")}}if(r.length>0)throw new ii(r)}function uh(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function dh(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:uh(e.state.verification_result,"missing"),envelope:null};try{let[t,r]=await Promise.all([ak(e),Hn(e.paths,e.state.name,e.state.verification_evidence)]);if(r.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:uh(e.state.verification_result,"stale"),envelope:null};let i=await hH({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),n=[...t.findingCodes];(i.hash!==r.reportHash||i.ref!==r.reportRef)&&n.push("verification-report-stale"),(r.result!==e.state.verification_result||r.implementationScopeRef!==e.state.implementation_scope||r.partialAllowanceRef!==e.state.partial_allowance||r.sourceRevision>=e.state.revision||r.contractHash!==t.bundle.scope.contractHash||r.acceptanceCriteriaHash!==t.acceptanceHash)&&n.push("verification-state-mismatch");try{await gH({paths:e.paths,state:e.state,result:r.result,trace:r.acceptanceTrace,requiredReceiptRefs:r.requiredReceiptRefs,contractHash:r.contractHash,implementationScope:t.bundle,sourceRevision:r.sourceRevision})}catch{n.push("verification-receipt-invalid")}let a=[...new Set(n)].sort(),o=a.length>0?"stale":r.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:r.contractHash,acceptanceHash:r.acceptanceCriteriaHash,implementationScopeHash:r.implementationScopeHash,reportHash:r.reportHash,envelopeHash:r.envelopeHash,partialAllowanceHash:r.partialAllowanceHash,skippedAcceptanceCount:r.acceptanceTrace.skipped},envelope:r}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:uh(e.state.verification_result,"invalid"),envelope:null}}}function yH(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function ck(e){try{return await wH.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function NH(e,t){try{return(await ne({root:e,ref:t,maxBytes:null})).hash}catch(r){if(r.code==="ENOENT")return null;throw r}}async function bH(e,t,r){let i=ao(e,r.capability);if(!q(e.nativeRoot,i))throw new Error(`Native canonical spec escapes its root: ${r.capability}`);let n=sk.relative(e.nativeRoot,i).replaceAll("\\","/"),a=await NH(e.nativeRoot,n),o=null;if(r.operation!=="remove"){if(!r.source)throw new Error(`Native proposed spec is missing: ${r.capability}`);o=(await ne({root:Ne(e,t),ref:r.source,maxBytes:null})).hash}return{capability:r.capability,operation:r.operation,expectedBaseHash:r.operation==="create"?null:r.base_hash,actualBaseHash:a,proposedHash:o}}async function kH(e,t){return ck(Kf(e,t))}async function ph(e){let t=e.now??new Date,r=await sr(e.paths,e.name),i=await or(e.paths,e.name),n=await Te(e.paths.projectRoot),a=yH(r.name,t),o=sk.resolve(e.paths.nativeRoot,...a.split("/"));if(!q(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,p,f]=await Promise.all([Promise.all(r.spec_changes.map(m=>bH(e.paths,r.name,m))),dh({paths:e.paths,state:r,now:t}),kl(e.paths,r.name),Fc(e.paths,r.name),gy(e.paths,r.name),kH(e.paths,r.name),ck(o)]);return zb({change:r.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:r.schema,revision:r.revision,phase:r.phase,archived:r.archived,pendingJournal:u||d||p,targetRef:a,targetExists:f,specs:s,evidence:c.evidence,workspace:i?.schema==="comet.native.workspace.v3"?{schema:i.schema,isolation:i.isolation,changeBranch:i.changeBranch,targetBranch:i.targetBranch,finish:i.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}U();ti();Ro();Ii();async function SH(e,t){let r=Y(e,t.name),i=await bn(r);if(!i||!t.run_id||i.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let n=await jc(r,i.checkpointRef);if(!n||n.runId!==i.runId||n.stateVersion!==i.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await Ni(r,i.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:i.runId}}async function EH(e,t){let r=await SH(e,t);return{committed:r,latest:Nb(r),history:yb(r)}}async function lk(e,t,r){if(t.phase!=="build"||t.verification_result!=="fail")return null;let i=await EH(e,t),n=i.latest;if(!n)return null;let a=i.history.filter(c=>c.kind==="failure"),o=a.length>=r,s=n.disposition==="hard-stop"&&!o?"continue":n.disposition;return{disposition:o?"hard-stop":s,signatureHash:n.signatureHash,overrideRecorded:i.history.some(c=>c.kind==="override"&&c.signatureHash===n.signatureHash),failedAcceptanceIds:[...n.failedAcceptanceIds],failedCheckIds:[...n.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:r,remainingVerifyFailures:Math.max(0,r-a.length)}}ti();wt();U();function Fo(e,t){try{return Ha(e,t)}catch{return}}var mr=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function CH(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function RH(e){return(await ub(e))?.change??null}function PH(e,t,r=!1,i){return gl({state:e,archiveReady:t,evidenceRetreat:r}).command}async function _H(e,t){let r=Ne(e,t.name),i=[...(await Lc(r,t.brief)).findings,...(await Cy(e,t)).findings,...await db(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await Cc(e,t.name);if(n===null)i.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await Uw(e,n);a.complete||i.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){i.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${n.message}`})}if(t.phase==="build")try{let n=await En({changeDir:r,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==n.contract.contractHash&&i.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){i.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${n.message}`})}try{await Ab(e,t.name)&&i.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(n){i.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${n.message}`})}return t.verification_report?i.push(...(await Vp(r,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&i.push({code:"verification-report-missing",message:"Native change has no verification report"}),i}async function fh(e,t,r){let i=await RH(e)===t,n=await Kd(e,t),a=await to(e,t),o;try{let y=await Fp(e,t);if(y.status==="migration-required"&&y.state)return{name:t,artifacts:Fo(e,t),phase:y.state.phase,revision:"revision"in y.state?y.state.revision:null,approval:y.state.approval,verificationResult:y.state.verification_result,specChanges:y.state.spec_changes.length,selected:i,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:y.schema,migrationRequired:!0,minimumRuntimeVersion:y.minimumRuntimeVersion,error:y.message};if(y.status!=="current"||!y.state)return{name:t,artifacts:Fo(e,t),phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:i,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:y.schema,minimumRuntimeVersion:y.minimumRuntimeVersion,error:y.message??`Native change ${t} is incompatible`};o=y.state}catch(y){return{name:t,artifacts:Fo(e,t),phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:i,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:y.message}}if(n.status!=="available"){let y={code:n.status==="missing"?"runtime-missing":"runtime-storage-invalid",message:n.status==="missing"?`Native Runtime is missing; continue ${o.name} to rebuild local execution state`:n.message??"Native Runtime storage is invalid",path:n.path},C=eh({paths:e,state:o,findings:[y]}),O=gl({state:o,findings:C});return{name:o.name,artifacts:Fo(e,o.name),phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:i,nextCommand:O.command,archiveReady:!1,inspection:{freshness:"stale",codes:[y.code],reasonCount:1,codesTruncated:!1},findingSummary:th(C),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:O,workspace:a,runtime:n,...r?.details?{findings:C}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:y.message}:{}}}let s=await Mb({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await lk(e,o,r?.maxVerifyFailures??5),c&&(c.disposition==="manual-stop"||c.disposition==="hard-stop")){let y=c.disposition==="hard-stop"?"repair-iteration-limit":c.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";l.push({code:y,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(r?.details&&(o.phase==="build"||o.phase==="verify"||o.phase==="archive"))try{let y=await En({changeDir:Ne(e,o.name),briefRef:o.brief,specChanges:o.spec_changes}),C=new Map;if(o.phase==="build"&&o.verification_result==="fail"&&o.verification_evidence){let Q=await Hn(e,o.name,o.verification_evidence);for(let Pe of Q.acceptanceTrace.entries)C.set(Pe.acceptanceId,Pe.status==="failed"?"failed":Pe.status==="missing"?"missing":"satisfied")}let O=ow({criteria:y.contract.acceptance,acceptanceHash:y.contract.acceptanceHash,verificationStatuses:C,failedCheckIds:c?.failedCheckIds??[],...r.acceptanceCursor?{cursor:r.acceptanceCursor}:{}}),j=O.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",O.nextCursor,"--project-root",e.projectRoot]:null;u={...O,...j?{nextPageCommand:CH(j),nextPageArgs:j}:{}}}catch(y){if(r.acceptanceCursor)throw y;u=void 0}let d=[];if(r?.includeConflictFindings!==!1)try{let y=await kl(e,o.name,{tolerateInvalidSiblings:!0});d.push(...y.findingCodes.map(C=>({code:C,message:`Native change overlap is visible in the current root: ${C}`})))}catch{d.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let p=[];try{let y=await or(e,o.name);if(y)if(y.schema==="comet.native.workspace.v3"){let C=await Sn({paths:e,identity:y});C.state==="drifted"&&C.code&&p.push({code:C.code,message:C.message??"Native workspace binding is no longer valid"})}else{let C=await Hc({paths:e,identity:y});p.push(...C.findingCodes.map(O=>({code:O,message:`Native workspace advisory changed: ${O} (${C.driftComponents.join(", ")||"no-component"})`})))}}catch{p.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let f=[],m=!1;if(o.phase==="verify"){let y=await ok({paths:e,state:o});m=y.freshness!=="fresh",f.push(...y.findingCodes.map(C=>({code:C,message:`Native Verify implementation scope is not current: ${C}`})))}let h=null,v=[];if(o.phase==="archive")try{h=await ph({paths:e,name:o.name}),v.push(...h.findingCodes.map(y=>({code:y,message:`Native Archive is blocked: ${y}`})))}catch{v.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let g=[...await _H(e,o),...s.findings,...d,...p,...f,...l,...v].filter((y,C,O)=>O.findIndex(j=>j.code===y.code&&j.path===y.path)===C),b=eh({paths:e,state:o,findings:g}),k=b.filter(y=>!kn(y.code)),N=o.phase==="archive"&&h?.ready===!0&&k.length===0,x=m||o.phase==="archive"&&(h?.findingCodes??[]).some(y=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(y)),w=b.some(y=>y.code==="trajectory-tail-incomplete"||y.code==="trajectory-invalid"||y.requiredAction==="return-to-bound-working-directory"||y.requiredAction==="repair-workspace-binding"),S=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",E=b.find(y=>y.severity==="error");return{name:o.name,artifacts:Fo(e,o.name),phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:i,nextCommand:w||S?null:PH(o,N,x,r?.clarificationMode),archiveReady:N,inspection:s.inspection,findingSummary:th(b),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:gl({state:o,findings:b,archiveReady:N,evidenceRetreat:x,clarificationMode:r?.clarificationMode}),workspace:a,runtime:n,repair:c,...r?.details?{...u?{acceptancePage:u}:{},findings:b.slice(0,50),inspectionDetails:s.inspectionDetails,checkpointDetails:s.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:Nl,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:b.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...E?{error:E.message}:{}}}async function uk(e){let t;try{t=await Np({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[],i=await xH.opendir(e.changesDir);try{for await(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink())&&(r.push(n.name),r.length>mr.maxChanges))throw new Error(`Native status exceeds ${mr.maxChanges} visible changes`)}finally{await i.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),r.sort()}U();var mh=Kt(It(),1);ot();ue();et();gt();import{promises as AH}from"node:fs";import hh from"node:path";var El=class extends Error{};async function Cl(e,t){let r=await ne({root:e.nativeRoot,ref:hh.relative(e.nativeRoot,t).replaceAll("\\","/"),maxBytes:null,includeHash:!1}),i=(0,mh.parse)(r.text);if(["comet.native.v1","comet.native.v2","comet.native.v3"].includes(i?.schema))throw new El("Historical Native schema");return{projectRoot:e.projectRoot,file:t,state:qe(i)}}async function pk(e,t,r){let i;try{i=await AH.readdir(e.archiveDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return[];throw a}if(i.length>4096)throw new Error("Native archive discovery exceeds 4096 records");let n=[];for(let a of i){if(!a.isDirectory()||a.isSymbolicLink())continue;let o=/^\d{4}-\d{2}-\d{2}-(.+)$/u.exec(a.name)?.[1];if(r!==void 0&&o!==void 0&&o!==r)continue;let s=hh.join(e.archiveDir,a.name,"comet-state.yaml");try{let c=await Cl(e,s);c.state.archived&&c.state.status==="done"&&n.push(c)}catch(c){if(c.code==="ENOENT"||c instanceof El)continue;let l=a.name.replace(/^\d{4}-\d{2}-\d{2}-/u,"");t?.(l,`Native archive ${a.name} is unreadable: ${c.message}`)}}return n}function xl(e){return T("comet.native.status-record.v1",e)}function dk(e){let t=hh.relative(e.projectRoot,e.file).replaceAll("\\","/");try{let r=Ve(e.projectRoot,["log","-1","--format=%H","HEAD","--",t]);if(!r)return null;let i=qe((0,mh.parse)(Ve(e.projectRoot,["show",`${r}:${t}`])));return xl(i)===xl(e.state)?r:null}catch{return null}}function fk(e,t){if(!e.state.archived||e.state.status!=="done"||e.state.name!==t.state.name||e.state.created_at!==t.state.created_at)return!1;let r=dk(e),i=dk(t);if(!r||!i)return!1;try{return Ve(e.projectRoot,["merge-base","--is-ancestor",i,r]),!0}catch{return!1}}function hk(e,t){return e.state.archived&&t.state.archived&&xl(e.state)===xl(t.state)}import Sk from"node:path";import{promises as mk}from"node:fs";import IH from"node:path";ue();var TH=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),jH=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),$H=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task","builderFailureCount"]),OH=new Set(["status","summary"]);function Rl(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Pl(e,t,r,i=new Set){let n=new Set(Object.keys(e)),a=[...t].filter(s=>!n.has(s)&&!i.has(s)),o=[...n].filter(s=>!t.has(s));return a.length===0&&o.length===0?null:`${r} fields must be exact (missing: ${a.join(", ")||"none"}; unexpected: ${o.join(", ")||"none"})`}function HH(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((r,i)=>r===t[i])}function ji(e,t,r){return{status:"incompatible",file:e,snapshot:t,message:r}}function DH(e,t,r,i){let n=Rl(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=Pl(n,TH,"Native Supervisor overlay");if(a)return a;if(i.stateVersion!==1)return"Native Supervisor overlay stateVersion is not 1";if(i.parent!==t.name)return`Native Supervisor overlay parent ${i.parent} does not match ${t.name}`;let o=Rl(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=Pl(o,jH,"Native Supervisor integration");if(s)return s;if(i.integration.headCommit!==i.integration.targetCommit)return"Native Supervisor integration headCommit has advanced beyond targetCommit";if(!Array.isArray(n.history)||n.history.length!==0)return"Native Supervisor overlay history is not empty";let c=Rl(n.finalVerification,"Native Supervisor finalVerification");if(!c)return"Native Supervisor finalVerification must be an object";let l=Pl(c,OH,"Native Supervisor finalVerification");if(l)return l;if(i.finalVerification.status!=="pending"||i.finalVerification.summary!==null)return"Native Supervisor final verification already contains progress";if(!Array.isArray(n.children))return"Native Supervisor children must be an array";if(n.children.length!==r.children.length)return"Native Supervisor child count does not match the legacy children contract";for(let[u,d]of n.children.entries()){let p=Rl(d,`Native Supervisor child ${u}`);if(!p)return`Native Supervisor child ${u} must be an object`;let{acceptanceScope:f,contractHash:m,...h}=p,v=Pl(h,$H,`Native Supervisor child ${u}`,new Set(["builderFailureCount"]));if(v)return v;let g=r.children[u],b=g.covers.length>0?g.covers.map(N=>({id:N,source:r.acceptance_index?.[N]?.source??"brief.md",text:r.acceptance_index?.[N]?.text??N})):[{id:`child:${g.name}`,source:"children.yaml",text:g.summary??g.name}];if(f!==void 0&&JSON.stringify(f)!==JSON.stringify(b)||m!==void 0&&m!==T("comet.native.supervisor-contract.v1",r))return`Native Supervisor child ${g.name} acceptance scope does not match the legacy contract`;if(p.name!==g.name||p.summary!==g.summary||!HH(p.dependsOn,g.depends_on))return`Native Supervisor child ${g.name} does not match the legacy children contract`;let k=g.depends_on.length===0?"ready":"pending";if(p.status!==k)return`Native Supervisor child ${g.name} has progressed beyond its initial ${k} status`;if(p.baseCommit!==null||p.candidateCommit!==null||p.verifiedCommit!==null||p.integrationCommit!==null||p.verification!==null||p.blocker!==null||p.projectRoot!==null||p.task!==null)return`Native Supervisor child ${g.name} contains execution progress`;if((p.builderFailureCount??0)!==0)return`Native Supervisor child ${g.name} contains Builder failure progress`;if(!Array.isArray(p.checks)||p.checks.length!==0)return`Native Supervisor child ${g.name} contains integration checks`}return null}async function vk(e){let t=go(e.paths,e.state.name),r;try{let c=await mk.lstat(t);if(!c.isFile()||c.isSymbolicLink())return ji(t,"","Native Supervisor overlay is not a regular file");r=await mk.readFile(t,"utf8")}catch(c){return c.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:ji(t,"",`Native Supervisor overlay cannot be read: ${c.message}`)}let i;try{i=JSON.parse(r)}catch(c){return ji(t,r,`Native Supervisor overlay is invalid JSON: ${c.message}`)}let n=IH.join(e.paths.changesDir,e.state.name),a;try{a=await Vt({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:c})=>c),policy:"advisory"})}catch(c){return ji(t,r,`Native children contract cannot be validated; restore children.yaml and retry next: ${c.message}`)}if(!a||a.contract.schema!=="comet.native.children.v1")return{status:"compatible",file:t,message:"The current Native children contract is not legacy children.v1",snapshot:r};let o;try{o=await Ue(e.paths,e.state.name)}catch(c){return ji(t,r,`Native Supervisor overlay is invalid: ${c.message}`)}if(!o)return ji(t,r,"Native Supervisor overlay disappeared during inspection");let s=DH(i,e.state,a.contract,o);return s?ji(t,r,s):{status:"repairable-legacy-overlay",file:t,message:"An exact unstarted v2 Supervisor overlay is stale beside a legacy children.v1 contract",snapshot:r}}za();Ci();function be(e,t,r){return e.language==="zh-CN"?r:t}function BH(e,t,r,i){let n=a=>({required:!1,message:null,suggestedReply:null,agentInstruction:a});if(e.phase==="shape"&&e.status==="await-user"&&e.loop.next_action==="confirm-shape")return t?{required:!0,message:be(e,"Shape is ready. Confirm the complete plan and choose A) Multi-session coordination (recommended), or B) Single-session progression in one reply.","Shape 已整理完成。请确认完整方案,并在同一次回复中选择 A)多会话协作(推荐),或 B)单会话推进。"),suggestedReply:be(e,"Confirm the plan and use A","确认方案,按 A 开始"),agentInstruction:be(e,"First present the target, scope, key decisions, acceptance criteria, non-goals, child responsibilities and dependencies, and both coordination choices. Execute the matching confirm-shape alternative only when the user explicitly accepts this complete Shape and chooses its mode. Choosing a mode alone, additions, or corrections are not full confirmation; retain that choice and ask only for the missing decision. Do not run --confirmed before full confirmation.","先展示目标、范围、关键决定、验收标准、非目标、各 Child 的职责与依赖,以及两种推进方式。只有用户明确同意当前完整 Shape 并选择推进方式后,才执行对应的 confirm-shape 选项。仅选择推进方式、补充或修改要求都不算完整确认;保留已选方式,只补问缺少的决定。完整确认前不要运行 --confirmed。")}:e.language==="zh-CN"?{required:!0,message:"Shape 已整理完成。请确认目标、范围、关键决定、验收标准和非目标是否准确;明确确认后才会进入 Build。",suggestedReply:"确认进入 Build",agentInstruction:"先用自然语言简要展示目标、范围、关键决定、验收标准和非目标,再转述 message 并等待用户明确确认。只有用户明确同意当前完整 Shape 时,才执行 commandAlternatives 中的 confirm-shape;补充或修改要求不算确认。不要展示机器状态或提前运行 --confirmed。"}:{required:!0,message:"Shape is ready. Confirm that the target, scope, key decisions, acceptance criteria, and non-goals are accurate; Build starts only after explicit confirmation.",suggestedReply:"Confirm and enter Build",agentInstruction:"First present a concise natural-language summary of the target, scope, key decisions, acceptance criteria, and non-goals. Then relay message and wait for explicit user confirmation. Run confirm-shape from commandAlternatives only when the user explicitly accepts the complete current Shape; additions or corrections are not confirmation. Do not expose machine state or run --confirmed early."};if(t&&e.phase==="shape"&&e.status==="active")return n(be(e,"Complete the Shape documents and child plan, resolve blocking questions, then execute prepare-shape-confirmation. Its persisted response combines complete Shape confirmation and coordination choice in one user decision. If the user already chose only a mode, include that --coordination-mode when preparing and ask only for complete Shape confirmation afterward.","完成 Shape 文档和 Child 计划,解决阻塞问题后执行 prepare-shape-confirmation。持久化后的响应会让用户一次确认完整 Shape 并选择推进方式。如果用户已经仅选择了推进方式,准备时附上对应的 --coordination-mode,随后只确认完整 Shape。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready"&&e.loop.next_action!=="await-verifier-result")return n(be(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"){let a=i==="confirmed"?be(e,"The Verifier has confirmed startup. Continue waiting on the same host task and use its actual progress.","Verifier 已确认启动。继续等待同一个宿主任务,并使用该任务的实际进度。"):be(e,"Check whether the host accepted the startup call and locate the task for the current verifierExecutionRef. If the call has not been made, start the dispatched task once; if the host accepted it, check that same task and let the Verifier submit its startup receipt. A missing receipt alone does not prove failure. If local startup state is unavailable, recover the host task context before deciding whether startup is needed.","先核实宿主是否接受了启动调用,并找到当前 verifierExecutionRef 对应的任务。尚未调用时启动已派发的任务一次;宿主已接受时检查同一个任务,由 Verifier 提交启动回执。仅缺少回执不能证明执行失败。本地启动记录不可用时,先恢复宿主任务上下文,再判断是否需要启动。");return n(`${a} ${be(e,"Keep the same dispatched Verifier while it is active. A wait-tool timeout is not an execution timeout: check task progress and continue waiting; do not cancel, interrupt, or spawn a replacement just because a wait returned without a result. Request progress without telling the Verifier to stop inspecting. Only after confirmed task failure, a host-reported execution timeout, loss, or termination without a usable result, immediately submit verifier-execution-error. Preserve completed evidence and explain the failure and changed recovery approach before retrying. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Forward the actual report, including risks and incomplete checks; never turn an uninspected candidate into pass. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","已派发的验收任务仍在运行时,继续使用同一个 Verifier。等待工具超时不等于执行超时:检查任务进度并继续等待,不得仅因一次等待没有结果就取消、中断或重新派发。询问进度时不要要求停止核查。仅在确认任务失败、宿主报告执行超时、任务丢失或结束后没有可用结果时,立即提交 verifier-execution-error;保留已完成证据,重试前说明失败原因及恢复方式的变化。只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。忠实传递原始报告,包括风险和未完成检查;没有核查当前候选不能判定通过。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。")}`)}if(e.status==="blocked"&&e.blockers.some(({resolution_action:a})=>a==="retry-verifier"))return e.loop.retry_epoch>=3?e.language==="zh-CN"?{required:!0,message:"自动重试验收已连续多轮未能取得结果,验证环境很可能不可用。请人工检查验证环境(subagent 配额、平台任务队列、网络),或使用 doctor --repair 评估该 change 状态。",suggestedReply:"人工检查验证环境",agentInstruction:"只向用户转述 message,等待用户完成人工检查后再继续。不要自动重试验收。"}:{required:!0,message:"Automatic verification retries have failed across multiple rounds; the verification environment is likely unavailable. Inspect the environment manually (subagent quota, platform task queue, network), or use doctor --repair to assess the change state.",suggestedReply:"Inspect the verification environment",agentInstruction:"Relay message to the user and wait for a manual environment check before continuing. Do not retry verification automatically."}: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 o=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",s=o?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。注意:预算不会重置,选择继续修复后,下一次验收失败会再次暂停。",c=o?"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:s,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:c,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."}}if(e.phase==="verify"&&e.status==="await-user"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass")return{required:!0,message:be(e,"The reported verification passed, but this platform cannot confirm an independent Verifier execution. Review the result and choose whether to accept it for Archive, revise the implementation, or revise the requirements."+(e.workspace.isolation!=="current"&&e.workspace.finish===null?" If accepting, also choose: keep the workspace, merge locally, push the branch, or push and create a PR. You may accept the result and defer the finish choice.":""),"当前验收报告已通过,但当前平台无法确认验收是否独立执行。请检查结果,并选择接受结果进入归档、继续修改实现,或调整需求。"+(e.workspace.isolation!=="current"&&e.workspace.finish===null?" 接受时可一起选择:保留工作区、本地合并、推送分支,或推送并创建 PR;也可以先接受结果,稍后再选择收尾方式。":"")),suggestedReply:be(e,"Accept the result","接受结果"),agentInstruction:be(e,"Summarize the result and verification evidence, relay the message, and wait for an explicit user decision. Only then execute the matching commandAlternative. Do not accept the result on the user’s behalf.","简要说明交付结果和验收证据,转述 message,并等待用户明确选择后再执行对应的 commandAlternative。不要替用户接受结果。")};if(e.phase==="build"&&e.status==="active"){let a=r?.children.some(({status:l})=>l==="blocked")??!1,o=r?.children.some(({status:l})=>l==="needs-reverify")??!1,s=r?.children.some(({status:l})=>l==="ready"||l==="active")??!1,c=r?.children.some(({status:l,builderFailureCount:u})=>l==="blocked"&&(u??0)>=Zc)??!1;return a&&!o&&!s&&!c?e.language==="zh-CN"?{required:!0,message:"Supervisor 子任务暂时无法启动,已暂停自动重试以避免流程循环。请先根据子任务 blocker 修复工作区、分支或依赖;修复完成后重新运行最新的 next 继续流程。代码和已有证据已保留。",suggestedReply:"修复 blocker 后继续",agentInstruction:"向用户说明子任务 blocker 和需要先完成的外部修复;不要反复执行 next,也不要创建替代任务。用户确认工作区或依赖已修复后,再重新读取 status 并执行最新 continuation。"}:{required:!0,message:"Supervisor child dispatch is paused because every remaining child is blocked. Automatic retries are stopped to avoid a loop. Resolve the recorded child blocker (workspace, branch, or dependency) first, then read the latest status and continue; code and completed evidence are preserved.",suggestedReply:"Resolve the blocker and continue",agentInstruction:"Explain the child blocker and the required external repair to the user. Do not repeatedly run next or spawn replacement tasks. After the user confirms the workspace or dependency is fixed, read status again and execute the latest continuation."}:n(be(e,"Implement the complete confirmed brief and Spec scope, then review every acceptance ID with its implementation and evidence before handoff. Fill acceptance_review from this audit; derive remaining work from it. Do not submit a partial candidate just to obtain verification feedback. Run focused checks; a separate pre-review is optional. If review is useful, retain the same Reviewer for focused repair follow-ups. Submit the completed candidate for one complete independent verification and release completed helper tasks.","完成已确认的 brief 和 Spec 全部范围,交接前逐项核对所有验收 ID 的实现和证据,填写 acceptance_review,并由这份自查生成剩余工作。不得提交未完成的候选来试探验收反馈。开发期运行相关检查,额外预审为可选项;确需审查时,保留同一个 Reviewer 复核修复及受影响范围。全部完成后提交一次完整独立验收,及时释放已完成的辅助任务。"))}return n(be(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 FH(e){let t=e.workspace.change_branch??"<change-branch>",r=e.workspace.target_branch??"<target-branch>";return e.language==="zh-CN"?{required:!0,message:`当前 change 位于 ${t},目标分支为 ${r}。请选择一次工作区收尾方式:A) 保留工作区;B) 本地合并;C) 推送分支;D) 推送并创建 PR;E) 暂不归档。选择 A-D 后 Runtime 会完成预检,检查通过后按所选方式归档;选择 E 将保留当前 change 等待稍后继续。`,suggestedReply:"回复 A、B、C、D 或 E",agentInstruction:"向用户展示五种收尾方式及实际影响,等待用户选择。选择 A-D 时执行对应 commandAlternatives 的完整命令,Runtime 会在归档前检查状态和证据;选择 E 时停止,不运行 Archive 命令。按用户的明确选择执行 finish。"}:{required:!0,message:`This change is on ${t} and targets ${r}. Choose one workspace finish: A) keep the workspace; B) merge locally; C) push the branch; D) push and create a PR; or E) defer Archive. For A-D, Runtime will run preflight and archive with the selected finish when the checks pass; E keeps the current change for later.`,suggestedReply:"Reply A, B, C, D, or E",agentInstruction:"Show all five finish choices and their actual effects, then wait. For A-D, execute the matching complete commandAlternative; Runtime checks state and evidence before archiving. For E, stop without running an Archive command. Use the finish explicitly selected by the user."}}function LH(e){return[...[{finish:"keep",name:"keep-workspace",description:["保留当前分支和目录;完成归档提交,不合并、不推送、不创建 PR。","Keep the current branch and directory; create the archive commit without merging, pushing, or creating a PR."]},{finish:"merge",name:"merge-locally",description:["完成归档提交,并把 change 分支本地合并到目标分支;不推送、不创建 PR。","Create the archive commit and merge the change branch locally into the target branch without pushing or creating a PR."]},{finish:"push",name:"push-branch",description:["完成归档提交并推送 change 分支;不合并到目标分支、不创建 PR。","Create the archive commit and push the change branch without merging into the target branch or creating a PR."]},{finish:"pull-request",name:"push-pull-request",description:["完成归档提交、推送 change 分支,并以目标分支为基础创建 PR。","Create the archive commit, push the change branch, and create a PR against the target branch."]}].map(({finish:i,name:n,description:a})=>({name:n,stateVersion:e.state_version,expectedAction:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed","--finish",i,"--expected-state-version",String(e.state_version)],requiredInputs:[],inputOptions:[],description:be(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:be(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function Nk(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function $i(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function gk(){return{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}}function qH(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function wk(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function MH(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function VH(e){return["comet","native","next",e.change,"--summary","<summary>","--expected-state-version",String(e.stateVersion),"--expected-action","prepare-shape-confirmation"]}function Jt(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:Nk({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[$i("summary","--summary"),qH(e.name,e.flag)]}}function yk(e,t){return t.some(i=>/^verification\.md is (?:missing|stale|invalid)$/u.test(i))?[{name:"repair-verification-report",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],inputOptions:[],description:be(e,"Rebuild the Runtime-managed verification report, then rerun the Archive dry-run.","重建由 Runtime 管理的 verification.md,然后重新运行 Archive 预检。")}]:[]}function WH(e){return/^verification\.md is (?:missing|stale|invalid)$/u.test(e)}function _l(e){return[Jt({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Jt({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function zH(e){let t={"request-checks":"Choose when the Verifier needs additional Runtime checks.","final-result":"Choose when the Verifier has a result for every current scope ID.","verifier-execution-error":"Choose when a dispatched Verifier failed, was lost, or ended without a result.","verifier-unavailable":"Choose only when the platform has no usable independent Verifier capability."};return e.flatMap(r=>Array.isArray(r.template)?r.template.map(i=>{let n=i.response?.kind??i.kind;return{...r,name:n,required:!1,exclusiveGroup:"runner-input",description:t[n],template:i}}):[r])}function Lo(e,t,r={}){let i=MH(t)&&e.coordination_mode===void 0,n=BH(e,i,t,r.verifierStartup),a={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],requiresUserDecision:n.required,userCommunication:n},o=s=>({kind:s,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...a,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:o("none")};if(e.status==="await-user")return e.phase==="shape"&&e.loop.next_action==="confirm-shape"?{...a,disposition:"await-user",action:"confirm-shape",commandArgs:null,requiredInputs:["summary","shared-understanding-confirmation",...i?["coordination-choice"]:[]],inputOptions:[$i("summary","--summary")],commandAlternatives:i?uw.map(s=>{let c=Jt({name:`confirm-shape-${s}`,change:e.name,stateVersion:e.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"});return{...c,commandArgs:[...c.commandArgs,"--coordination-mode",s],requiredInputs:[...c.requiredInputs,"coordination-choice"],inputOptions:[...c.inputOptions,wk("coordination-mode","--coordination-mode",[s])]}}):[Jt({name:"confirm-shape",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"})],runnerAction:o("none")}:e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...a,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[$i("summary","--summary")],commandAlternatives:[...e.workspace.isolation!=="current"&&e.workspace.finish===null?["keep","merge","push","pull-request"].map(s=>{let c=Jt({name:`accept-result-${s}`,change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"});return{...c,commandArgs:[...c.commandArgs,"--finish",s]}}):[],Jt({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),..._l({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...a,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[$i("summary","--summary")],commandAlternatives:[Jt({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),Jt({name:"confirm-verifier-unavailable",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-verifier-unavailable",flag:"--confirmed",confirmationInput:"user-decision"})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...a,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[$i("summary","--summary")],commandAlternatives:[Jt({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),..._l({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...a,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[$i("summary","--summary")],commandAlternatives:_l({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,commandAlternatives:_l({change:e.name,stateVersion:e.state_version}),userCommunication:{...a.userCommunication,required:!0,message:e.blockers.length>0?e.blockers.map(({reason:s})=>s).join("; "):a.userCommunication.message,suggestedReply:e.blockers.length>0?e.blockers[0]?.resolution_action??null:a.userCommunication.suggestedReply},requiredInputs:["resolve-blocker"],runnerAction:o("none")};if(e.status==="blocked"){let s=e.blockers.some(({resolution_action:c})=>c==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?Nk({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:s?["summary"]:["repair-runtime"],inputOptions:s?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:o(s?"retry-verifier":"none")}}if(e.phase==="shape")return{...a,disposition:"continue",action:"prepare-shape-confirmation",commandArgs:VH({change:e.name,stateVersion:e.state_version}),requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...a,disposition:"continue",action:"repair",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["repair-child"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(t.allDone)return{...a,disposition:"continue",action:"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:e.acceptance.map(({id:m})=>m),acceptance_review:e.acceptance.map(({id:m})=>({id:m,status:"not-implemented",evidence:[],note:"<implementation and evidence summary>"})),checks:[{name:"<check-name>",result:"not-run",note:null}],verification_checks:[gk()],known_limits:[]}}],runnerAction:o("builder-handoff")};let s=t.children.find(({status:m})=>m==="verified");if(s){let m=r.supervisorIntegrationRetryIds;return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["supervisor-integration-checks"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-integrate",child:s.name,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}],...m&&m.length>0?{retry_check_ids:[...m]}:{}}}],runnerAction:o("none")}}let c=t.children.some(({status:m})=>m==="blocked"||m==="needs-reverify"),l=t.children.some(({status:m})=>m==="needs-reverify"),u=t.children.some(({status:m})=>m==="ready"||m==="active"),d=t.supervisorStateVersion===void 0?null:t.children.find(m=>m.status==="blocked"&&(m.builderFailureCount??0)>=Zc)??null,p=d===null?null:{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-retry-builder",child:d.name,stateVersion:t.supervisorStateVersion},description:be(e,"Explicitly authorize one fresh Builder attempt after the Builder failure budget was exhausted.","Builder 失败预算已耗尽;明确授权后才能重新开始一次 Builder 尝试。")},f=c&&!l&&!u&&p===null;return{...a,disposition:f?"blocked":"continue",action:"advance-children",commandArgs:f?null:p!==null?["comet","native","next",e.name,"--runner-input","<temporary-json-file>"]:["comet","native","next",e.name,"--summary","<summary>",...e.coordination_mode==="single-session"?["--max-parallel","1"]:[]],requiredInputs:f?[]:p!==null?["supervisor-builder-retry-json-file"]:["ready-children"],inputOptions:f?[]:p!==null?[p]:[$i("summary","--summary")],runnerAction:o("none")}}return{...a,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:e.acceptance.map(({id:s})=>s),acceptance_review:e.acceptance.map(({id:s})=>{let c=e.builder_handoff?.acceptance_review?.find(l=>l.id===s);return c?{...c,evidence:[...c.evidence],...e.loop.previous_unresolved_ids.includes(s)?{status:"implemented-no-evidence",evidence:[],note:"<current repair and evidence summary>"}:{}}:{id:s,status:"not-implemented",evidence:[],note:"<implementation and evidence summary>"}}),checks:[{name:"<check-name>",result:"not-run",note:null}],verification_checks:[],known_limits:[]}}],runnerAction:o("builder-handoff")}}if(e.phase==="verify"){let s=e.loop.next_action==="await-verifier-result",c=!!e.children_contract_hash,l=gk();return!s&&r.retryCheckIds&&r.retryCheckIds.length>0?{...a,disposition:"continue",action:"retry-checks",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["retry-checks-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"retry-checks",check_ids:[...r.retryCheckIds]}}],runnerAction:o("retry-checks")}:{...a,userCommunication:!s&&c?{...a.userCommunication,agentInstruction:`${a.userCommunication.agentInstruction} ${be(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:a.userCommunication,disposition:"continue",action:s?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[s?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:zH([{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:s?[{kind:"verifier-response",candidateId:e.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[l]}},{kind:"verifier-response",candidateId:e.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"blocked",acceptance:[{id:"<acceptance-id>",result:"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:r.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:r.verifierExecutionRef??"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:r.verificationCheckPlans?r.verificationCheckPlans.map(u=>({...u,argv:[...u.argv]})):c?[l]:[]}}]),runnerAction:o(s?"await-verifier":"dispatch-verifier")}}if(e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived){let s=r.archiveMode??"archive-ready",l=e.workspace.isolation!=="current"&&e.workspace.finish===null;if(s==="blocked")return{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")};if(s==="preview"){if(r.archiveBlockers&&r.archiveBlockers.length>0){let u=yk(e,r.archiveBlockers)[0];return u&&r.archiveBlockers.every(d=>WH(d))?{...a,disposition:"continue",action:"repair",commandArgs:u.commandArgs,requiredInputs:[],inputOptions:[],runnerAction:o("none")}:{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],commandAlternatives:yk(e,r.archiveBlockers),runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}return l?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[wk("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...LH(e)],userCommunication:FH(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[Jt({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}import bk from"node:path";function kk(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function vh(e,t){let r=e.acceptance.reduce((i,n)=>({...i,[n.result]:i[n.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:r,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:kk(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},learning:{failureResolved:e.verification_result==="pass"&&e.history.some(i=>i.outcome==="fail"&&i.goal_cycle===e.loop.goal_cycle),...e.verification?{summary:kk(e.verification.summary.text)}:{},artifactRefs:t?["brief.md",...e.verification_report?[e.verification_report]:[],...e.spec_changes.map(i=>i.source).filter(i=>i!==null)].slice(0,16).map(i=>bk.relative(t.projectRoot,bk.join(t.changesDir,e.name,i)).replaceAll("\\","/")):[]},archived:e.archived}}U();function Ek(e,t,r){return`native-details-v2.${e}.${t}.${r.toString(36)}`}function xk(e,t,r){if(!e)return 0;let i=/^native-details-v2\.(\d+)\.(\d+)\.([0-9a-z]+)$/u.exec(e);if(!i||Number(i[1])!==t||Number(i[2])!==r)throw new Error("Native details cursor is stale or invalid");let n=Number.parseInt(i[3],36);if(!Number.isSafeInteger(n)||n<0)throw new Error("Native details cursor offset is invalid");return n}function Ck(e,t,r){return[...e.acceptance.map(i=>({kind:"acceptance",value:i})),...e.spec_changes.map(i=>({kind:"spec-change",value:i})),...e.builder_handoff?[{kind:"builder-handoff",value:e.builder_handoff}]:[],...e.verification?[{kind:"verification",value:e.verification}]:[],...e.history.map(i=>({kind:"history",value:i})),{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(i=>({kind:"supervisor-child",value:UH(i,r)})),...t.history.map(i=>({kind:"supervisor-history",value:KH(i,r)}))]:[]]}function Rk(e){return e.acceptance.reduce((t,r)=>({...t,[r.result]:t[r.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0})}function GH(e,t){let r=t?.execution;if(e.phase!=="verify"||e.status!=="active"||e.loop.next_action!=="await-verifier-result"||!r||r.stage!=="verifying"||r.actor!=="verifier"||r.status!=="running")return;let i=r.verifierStartedAt??null,n=Up(e,t??null);if(n===void 0)return;let a=n==="confirmed";return{attempt:e.loop.attempt,registeredAt:r.startedAt,confirmedAt:i,confirmation:a?"confirmed":"unconfirmed",...a?{}:{waitingMinutes:Math.max(0,Math.round((Date.now()-Date.parse(r.startedAt))/6e4))}}}function Al(e,t,r=ve(e.projectRoot)){let i=null;return t.workspace.change_branch!==null&&(r.isGitWorktree?r.currentBranch!==t.workspace.change_branch&&(i=`Expected branch ${t.workspace.change_branch}, current branch is ${r.currentBranch??"(detached)"}.`):i="The Native change requires a registered Git worktree."),i===null&&t.workspace.isolation==="worktree"&&!r.isSecondaryWorktree&&(i="The Native change requires its linked worktree."),{projectRoot:Sk.resolve(e.projectRoot),isolation:t.workspace.isolation,bindingState:i===null?"aligned":"mismatch",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:i}}function gh(e){let{state:t,paths:r}=e,i=e.finishJournal??null,n=vh(t),a=i!==null,o=i?.result?.message??"Native Archive completed, but workspace finish is still pending; retry the recorded finish command.",s=a?{...Lo(t),status:"blocked",disposition:"blocked",action:"archive",requiresUserDecision:!1,commandArgs:i?.result?.recoveryArgs??["comet","native","archive",t.name,"--confirmed"],requiredInputs:[],inputOptions:[],userCommunication:{required:!0,message:o,suggestedReply:null,agentInstruction:"Report the Git blocker and resolve it within the recorded delivery authorization, then retry the recorded Native workspace finish command. Ask the user only when new information or authorization is required; keep delivery pending until it succeeds."},runnerAction:{...Lo(t).runnerAction,kind:"none"}}:Lo(t),c=e.details?Ck(t,null,[]):[],l=xk(e.cursor,t.state_version,0),u=c.slice(l,l+32),d=l+u.length<c.length?Ek(t.state_version,0,l+u.length):null;return{schema:"comet.native.status.v2",name:t.name,artifacts:Ha(r,t.name),phase:t.phase,status:a?"blocked":t.status,stateVersion:t.state_version,archived:!0,archiveRef:Sk.relative(r.projectRoot,e.file).replaceAll("\\","/"),loop:t.loop,acceptance:Rk(t),unresolvedAcceptanceIds:n.unresolved_acceptance_ids,verificationResult:t.verification_result,blockers:a?[...n.blockers,{owner:"runtime",reason:o,acceptance_ids:[],resolution_action:"wait-external"}]:n.blockers,workspace:{projectRoot:r.projectRoot,isolation:t.workspace.isolation,bindingState:"aligned",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:null},localExecution:{status:"not-expected",operation:null},continuation:s,...e.details?{details:{stateVersion:t.state_version,items:u,nextCursor:d,nextPageArgs:d?["comet","native","status",t.name,"--details","--cursor",d,"--project-root",r.projectRoot,"--json"]:null}}:{}}}function JH(e,t){return[e.projectRoot,t.integration.worktree,...t.children.flatMap(r=>[r.projectRoot,r.task?.projectRoot])].filter(r=>!!r).map(r=>r.replaceAll("/","\\")).sort((r,i)=>i.length-r.length)}function Il(e,t){return e===null?null:t.reduce((r,i)=>r.replaceAll(i,"<worktree>").replaceAll(i.replaceAll("\\","/"),"<worktree>"),e)}function UH(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:Il(e.blocker,t),task:e.task?{...e.task,projectRoot:"<worktree>",baseCommit:"<redacted>",runId:"<redacted>"}:null}}function KH(e,t){return{...e,runId:e.runId?"<redacted>":null,summary:Il(e.summary,t)??""}}async function Pk(e){let t=await Yp(e),r=vh(t.state),i=t.state.status==="active"&&t.state.loop.stage!=="done",n=await wo({paths:e.paths,state:t.state}),a=await vk({paths:e.paths,state:t.state}),o=a.status==="repairable-legacy-overlay"||a.status==="incompatible"?null:await Ue(e.paths,e.name,{diagnostics:!0}),s=o?{...Al(e.paths,t.state,e.gitContext),projectRoot:"."}:Al(e.paths,t.state,e.gitContext),c=Lo(t.state,n,{verifierExecutionRef:Jp(t.state,t.local),verifierStartup:Up(t.state,t.localStatus==="available"?t.local:null),...t.local?{verificationCheckPlans:lb(t.local,t.local.workspace.projectRoot)}:{}}),l=s.bindingState==="mismatch"?{...c,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["return-to-bound-workspace"],runnerAction:{...c.runnerAction,kind:"none"}}:c,u=o?JH(e.paths,o):[],d=o?(()=>{let m=new Map(n?.children.map(w=>[w.name,w.status])??[]),h=w=>m.get(w.name)??w.status,v=o.children.filter(w=>h(w)==="pending"||h(w)==="ready").length,g=o.children.filter(w=>h(w)==="active"||h(w)==="verified").length,b=o.children.filter(w=>h(w)==="integrated"||h(w)==="archived").length,k=o.children.filter(w=>h(w)==="blocked"||h(w)==="needs-reverify").length,N=o.children.filter(w=>h(w)==="active"||h(w)==="blocked"||h(w)==="needs-reverify").slice(0,16).map(w=>({name:w.name,summary:w.summary,projectRoot:w.task?.projectRoot??w.projectRoot?"<worktree>":null,reason:Il(w.blocker,u)})),x=o.children.flatMap(({blocker:w})=>{let S=Il(w,u);return S?[S]:[]}).slice(0,16);return{targetSpecs:t.state.spec_changes.length,implementationChildren:o.children.length,waiting:v,working:g,integrated:b,blocked:k,active:N,agents:{working:o.children.filter(({task:w})=>w!==null).length,completed:b},risks:x,nextAction:o.finalVerification.status==="passed"?"final-delivery":o.finalVerification.status==="pending"&&b===o.children.length?"parent-verification":v>0?"dispatch-ready-child":k>0?"resolve-blocker":"continue-supervisor"}})():null,p=e.details?(()=>{let m=o?.stateVersion??0,h=Ck(t.state,o,u),v=xk(e.cursor,t.state.state_version,m),g=h.slice(v,v+32),b=v+g.length<h.length?Ek(t.state.state_version,m,v+g.length):null;return{items:g,nextCursor:b,supervisorStateVersion:m}})():null,f=o?{schema:o.schema,parent:o.parent,integration:{branch:o.integration.branch,targetBranch:o.integration.targetBranch},finalVerification:{status:o.finalVerification.status,summary:o.finalVerification.summary},summary:d}:null;return{schema:"comet.native.status.v2",name:t.state.name,artifacts:Ha(e.paths,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:Rk(t.state),unresolvedAcceptanceIds:r.unresolved_acceptance_ids,verificationResult:t.state.verification_result,blockers:o?[]:r.blockers,workspace:s,localExecution:(()=>{let m=GH(t.state,t.localStatus==="available"?t.local:null);return{status:i?t.localStatus:"not-expected",operation:t.localStatus==="available"?t.local?.execution??null:null,...m?{verifierStartup:m}:{}}})(),...n?{childSummary:n.children.reduce((m,h)=>({...m,[h.status]:(m[h.status]??0)+1}),{total:n.children.length}),readyChildren:n.readyChildren}:{},...f?{supervisor:f}:{},...a.status==="repairable-legacy-overlay"||a.status==="incompatible"?{supervisorOverlay:{status:a.status,message:a.message,repairCommand:a.status==="repairable-legacy-overlay"?`comet native doctor ${e.name} --repair`:null}}:{},continuation:l,...e.details?{details:{stateVersion:t.state.state_version,...o?{supervisorStateVersion:p.supervisorStateVersion}:{},items:p.items,nextCursor:p.nextCursor,nextPageArgs:p.nextCursor?["comet","native","status",t.state.name,"--details","--cursor",p.nextCursor,"--json","--project-root",e.paths.projectRoot]:null}}:{}}}import{accessSync as k3,constants as S3,promises as wh}from"node:fs";import Wn from"node:path";ae();Di();ot();il();Di();var _k="comet.native.workspace-finish.v1",Ik="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",Tk=new RegExp(`^${Ik}$`,"u"),XH=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,qo=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function Ak(e,t){if(!e.trim()||e.includes("\0"))throw new Error(`${t} must contain non-whitespace text and no NUL character`)}function QH(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace finish journal is invalid");let t=e;if(t.schema!==_k||typeof t.name!="string"||!Tk.test(t.name)||typeof t.transactionId!="string"||!XH.test(t.transactionId)||t.archiveDir!==null&&(typeof t.archiveDir!="string"||!Wn.isAbsolute(t.archiveDir))||!["pending","blocked"].includes(String(t.status))||typeof t.updatedAt!="string"||!Number.isFinite(Date.parse(t.updatedAt)))throw new Error("Native workspace finish journal is invalid");if(t.result!==null){if(!t.result||typeof t.result!="object"||Array.isArray(t.result))throw new Error("Native workspace finish journal result is invalid");let r=t.result;if(!["merge","push","pull-request","keep"].includes(String(r.action))||!["completed","kept","blocked"].includes(String(r.status))||!Array.isArray(r.blockedPaths)||r.blockedPaths.some(i=>typeof i!="string")||r.recoveryArgs!==null&&(!Array.isArray(r.recoveryArgs)||r.recoveryArgs.some(i=>typeof i!="string")))throw new Error("Native workspace finish journal result is invalid")}if(t.plan!==void 0){let r=t.plan;if(!r||typeof r!="object"||!["keep","merge","push","pull-request"].includes(r.finish)||!["current","branch","worktree"].includes(r.isolation)||![r.changeRoot,r.primaryRoot].every(i=>typeof i=="string"&&Wn.isAbsolute(i))||![r.changeBranch,r.targetBranch].every(i=>typeof i=="string"&&i.length>0)||r.targetRoot!==null&&(typeof r.targetRoot!="string"||!Wn.isAbsolute(r.targetRoot))||r.remote!==null&&typeof r.remote!="string"||typeof r.commitMessage!="string"||r.mergeMessage!==null&&typeof r.mergeMessage!="string")throw new Error("Native workspace finish journal plan is invalid");Ak(r.commitMessage,"commit-message"),r.mergeMessage!==null&&Ak(r.mergeMessage,"merge-message")}if(t.createdAt!==void 0&&(typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))))throw new Error("Native workspace finish journal creation identity is invalid");if(t.commit!==void 0){let r=t.commit;if(!r||!qo.test(r.parent)||!Array.isArray(r.paths)||!r.paths.every(i=>typeof i=="string"&&i.length>0&&!Wn.posix.isAbsolute(i)&&!Wn.win32.isAbsolute(i)&&!i.split("/").includes(".."))||!Array.isArray(r.entries)||!r.entries.every(i=>typeof i=="string")||r.sha!==null&&!qo.test(r.sha))throw new Error("Native workspace finish journal commit is invalid")}if(t.merge!==void 0){let r=t.merge;if(!r||!qo.test(r.target)||!qo.test(r.source)||r.sha!==null&&!qo.test(r.sha))throw new Error("Native workspace finish journal merge is invalid")}return{schema:_k,name:t.name,transactionId:t.transactionId,archiveDir:t.archiveDir,status:t.status,result:t.result,updatedAt:t.updatedAt,...t.createdAt===void 0?{}:{createdAt:t.createdAt},...t.plan===void 0?{}:{plan:t.plan},...t.commit===void 0?{}:{commit:t.commit},...t.merge===void 0?{}:{merge:t.merge}}}function ZH(e,t){if(!Tk.test(t))throw new Error(`Invalid Native workspace finish journal name: ${t}`);return Wn.join(e.transactionsDir,`workspace-finish-${t}.json`)}async function yh(e,t,r={}){let i=ZH(e,t);try{let n=await wh.lstat(i);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native workspace finish journal is not a regular file");let a=QH(JSON.parse(await wh.readFile(i,"utf8")));if(a.name!==t)throw new Error("Native workspace finish journal name is invalid");return a}catch(n){if(n.code==="ENOENT")return null;if(r.onError)return r.onError(t,n instanceof Error?n.message:String(n)),null;throw n}}async function jk(e,t={}){let r;try{r=await wh.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r){if(!n.isFile()&&!n.isSymbolicLink()||n.isDirectory())continue;let a=new RegExp(`^workspace-finish-(${Ik})\\.json$`,"u").exec(n.name);if(!a)continue;let o=await yh(e,a[1],t);o&&i.push(o)}return i}var tD=/^native-workspaces-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function Tl(e,t){let r=vr.normalize(Nh(e)),i=vr.normalize(Nh(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function Nh(e){let t=vr.resolve(e);try{return eD.native(t)}catch{return t}}function rD(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function $k(e,t){let r=[];for(let i of await uk(e))t!==void 0&&i!==t||r.push({name:i,kind:await Vc(e,i)?"portable":"legacy"});return r}async function Bk(e,t){let r=vr.resolve(e),i=Go(e),n=i.map(({root:c})=>c),a=n.length>0?n:[r];a.some(c=>Tl(c,r))||a.push(r);let o=[],s=new Set;for(let c of a.map(l=>vr.resolve(l)).sort()){let l=Tl(c,r)?r:c,u=Nh(l),d=process.platform==="win32"?u.toLowerCase():u;if(s.has(d))continue;s.add(d);let p=await Te(l);if(!p)continue;let f=await tr(l,p.native.artifact_root);o.push({projectRoot:l,config:p,paths:f,gitContext:Kn(l,i)??ve(l),changes:await $k(f,t)})}if(o.length===0){let c=await Te(e);if(!c)throw new Error(".comet/config.yaml was not found in any registered worktree");let l=await tr(e,c.native.artifact_root);o.push({projectRoot:vr.resolve(e),config:c,paths:l,gitContext:Kn(e,i)??ve(e),changes:await $k(l,t)})}for(let c of o){c.archiveErrors=[],c.finishJournalErrors=[],c.archives=await pk(c.paths,(u,d)=>c.archiveErrors.push({name:u,message:d}),t),t!==void 0&&(c.archives=c.archives.filter(({state:u})=>u.name===t),c.archiveErrors=c.archiveErrors.filter(({name:u})=>u===t));let l=(u,d)=>c.finishJournalErrors.push({name:u,message:d});c.finishJournals=t?[await yh(c.paths,t,{onError:l})].filter(u=>u!==null):await jk(c.paths,{onError:l})}return o}function Ok(e,t){return e.workspace.bindingState==="aligned"?0:Tl(e.source.projectRoot,t)?1:e.workspace.bindingState==="legacy"?2:e.workspace.bindingState==="missing"?3:e.workspace.bindingState==="drifted"?4:5}async function Fk(e,t){let r=new Map;for(let n of t){for(let a of n.changes)r.set(a.name,[...r.get(a.name)??[],{source:n,kind:a.kind}]);for(let a of n.archives??[])r.has(a.state.name)||r.set(a.state.name,[]);for(let a of n.archiveErrors??[])r.has(a.name)||r.set(a.name,[]);for(let a of n.finishJournals??[])r.has(a.name)||r.set(a.name,[]);for(let a of n.finishJournalErrors??[])r.has(a.name)||r.set(a.name,[])}let i=[];for(let[n,a]of[...r.entries()].sort(([o],[s])=>o.localeCompare(s))){let o=await Promise.all(a.map(async({source:d,kind:p})=>{let f=d.finishJournalErrors?.find(({name:m})=>m===n);if(p==="portable")try{let m=await St(d.paths,n);return{source:d,name:n,kind:p,workspace:Al(d.paths,m,d.gitContext),portableStatus:null,inspectionError:f?.message??null,finishJournal:d.finishJournals?.find(({name:h})=>h===n)??null}}catch(m){return{source:d,name:n,kind:p,workspace:{projectRoot:d.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:"The portable state could not be inspected."},portableStatus:null,inspectionError:m instanceof Error?m.message:String(m)}}return{source:d,name:n,kind:p,workspace:a.length>1?await to(d.paths,n):{projectRoot:d.projectRoot,currentBranch:d.gitContext.currentBranch,isSecondaryWorktree:d.gitContext.isSecondaryWorktree,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:null,finish:null},portableStatus:null,inspectionError:f?.message??null}})),s=t.flatMap(d=>(d.archives??[]).filter(({state:p})=>p.name===n).map(p=>{let f=gh({paths:d.paths,...p,finishJournal:d.finishJournals?.find(({name:m})=>m===n)??null});return{source:d,name:n,kind:"portable",workspace:f.workspace,portableStatus:f,inspectionError:d.finishJournalErrors?.find(({name:m})=>m===n)?.message??null,record:p,finishJournal:d.finishJournals?.find(({name:m})=>m===n)??null}})),c=t.flatMap(d=>(d.archiveErrors??[]).filter(p=>p.name===n).map(p=>({source:d,error:p})))[0];if(c){i.push({source:c.source,name:n,kind:"portable",portableStatus:null,inspectionError:c.error.message,workspace:{projectRoot:c.source.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:c.error.message}});continue}let l=t.flatMap(d=>(d.finishJournalErrors??[]).filter(p=>p.name===n).map(p=>({source:d,error:p})))[0];if(l&&o.length===0&&s.length===0){i.push({source:l.source,name:n,kind:"portable",portableStatus:null,inspectionError:l.error.message,workspace:{projectRoot:l.source.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:l.error.message}});continue}if(o.length===0&&s.length===0){let d=t.find(f=>f.finishJournals?.some(({name:m})=>m===n)),p=d?.finishJournals?.find(({name:f})=>f===n);if(d&&p){i.push({source:d,name:n,kind:"portable",portableStatus:null,inspectionError:p.result?.message??"Native workspace finish journal has no matching active or archived change record.",workspace:{projectRoot:d.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:p.result?.message??"Native workspace finish record is orphaned."},finishJournal:p});continue}}if(s.length>0){for(let p of o)if(p.kind==="portable")try{p.record=await Cl(p.source.paths,vr.join(p.source.paths.changesDir,n,"comet-state.yaml"))}catch{}let d=s.find(p=>[...o,...s.filter(f=>!hk(p.record,f.record))].every(f=>f.record&&fk(p.record,f.record)));if(d){i.push(d);continue}i.push({...s[0],inspectionError:`Native change ${n} has conflicting active/archive records; identity and committed Git ancestry do not prove supersession. Resolve the records explicitly.`});continue}o.sort((d,p)=>Ok(d,e)-Ok(p,e)||d.source.projectRoot.localeCompare(p.source.projectRoot));let u=o.filter(d=>d.workspace.bindingState==="aligned");u.length>1?i.push(...u):u.length===0&&o.length>1?i.push({...o[0],inspectionError:`Native change ${n} has conflicting workspace records and no aligned binding`}):i.push(u[0]??o[0])}if(i.length>mr.maxChanges)throw new Error(`Native status discovery exceeds ${mr.maxChanges} visible changes`);return i.sort((n,a)=>`${n.name}\0${n.source.projectRoot}`.localeCompare(`${a.name}\0${a.source.projectRoot}`))}function Hk(e,t){let r=t.toString(36),i=T("comet.native.workspace-status-cursor.v1",{candidatesHash:e,offset:t});return`native-workspaces-v1.${e}.${r}.${i}`}function iD(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=tD.exec(e.cursor);if(!t||t[1]!==e.candidatesHash)throw new Error("Native workspace status cursor is invalid or stale");let r=Number.parseInt(t[2],36);if(!Number.isSafeInteger(r)||r<=0||r>=e.total||r.toString(36)!==t[2])throw new Error("Native workspace status cursor offset is invalid");let i=T("comet.native.workspace-status-cursor.v1",{candidatesHash:e.candidatesHash,offset:r});if(t[3]!==i)throw new Error("Native workspace status cursor integrity failed");return r}function Dk(e,t){let r=t?["comet","native","status","--cursor",t,"--project-root",e,"--json"]:null;return{nextPageCommand:r?rD(r):null,nextPageArgs:r}}async function nD(e,t,r){let i=await to(e.source.paths,e.name),n=null;try{n=await yy(e.source.paths,e.name)}catch{}return n?.state?{schema:"comet.native.status.v2",name:e.name,phase:n.state.phase,status:"blocked",migrationRequired:!0,legacySchema:n.schema,workspace:i,continuation:{schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:n.state.phase,status:"blocked",disposition:"blocked",action:"none",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],message:"This change uses a legacy schema; the first mutating command performs the deterministic migration. Run the listed next command with a migration summary.",runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0}}}:fh(e.source.paths,e.name,{details:t,...r?{acceptanceCursor:r}:{},clarificationMode:e.source.config.native.clarification_mode,maxVerifyFailures:e.source.config.native.max_verify_failures})}async function bh(e,t,r,i){if(e.inspectionError)return{schema:"comet.native.status.v2",name:e.name,phase:"invalid",status:"blocked",inspectionError:e.inspectionError,workspace:e.workspace,continuation:{schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:"invalid",status:"blocked",disposition:"blocked",action:"none",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],message:`Run the repair command in the workspace holding this change: ${e.source.paths.projectRoot}`,runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0}}};if(e.kind==="portable"){if(r)throw new Error("Portable Native status includes the complete acceptance list");if(!t&&e.portableStatus)return e.portableStatus;if(e.record?.state.archived)return gh({paths:e.source.paths,...e.record,finishJournal:e.finishJournal??null,details:t,cursor:i});try{return await Pk({paths:e.source.paths,name:e.name,details:t,gitContext:e.source.gitContext,...i?{cursor:i}:{}})}catch(n){if(i)throw n;return bh({...e,inspectionError:n instanceof Error?n.message:String(n)},!1)}}return nD(e,t,r)}async function Lk(e){let{sources:t,candidates:r}=await aD(e.projectRoot,e.name);if(r.length===0){let i=t.find(n=>Tl(n.projectRoot,e.projectRoot))??t[0];return e.onSelectedRoot?.(i.projectRoot),fh(i.paths,e.name,{details:e.details,...e.acceptanceCursor?{acceptanceCursor:e.acceptanceCursor}:{},clarificationMode:i.config.native.clarification_mode,maxVerifyFailures:i.config.native.max_verify_failures})}return e.onSelectedRoot?.(r[0].source.projectRoot),bh(r[0],e.details??!1,e.acceptanceCursor,e.detailsCursor)}async function aD(e,t){let r=await Bk(e,t),i=(await Fk(e,r)).filter(n=>n.name===t);if(i.length>1)throw new Error(`Native change ${t} has multiple aligned workspace bindings: ${i.map(n=>n.source.projectRoot).join(", ")}`);return{sources:r,candidates:i}}async function qk(e){let t=await Bk(e.projectRoot),r=await Fk(e.projectRoot,t),i=T("comet.native.workspace-status-candidates.v1",r.map(u=>({name:u.name,projectRoot:u.source.projectRoot,bindingState:u.workspace.bindingState,kind:u.kind}))),n=iD({candidatesHash:i,total:r.length,cursor:e.cursor}),a=await Promise.all(r.slice(n,n+mr.maxItems).map(u=>bh(u,!1))),o=[],s=r.some(({kind:u})=>u==="portable")?"comet.native.status-page.v2":"comet.native.status-page.v1";for(let u of a){let d=[...o,u],p=n+d.length,f=p<r.length?Hk(i,p):null,m={schema:s,total:r.length,offset:n,items:d,nextCursor:f,...Dk(vr.resolve(e.projectRoot),f),limits:{...mr}};if(Buffer.byteLength(JSON.stringify(m),"utf8")>mr.maxSerializedBytes){if(o.length===0)throw new Error("Native workspace status item exceeds its page serialization budget");break}o.push(u)}let c=n+o.length,l=c<r.length?Hk(i,c):null;return{schema:s,total:r.length,offset:n,items:o,nextCursor:l,...Dk(vr.resolve(e.projectRoot),l),limits:{...mr}}}ja();import Mo from"path";import{realpathSync as ED}from"fs";function Mk(e,t){let r=u=>u!==null&&typeof u=="object"&&!Array.isArray(u)?u:{},i=r(e),n=r(i.entry),a=r(i.state??n.state??i),o=r(i.preparation??i.workspace??n.workspace),s=r(i.continuation??n.continuation),c=typeof o.projectRoot=="string"&&o.projectRoot!=="."?o.projectRoot:t??null,l=a.stateVersion??a.state_version;return{phase:typeof a.phase=="string"?a.phase:null,status:typeof a.status=="string"?a.status:null,stateVersion:typeof l=="number"?l:null,workspace:{cwd:c},continuation:Object.keys(s).length?{...s,cwd:c}:null}}var gr={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function Vk(e){return e?e.command?`${gr.next} ${e.command}`:e.ask_user?`${gr.next} ${e.ask_user}`:null:null}function Wk(e,t){let r=[e.summary],i=Vk(e.next);return i&&r.push(i),e.user_message&&r.push("",gr.relay,e.user_message),t!==void 0&&r.push("",gr.details,JSON.stringify(t,null,2)),`${r.join(`
254
+ `}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${Mt(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:r}){let i=this.parser.parseInline(r),n=Xy(e);if(n===null)return i;e=n;let a='<a href="'+e+'"';return t&&(a+=' title="'+Mt(t)+'"'),a+=">"+i+"</a>",a}image({href:e,title:t,text:r,tokens:i}){i&&(r=this.parser.parseInline(i,this.parser.textRenderer));let n=Xy(e);if(n===null)return Mt(r);e=n;let a=`<img src="${e}" alt="${Mt(r)}"`;return t&&(a+=` title="${Mt(t)}"`),a+=">",a}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:Mt(e.text)}},pf=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},Et=class nf{options;renderer;textRenderer;constructor(t){this.options=t||xi,this.options.renderer=this.options.renderer||new Yc,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new pf}static parse(t,r){return new nf(r).parse(t)}static parseInline(t,r){return new nf(r).parseInline(t)}parse(t){this.renderer.parser=this;let r="";for(let i=0;i<t.length;i++){let n=t[i];if(this.options.extensions?.renderers?.[n.type]){let o=n,s=this.options.extensions.renderers[o.type].call({parser:this},o);if(s!==!1||!["space","hr","heading","code","table","blockquote","list","checkbox","html","def","paragraph","text"].includes(o.type)){r+=s||"";continue}}let a=n;switch(a.type){case"space":{r+=this.renderer.space(a);break}case"hr":{r+=this.renderer.hr(a);break}case"heading":{r+=this.renderer.heading(a);break}case"code":{r+=this.renderer.code(a);break}case"table":{r+=this.renderer.table(a);break}case"blockquote":{r+=this.renderer.blockquote(a);break}case"list":{r+=this.renderer.list(a);break}case"checkbox":{r+=this.renderer.checkbox(a);break}case"html":{r+=this.renderer.html(a);break}case"def":{r+=this.renderer.def(a);break}case"paragraph":{r+=this.renderer.paragraph(a);break}case"text":{r+=this.renderer.text(a);break}default:{let o='Token with "'+a.type+'" type was not found.';if(this.options.silent)return console.error(o),"";throw new Error(o)}}}return r}parseInline(t,r=this.renderer){this.renderer.parser=this;let i="";for(let n=0;n<t.length;n++){let a=t[n];if(this.options.extensions?.renderers?.[a.type]){let s=this.options.extensions.renderers[a.type].call({parser:this},a);if(s!==!1||!["escape","html","link","image","checkbox","strong","em","codespan","br","del","text"].includes(a.type)){i+=s||"";continue}}let o=a;switch(o.type){case"escape":{i+=r.text(o);break}case"html":{i+=r.html(o);break}case"link":{i+=r.link(o);break}case"image":{i+=r.image(o);break}case"checkbox":{i+=r.checkbox(o);break}case"strong":{i+=r.strong(o);break}case"em":{i+=r.em(o);break}case"codespan":{i+=r.codespan(o);break}case"br":{i+=r.br(o);break}case"del":{i+=r.del(o);break}case"text":{i+=r.text(o);break}default:{let s='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(s),"";throw new Error(s)}}}return i}},fo=class{options;block;constructor(e){this.options=e||xi}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?st.lex:st.lexInline}provideParser(e=this.block){return e?Et.parse:Et.parseInline}},Sj=class{defaults=af();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Et;Renderer=Yc;TextRenderer=pf;Lexer=st;Tokenizer=Kc;Hooks=fo;constructor(...e){this.use(...e)}walkTokens(e,t){let r=[];for(let i of e)switch(r=r.concat(t.call(this,i)),i.type){case"table":{let n=i;for(let a of n.header)r=r.concat(this.walkTokens(a.tokens,t));for(let a of n.rows)for(let o of a)r=r.concat(this.walkTokens(o.tokens,t));break}case"list":{let n=i;r=r.concat(this.walkTokens(n.items,t));break}default:{let n=i;this.defaults.extensions?.childTokens?.[n.type]?this.defaults.extensions.childTokens[n.type].forEach(a=>{let o=n[a].flat(1/0);r=r.concat(this.walkTokens(o,t))}):n.tokens&&(r=r.concat(this.walkTokens(n.tokens,t)))}}return r}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(r=>{let i={...r};if(i.async=this.defaults.async||i.async||!1,r.extensions&&(r.extensions.forEach(n=>{if(!n.name)throw new Error("extension name required");if("renderer"in n){let a=t.renderers[n.name];a?t.renderers[n.name]=function(...o){let s=n.renderer.apply(this,o);return s===!1&&(s=a.apply(this,o)),s}:t.renderers[n.name]=n.renderer}if("tokenizer"in n){if(!n.level||n.level!=="block"&&n.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let a=t[n.level];a?a.unshift(n.tokenizer):t[n.level]=[n.tokenizer],n.start&&(n.level==="block"?t.startBlock?t.startBlock.push(n.start):t.startBlock=[n.start]:n.level==="inline"&&(t.startInline?t.startInline.push(n.start):t.startInline=[n.start]))}"childTokens"in n&&n.childTokens&&(t.childTokens[n.name]=n.childTokens)}),i.extensions=t),r.renderer){let n=this.defaults.renderer||new Yc(this.defaults);for(let a in r.renderer){if(!(a in n))throw new Error(`renderer '${a}' does not exist`);if(["options","parser"].includes(a))continue;let o=a,s=r.renderer[o],c=n[o];n[o]=(...l)=>{let u=s.apply(n,l);return u===!1&&(u=c.apply(n,l)),u||""}}i.renderer=n}if(r.tokenizer){let n=this.defaults.tokenizer||new Kc(this.defaults);for(let a in r.tokenizer){if(!(a in n))throw new Error(`tokenizer '${a}' does not exist`);if(["options","rules","lexer"].includes(a))continue;let o=a,s=r.tokenizer[o],c=n[o];n[o]=(...l)=>{let u=s.apply(n,l);return u===!1&&(u=c.apply(n,l)),u}}i.tokenizer=n}if(r.hooks){let n=this.defaults.hooks||new fo;for(let a in r.hooks){if(!(a in n))throw new Error(`hook '${a}' does not exist`);if(["options","block"].includes(a))continue;let o=a,s=r.hooks[o],c=n[o];fo.passThroughHooks.has(a)?n[o]=l=>{if(this.defaults.async&&fo.passThroughHooksRespectAsync.has(a))return(async()=>{let d=await s.call(n,l);return c.call(n,d)})();let u=s.call(n,l);return c.call(n,u)}:n[o]=(...l)=>{if(this.defaults.async)return(async()=>{let d=await s.apply(n,l);return d===!1&&(d=await c.apply(n,l)),d})();let u=s.apply(n,l);return u===!1&&(u=c.apply(n,l)),u}}i.hooks=n}if(r.walkTokens){let n=this.defaults.walkTokens,a=r.walkTokens;i.walkTokens=function(o){let s=[];return s.push(a.call(this,o)),n&&(s=s.concat(n.call(this,o))),s}}this.defaults={...this.defaults,...i}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return st.lex(e,t??this.defaults)}parser(e,t){return Et.parse(e,t??this.defaults)}parseMarkdown(e){return(t,r)=>{let i={...r},n={...this.defaults,...i},a=this.onError(!!n.silent,!!n.async);if(this.defaults.async===!0&&i.async===!1)return a(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return a(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return a(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(n.hooks&&(n.hooks.options=n,n.hooks.block=e),n.async)return(async()=>{let o=n.hooks?await n.hooks.preprocess(t):t,s=await(n.hooks?await n.hooks.provideLexer(e):e?st.lex:st.lexInline)(o,n),c=n.hooks?await n.hooks.processAllTokens(s):s;n.walkTokens&&await Promise.all(this.walkTokens(c,n.walkTokens));let l=await(n.hooks?await n.hooks.provideParser(e):e?Et.parse:Et.parseInline)(c,n);return n.hooks?await n.hooks.postprocess(l):l})().catch(a);try{n.hooks&&(t=n.hooks.preprocess(t));let o=(n.hooks?n.hooks.provideLexer(e):e?st.lex:st.lexInline)(t,n);n.hooks&&(o=n.hooks.processAllTokens(o)),n.walkTokens&&this.walkTokens(o,n.walkTokens);let s=(n.hooks?n.hooks.provideParser(e):e?Et.parse:Et.parseInline)(o,n);return n.hooks&&(s=n.hooks.postprocess(s)),s}catch(o){return a(o)}}}onError(e,t){return r=>{if(r.message+=`
255
+ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error occurred:</p><pre>"+Mt(r.message+"",!0)+"</pre>";return t?Promise.resolve(i):i}if(t)return Promise.reject(r);throw r}}},Ei=new Sj;function X(e,t){return Ei.parse(e,t)}X.options=X.setOptions=function(e){return Ei.setOptions(e),X.defaults=Ei.defaults,tN(X.defaults),X};X.getDefaults=af;X.defaults=xi;function Ej(...e){return Ei.use(...e),X.defaults=Ei.defaults,tN(X.defaults),X}X.use=Ej;X.walkTokens=function(e,t){return Ei.walkTokens(e,t)};X.parseInline=Ei.parseInline;X.Parser=Et;X.parser=Et.parse;X.Renderer=Yc;X.TextRenderer=pf;X.Lexer=st;X.lexer=st.lex;X.Tokenizer=Kc;X.Hooks=fo;X.parse=X;var jW=X.options,$W=X.setOptions,OW=X.walkTokens,HW=X.parseInline;var DW=Et.parse,BW=st.lex;ae();et();ue();var PN=Kt(It(),1);import{promises as o$}from"node:fs";import xt from"node:path";ot();et();ue();Je();U();gt();el();el();Ri();Kr();ot();cc();ae();ue();al();Se();U();SN();Ri();Kr();ol();ot();Je();ol();Ba();U();var sl=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};function yf(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`}import i$ from"node:path";ot();Je();Se();Ri();Kr();async function cl(e){let t=yf(e.parent),r=Yt(e.paths.projectRoot,t);if(!r)return null;let i=Yt(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=yr(e.paths.projectRoot).map(o=>i$.resolve(o)).find(o=>ve(o).currentBranch===t);if(!n)return null;let a=il({parent:e.parent,targetBranch:e.targetBranch,targetCommit:i,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(r!==i){for(let o of a.children)o.status=o.dependsOn.length===0?"blocked":"pending",o.blocker=o.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;a.integration.headCommit=r}return mf(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function Nf(e,t){let r=xt.normalize(xt.resolve(e)),i=xt.normalize(xt.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function s$(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let r=e.slice(t.index+t[0].length);return r.split(/^#\s+/mu,1)[0]??r}function c$(e){let t=s$(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let r=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),i=t.match(/\bChild\s+\d+\b/giu);return Math.max(r?.length??0,i?.length??0)>=2}async function bf(e){try{let t=await ne({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return c$(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function kf(e){return T("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:r,text:i})=>({id:t,source:r,text:i})),children:e.children})}async function l$(e){let t=yr(e.projectRoot);t.some(i=>Nf(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>xt.resolve(n)))]){let n=await Te(i);n&&r.push({projectRoot:i,paths:await tr(i,n.native.artifact_root),parent:Nf(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function u$(e,t){let r=xt.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Br(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function d$(e,t){let r;try{r=await o$.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=xt.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await Br(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function p$(e,t,r){let i=xt.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${xt.sep}`))return null;let n=i.split(xt.sep).join("/");try{let a=(0,PN.parseDocument)(Ve(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:qe(a.toJS({mapAsMap:!1}))}catch{return null}}function f$(e,t,r){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==r||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${r??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function RN(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function No(e){let t=xt.join(e.paths.changesDir,e.state.name),r=await bf(t),i=null,n;try{n=await Vt({changeDir:t,validation:Jr(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:g})=>g)}:{},policy:"advisory"})}catch(g){i=`Children contract cannot be read; restore children.yaml and confirm Shape: ${g.message}`,n=null}if(!n){let g=await Ue(e.paths,e.state.name,{diagnostics:!0});if(g){let b=nl(g);return{...b,...r?{coordinationChoiceRequired:!0}:{},confirmed:!1,readyChildren:[],allDone:!1,children:b.children.map(k=>({...k,message:i??"Children contract is missing; restore children.yaml and confirm Shape before continuing"}))}}if(i)throw new Error(i);return e.state.children_contract_hash?{...r?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:r?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null}let a=kf({acceptance:e.state.acceptance,children:n.contract}),o=e.state.workspace.change_branch,s=e.state.phase!=="shape"&&e.state.children_contract_hash===a&&!n.drift;if(n.contract.schema===Gr){let g=await Ue(e.paths,e.state.name,{diagnostics:!0});if(!g){let N=e.state.workspace.change_branch??e.state.workspace.target_branch;if(N){let x=await cl({paths:e.paths,parent:e.state.name,targetBranch:N,contract:n.contract});x&&(g=x,await Ur(e.paths,x))}}if(g){let N=nl(g);return e.state.children_contract_hash!==a||n.drift?{...N,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:!1,readyChildren:[],allDone:!1,children:N.children.map(x=>({...x,message:n.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...N,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s&&N.confirmed}}let b=new Map(n.contract.children.map(N=>[N.name,N])),k=n.contract.children.map(N=>({name:N.name,summary:N.summary,dependsOn:[...N.depends_on],covers:[],status:s&&N.depends_on.every(x=>n.contract.children.filter(({name:w})=>w!==N.name).every(({name:w})=>w!==x))?"ready":"pending",phase:null,projectRoot:null,message:s?null:"Parent Shape confirmation is required"}));for(let N of k){if(N.status!=="ready")continue;b.get(N.name).depends_on.length>0&&(N.status="pending")}return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:k,readyChildren:k.filter(({status:N})=>N==="ready").map(({name:N})=>N),allDone:!1}}let c=await l$(e.paths),l=new Set(n.contract.children.map(({name:g})=>g)),u=new Map,d=new Map;for(let g of c){let b=g.parent&&o?`refs/heads/${o}`:"HEAD";for(let k of await d$(g,l)){let N={...k,source:g,committedState:p$(g,k.file,b)};u.set(k.state.name,[...u.get(k.state.name)??[],N])}for(let k of l){let N=await u$(g,k);N&&d.set(k,[...d.get(k)??[],{source:g,state:N}])}}let p=new Map;for(let g of n.contract.children){let b=(u.get(g.name)??[]).find(({source:x,committedState:w})=>x.parent&&w?.name===g.name&&RN(w,o));if(b){p.set(g.name,{kind:"done",phase:b.state.phase,projectRoot:b.source.projectRoot,message:null});continue}let k=u.get(g.name)?.[0];if(k){p.set(g.name,{kind:"blocked",phase:k.state.phase,projectRoot:k.source.projectRoot,message:`Native child ${g.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let N=d.get(g.name)??[];N.length>1?p.set(g.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${g.name} has multiple active workspace owners`}):N[0]&&p.set(g.name,f$(N[0].state,N[0].source,o))}let f=new Map(n.contract.children.map(g=>[g.name,g])),m=new Map,h=g=>{let b=m.get(g);if(b)return b;let k=f.get(g),x=k.depends_on.map(h).every(({status:O})=>O==="done"),w=p.get(g),S=w?.kind==="active"&&x?k.depends_on.filter(O=>!(u.get(O)??[]).some(({source:j,committedState:Q})=>Nf(j.projectRoot,w.projectRoot)&&Q?.name===O&&RN(Q,o))):[],E,y=w?.message??null;w?.kind==="done"?(E=x?"done":"blocked",x||(y=`Native child ${g} was merged before its dependencies`)):w?.kind==="active"?(E=x&&S.length===0?"active":"blocked",x?S.length>0&&(y=`Native child ${g} does not include merged dependencies: ${S.join(", ")}`):y=`Native child ${g} started before its dependencies merged`):w?.kind==="blocked"?E="blocked":(E=s&&x?"ready":"pending",s||(y="Parent Shape confirmation is required"));let C={name:g,summary:k.summary,dependsOn:[...k.depends_on],covers:[...k.covers],status:E,phase:w?.phase??null,projectRoot:w?.projectRoot??null,message:y};return m.set(g,C),C},v=n.contract.children.map(({name:g})=>h(g));return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:v,readyChildren:v.filter(({status:g})=>g==="ready").map(({name:g})=>g),allDone:v.every(({status:g})=>g==="done")}}fc();gt();wi();vo();tl();Se();dp();tp();gt();wi();ae();fi();vo();U();fi();ti();Je();var vb=Kt(It(),1);er();var JG=new Set("a an and are as at be by for from in is it of on or that the this to with you your".split(" "));var ZG=256*1024;gt();wi();Kr();var j0=Xs("en",{compact:!0});Je();Se();Ri();Kr();gt();wi();ot();cc();ue();import Bn from"node:path";ot();er();ae();var hU=8*1024*1024;al();Se();wi();U();function H0(e,t){let r=Bn.relative(Bn.resolve(e),Bn.resolve(t));if(Bn.isAbsolute(r)||r===".."||r.startsWith(`..${Bn.sep}`))throw new Error("Native local check cwd escaped the project root");let i=r.length===0?".":r.split(Bn.sep).join("/");return kN(e,i),i}function Nb(e,t=e.workspace.projectRoot){return e.checks.map(r=>{let[i,...n]=r.argv;if(!i)throw new Error(`Native local check ${r.id} has no executable`);return{id:r.id,name:r.name,executable:i,argv:n,cwdRef:H0(t,r.cwd),timeoutMs:r.timeoutMs,repeatable:r.repeatable}})}var DU=1024*1024*1024;Se();tl();vo();Kr();Se();Kr();Se();kp();var P6=16*1024;async function bb(e){let t=await Op(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(cn(t.selection.change),t.selection)}U();async function kb(e,t){let r=[],i=Y(e,t.name),n=Or(i,at.stateRef),a;try{a=await kn(i)}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")&&r.push({code:"run-state-missing",message:"Native change references a missing Run state",path:n}),r;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&&r.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")&&r.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:n}),a.currentStep!==t.phase&&r.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:n});let o=Or(i,a.trajectoryRef),s=await my(e,t.name);if(s.status==="repairable")return r.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}),r;if(s.status==="invalid")return r.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),r;let c;try{if(c=await bi(i,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 r.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),r}let l=Or(i,a.checkpointRef);try{let u=await Oc(i,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&r.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):r.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){r.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return r}Nn();import iO from"path";import{isDeepStrictEqual as Kf}from"util";ae();Lt();Ba();Se();U();wt();Pi();ue();ue();var Fn={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var D0=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function B0(e,t){return e<t?-1:e>t?1:0}function F0(e,t,r,i){if(!Array.isArray(e)||e.length>r||!i&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let n=e.map(a=>{if(typeof a!="string"||!D0.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(B0)}function Mf(e=[]){return F0(e,"Native repair failed check IDs",Fn.maxFailedCheckIds,!0)}function Sb(e,t){let r=new Set(t);return e.every(i=>r.has(i))}function L0(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:Sb(e.failedAcceptanceIds,t.failedAcceptanceIds)&&Sb(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function Vf(e,t){let r=1,i=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if(L0(i,a))break;r+=1,i=a}return r}fl();Ti();function Wf(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 Eb="repairStagnation",Ye={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},M0=/^[a-f0-9]{64}$/u;var V0=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),W0=["data","runId","sequence","timestamp","type"],xb=["disposition","overrideSummaryHash","signatureHash"],z0=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],Cb=12;function Gf(e,t){return e<t?-1:e>t?1:0}function Rb(e,t,r){let i=Object.keys(e).sort(Gf);if(i.length!==t.length||i.some((n,a)=>n!==t[a]))throw new Error(`${r} fields are invalid`)}function gl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Error(`${t} must be a plain object`);return e}function Ho(e,t){if(typeof e!="string"||!M0.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function G0(e){if(!Array.isArray(e)||e.length>Fn.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(Gf)}function Pb(e){if(typeof e!="string"||e.length===0||e.length>Ye.maxRunIdCharacters||Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function zf(e,t,r,i,n=!1){if(r.nodes+=1,r.nodes>Ye.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Ye.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(`${i} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>Ye.maxTextCharacters&&(!n||e.length>Ye.maxEventDataCharacters))throw new Error(`${i} contains oversized text`);if(r.characters+=e.length,r.characters>Ye.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${i} contains a non-JSON value`);if(r.ancestors.has(e))throw new Error(`${i} contains a cycle`);r.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>Ye.maxArrayEntries)throw new Error(`${i} contains an oversized array`);e.forEach((s,c)=>zf(s,t+1,r,`${i}[${c}]`));return}let a=gl(e,i),o=Object.keys(a);if(o.length>Ye.maxObjectFields)throw new Error(`${i} contains too many fields`);for(let s of o){if(s.length===0||s.length>Ye.maxKeyCharacters)throw new Error(`${i} contains an invalid field name`);if(r.characters+=s.length,r.characters>Ye.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");zf(a[s],t+1,r,`${i}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{r.ancestors.delete(e)}}}function J0(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 U0(e,t,r){let i=gl(e,`Native repair trajectory event ${t+1}`);if(Rb(i,W0,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(i.sequence)||i.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(J0(i.timestamp),typeof i.type!="string"||!V0.has(i.type))throw new Error("Native repair trajectory event type is invalid");if(Pb(i.runId)!==r)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let n={nodes:0,characters:0,ancestors:new Set};return zf(i.data,0,n,"Native trajectory event data"),gl(i.data,"Native repair trajectory event data"),{event:i,dataNodes:n.nodes,dataCharacters:n.characters}}function Jf(e){let t=gl(e,"Native repair trajectory projection"),r=Object.keys(t).sort(Gf),i=r.length===xb.length&&r.every((l,u)=>l===xb[u]);i||Rb(t,z0,"Native repair trajectory projection");let n=Ho(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:Ho(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(i)return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=Ho(t.contractHash,"Native repair trajectory contract hash"),s=G0(t.failedAcceptanceIds),c=Mf(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 K0(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 Y0(e,t){let r=t.filter(s=>s.kind==="failure"),i=r.length+1,n=e.maxVerifyFailures??Cb;if(i>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=Vf({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},r),o=i>=n?"hard-stop":a<Fn.warningAtConsecutiveFailures?"continue":a<Fn.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function X0(e,t,r){let i=t.filter(a=>a.kind==="failure"),n=r?.maxVerifyFailures??Cb;if(i.length>=n)throw new Error("Native repair trajectory cannot override a hard stop");if(r?.disposition!=="manual-stop"||r.signatureHash!==e.signatureHash||i.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 _b(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Ye.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=Pb(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 r=[],i=null,n=null,a=null,o=0,s=0,c=0;for(let l=0;l<e.committedTrajectoryOffset;l+=1){let u=U0(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>Ye.maxTotalDataNodes||c>Ye.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let p=d.data,f=Object.hasOwn(p,"repairScopeHash")?Ho(p.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(p,"implementationScopeHash")?Ho(p.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(p,Eb)){if(i?.contractHash===null&&d.type==="state_transitioned"&&p.previousPhase==="build"&&p.nextPhase==="verify"&&(f!==null&&n!==null&&f!==n||f===null&&(i?.disposition==="manual-stop"||i?.disposition==="hard-stop"))){r.length=0,i=null,n=f,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let m=Jf(p[Eb]);if(K0(p,m),m.overrideSummaryHash===null)m.contractHash!==null&&a!==null&&m.contractHash!==a&&(r.length=0,o=0),m.contractHash!==null&&(a=m.contractHash),m.contractHash===null&&f!==null&&n!==null&&f!==n&&(r.length=0,o=0),f!==null&&(n=f),Y0(m,r),o+=1,r.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:m.signatureHash,...m.contractHash===null?{}:{failedAcceptanceIds:[...m.failedAcceptanceIds],failedCheckIds:[...m.failedCheckIds]}});else{if(i?.contractHash===null&&f!==null&&n!==null&&f!==n)throw new Error("Native repair override cannot cross implementation scope progress");X0(m,r,i);let h=r.at(-1);if(!h||h.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");r.push({kind:"override",revision:d.sequence,iteration:h.iteration,signatureHash:m.signatureHash,summaryHash:m.overrideSummaryHash})}if(i=m,r.length>Fn.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:r,latestProjection:i}}function Ab(e){return _b(e).history}function Ib(e){let t=_b(e).latestProjection;return t?{...t}:null}Lt();var Ln={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:[]},Uf=ee("comet-native-runtime:v3:scope-reopen"),Q0=[{skillVersion:"3",skillHash:ee("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:ee("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:ee("comet-native-runtime:v1")}];function Tb(e){return e.skillVersion===Ln.definition.metadata.version&&e.skillHash===Uf||Q0.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}Lt();Lt();function jb(e){return ee(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}))}La();var Bb=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],nO=new Set(Bb),Fb=new Set([...Bb,"minimum_runtime_version","revision"]),aO=new Set([...Fb,"operation"]),Yf=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),oO=new Set([...Yf,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),Xf=class extends Error{constructor(r){super(`Native transition for ${r} requires doctor migration before recovery`);this.change=r;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function Zf(e,t){return iO.join(Y(e,t),"transition.json")}function yl(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function eh(e,t){let r=Object.keys(e).find(i=>!t.has(i));if(r)throw new Error(`Native transition journal contains unknown field: ${r}`)}function wl(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Qf(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let r=e,i=Object.keys(r),n=i.find(u=>!oO.has(u)),a=[...Yf].find(u=>!Object.hasOwn(r,u)),o=Yf.size+(Object.hasOwn(r,"implementationScopeHash")?1:0)+(Object.hasOwn(r,"repairScopeHash")?1:0)+(Object.hasOwn(r,"repairStagnation")?1:0)+(Object.hasOwn(r,"returnToBuild")?1:0);if(n||a||i.length!==o)throw new Error(`Native transition journal event data keys are invalid${n?`: ${n}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(r.previousPhase)||!["shape","build","verify","archive"].includes(r.nextPhase))throw new Error("Native transition journal event phases are invalid");if(r.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if(r.returnToBuild!==void 0&&typeof r.returnToBuild!="boolean")throw new Error("Native transition journal returnToBuild flag is invalid");if(Wf(r.summary,"Native transition journal event summary"),ct(r.summary)!==r.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(r.artifacts)||r.artifacts.length>128||r.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(r.noCodeReason!==null&&(Wf(r.noCodeReason,"Native transition journal event no-code reason"),ct(r.noCodeReason)!==r.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(r.verificationResult!==null&&r.verificationResult!=="pass"&&r.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(r,"implementationScopeHash")?r.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||r.previousPhase!=="build"&&r.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(r,"repairStagnation")?Jf(r.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(r.previousPhase!=="verify"||r.nextPhase!=="build"||r.verificationResult!=="fail")||!u&&(r.previousPhase!=="build"||r.nextPhase!=="verify"||r.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(r,"repairScopeHash")?r.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||r.previousPhase!=="build"&&r.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:r.previousPhase,nextPhase:r.nextPhase,evidenceHash:t,summary:r.summary,artifacts:[...r.artifacts],noCodeReason:r.noCodeReason,verificationResult:r.verificationResult,...r.returnToBuild===!0?{returnToBuild:!0}:{},...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function sO(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let r=e,i=Object.keys(r),n=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(i.length===n.size&&i.every(a=>n.has(a))&&r.reason==="spec-rebase")return Qf({previousPhase:r.previousPhase,nextPhase:r.nextPhase,evidenceHash:r.evidenceHash,summary:r.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return Qf(e,t)}function th(e,t,r=!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 i=r?sO(e.eventData,e.evidenceHash):Qf(e.eventData,e.evidenceHash),n=Dp(e.nextRun),a=e.previousRun===null?null:Dp(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:i}}function $b(e,t,r=!1){if(e.skill!==Ln.definition.metadata.name||(r?!Tb(e):e.skillVersion!==Ln.definition.metadata.version||e.skillHash!==Uf)||e.orchestration!==Ln.definition.orchestration.mode||e.pendingRef!==at.pendingRef||e.trajectoryRef!==at.trajectoryRef||e.contextRef!==at.contextRef||e.artifactsRef!==at.artifactsRef||e.checkpointRef!==at.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function Ob(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 Hb(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 rh(e,t,r,i=!1,n="advance"){let{previousRun:a,nextRun:o}=r;if($b(o,"next Run",i||a!==null),Hb(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($b(a,"previous Run",!0),Hb(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(!Kf(Ob(a),Ob(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function cO(e,t,r){return ee(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:r}))}function Lb(e,t,r){return e.phase!=="shape"&&t.phase==="build"&&r.verificationResult===null?"spec-rebase":"advance"}function Db(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function ih(e,t,r,i,n=!1){let a=r.eventData,o=Db(e),s=Db(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(i==="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&&Kf(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(i==="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&&Kf(e.spec_changes,t.spec_changes),l=jb({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||r.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(i==="spec-rebase"){let c=cO(e.name,a.summary,t.spec_changes),l=ee(`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&&r.evidenceHash!==c||n&&r.evidenceHash!==c&&r.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 lO(e,t){let r=yl(e);if(eh(r,aO),r.schema!==an)throw new Error(`Expected Native transition schema ${an}`);let i=wl(r.minimum_runtime_version,"Native transition minimum_runtime_version");if(i>3)throw new Error(`Native transition requires runtime protocol ${i}; current protocol is ${3}`);if(i!==3)throw new Error(`Native transition ${an} minimum_runtime_version must be ${3}`);let n=wl(r.revision,"Native transition revision");if(n!==1)throw new Error("Native transition journal revision must be 1");if(r.operation!=="advance"&&r.operation!=="spec-rebase"&&r.operation!=="evidence-retreat"&&r.operation!=="runtime-rebuild")throw new Error("Native transition journal operation is invalid");let a=th(r,t),o=Bt(r.previousState),s=Bt(r.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(ih(o,s,a,r.operation),rh(o,s,a,!1,r.operation),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:an,minimum_runtime_version:3,revision:n,operation:r.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 uO(e,t){let r=yl(e);if(eh(r,nO),r.schema!==Fa)throw new Error(`Expected Native transition schema ${Fa}`);let i=th(r,t,!0),n=mi(r.previousState),a=mi(r.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return ih(n,a,i,Lb(n,a,i.eventData),!0),rh(n,a,i,!0),{schema:Fa,id:i.id,change:t,evidenceHash:i.evidenceHash,createdAt:i.createdAt,previousState:n,nextState:a,previousRun:i.previousRun,nextRun:i.nextRun,eventData:i.eventData}}function dO(e,t){let r=yl(e);if(eh(r,Fb),r.schema!==on)throw new Error(`Expected Native transition schema ${on}`);if(wl(r.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${on} minimum_runtime_version must be 2`);let n=wl(r.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=th(r,t,!0),o=vi(r.previousState),s=vi(r.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(ih(o,s,a,Lb(o,s,a.eventData),!0),rh(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:on,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 pO(e,t){let r=yl(e);if(r.schema===an)return{status:"current",journal:lO(r,t)};if(r.schema===Fa)return{status:"migration-required",journal:uO(r,t)};if(r.schema===on)return{status:"migration-required",journal:dO(r,t)};throw new Error(`Unsupported Native transition journal schema: ${String(r.schema)}`)}async function fO(e,t){let r=Zf(e,t),i=we(e,r);await K(i,r);try{let n=await yi({root:i,file:r,maxBytes:null,label:`Native transition journal ${t}`});return pO(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function qb(e,t){let r=await fO(e,t);if(!r)return null;if(r.status==="migration-required")throw new Xf(t);return r.journal}var hO=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function mO(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function vO(e){return e?e.map(mO).join(" "):null}function gO(e){if(e===null)return null;let t=e.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/gu);return!t||t[0]!=="comet"?null:t.map(r=>{if(r.startsWith('"')&&r.endsWith('"'))try{return JSON.parse(r)}catch{return r.slice(1,-1)}return r.startsWith("'")&&r.endsWith("'")?r.slice(1,-1):r})}function lt(e,t,r,i={}){return{input:e,flags:t,required:i.required??!0,placeholder:r,...i.choices?{choices:i.choices}:{},...i.repeatable?{repeatable:!0}:{},...i.alternativeGroup?{alternativeGroup:i.alternativeGroup}:{}}}function wO(e){return e.map(t=>lt(t,[],null))}function yO(e){let t=["comet","native","next",e.name,"--summary","<summary>"],r=[lt("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),r.push(lt("shared-understanding-confirmation",["--confirmed"],null)),{commandArgs:t,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:r};if(e.phase==="build"){t.push("--artifact","<project-relative-path>"),r.push(lt("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),lt("artifact-or-no-code-reason",["--no-code-reason"],"<reason>",{alternativeGroup:"build-evidence"}));let i=["summary","artifact-or-no-code-reason"];return e.approval!=="confirmed"&&(t.push("--confirmed"),i.push("shared-understanding-confirmation"),r.push(lt("shared-understanding-confirmation",["--confirmed"],null))),{commandArgs:t,requiredInputs:i,inputOptions:r}}return e.phase==="verify"?(t.push("--result","<pass|fail>","--report","<change-relative-path>"),r.push(lt("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),lt("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:r}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function Re(e,t){let r=t.commandArgs===void 0?gO(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?vO(r??null):t.command,commandArgs:r??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??wO(t.requiredInputs??[])}}function Nl(e){let r=(e.findings??[]).filter(d=>!Sn(d.code)),i=r.find(d=>d.requiresUserDecision),n=r.find(d=>d.repairCommand!==null||hO.test(d.code)),a=r.find(d=>d.code==="repair-iteration-limit"||d.code==="repair-override-exhausted"),o=r.find(d=>d.code==="repair-stagnation-stop"),s=r.find(d=>d.requiredAction==="return-to-bound-working-directory"||d.requiredAction==="repair-workspace-binding"),c=r.find(d=>d.code==="runtime-missing"),l=[...new Set(r.map(d=>d.requiredAction))].sort();if(e.done)return Re(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return Re(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[lt("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(i)return Re(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return Re(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return Re(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return Re(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[lt("summary",["--summary"],"<summary>")]});if(n)return Re(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 Re(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[lt("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return Re(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(r.length>0)return e.state.phase==="archive"?Re(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?Re(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):Re(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"),Re(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[lt("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):Re(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return Re(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=yO(e.state);return Re(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import Do from"path";U();var Mb=8,NO={"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 bO(e){let t=NO[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"}:Sn(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 kO(e,t,r){if(!r.path)return null;let i;if(Do.isAbsolute(r.path)?i=Do.resolve(r.path):/^(?:brief-|verification-|spec-source)/u.test(r.code)?i=Do.resolve(Ne(e,t.name),...r.path.split(/[\\/]/u)):i=Do.resolve(e.projectRoot,...r.path.split(/[\\/]/u)),!q(e.projectRoot,i))return null;let n=Do.relative(e.projectRoot,i).replaceAll("\\","/");return n===""?".":n}function SO(e,t,r){return e==="next"?`comet native next ${t.name} --summary "<summary>"${r==="contract-changed-after-approval"||r==="shape-confirmation-required"||r==="approval-confirmation-required"?" --confirmed":""}`:e==="status"?`comet native status ${t.name} --details`:null}function nh(e){return e.findings.map(t=>{let r=bO(t.code);return{code:t.code,message:t.message,severity:r.severity,path:kO(e.paths,e.state,t),requiredAction:r.requiredAction,retryCommand:SO(r.retry,e.state,t.code),repairCommand:r.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,r)=>{let i={error:0,warning:1,info:2};return i[t.severity]-i[r.severity]||t.code.localeCompare(r.code)||(t.path??"").localeCompare(r.path??"")||t.message.localeCompare(r.message)})}function ah(e){let t=[...new Set(e.map(r=>r.code))];return{total:e.length,errors:e.filter(r=>r.severity==="error").length,warnings:e.filter(r=>r.severity==="warning").length,info:e.filter(r=>r.severity==="info").length,requiresUserDecision:e.some(r=>r.requiresUserDecision),codes:t.slice(0,Mb),truncated:t.length>Mb}}ae();import qn from"path";Lt();U();wt();Pa();Pi();var Bo={maxArtifacts:128},Mn=/^[a-f0-9]{64}$/u;function bl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function kl(e,t,r){let i=new Set(t),n=Object.keys(e).filter(o=>!i.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${r} is missing field(s): ${a.join(", ")}`)}function ri(e,t,r=2e3){if(typeof e!="string"||e.length===0||e.length>r)throw new Error(`${t} must be a non-empty string of at most ${r} characters`);return e}function Vb(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function oh(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function EO(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||qn.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let r=qn.posix.normalize(t);if(r==="."||r===".."||r.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return r}function Wb(e,t){return qn.join(Y(e,t),"checkpoints","progress.json")}function Fo(e,t){return qn.join(Y(e,t),"checkpoint-journal.json")}function zb(e,t,r){if(!Mn.test(r))throw new Error("Native checkpoint manifest hash is invalid");return qn.join(Y(e,t),"checkpoints","manifests",`${r}.json`)}function xO(e){if(!Mn.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function sh(e,t,r){let i=await yi({root:e,file:t,maxBytes:null,label:r});return JSON.parse(i.bytes.toString("utf8"))}function CO(e,t){let r=bl(e,`checkpoint manifest artifact ${t}`);kl(r,["path","hash","size"],`checkpoint manifest artifact ${t}`);let i=EO(ri(r.path,`checkpoint artifact ${t} path`,4096)),n=Tt(i);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${i}`);if(typeof r.hash!="string"||!Mn.test(r.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:i,hash:r.hash,size:oh(r.size,`checkpoint artifact ${t} size`)}}function ch(e,t){let r=bl(e,"Native checkpoint manifest");if(kl(r,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),r.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(r.change!==t)throw new Error("Native checkpoint manifest change mismatch");if(!Array.isArray(r.artifacts))throw new Error("Native checkpoint manifest artifacts must be an array");if(r.artifacts.length>Bo.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let i=r.artifacts.map(CO),n=[...i].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(i)!==JSON.stringify(n))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(i.map(o=>o.path)).size!==i.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=oh(r.totalBytes,"checkpoint manifest totalBytes");if(i.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:i,totalBytes:a}}function Gb(e){return ee(JSON.stringify(ch(e,e.change)))}function Jb(e,t){let r=bl(e,"Native progress checkpoint");if(kl(r,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),r.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(r.change!==t)throw new Error("Native checkpoint change mismatch");let i=r.phase;if(i!=="shape"&&i!=="build"&&i!=="verify"&&i!=="archive")throw new Error("Native checkpoint phase is invalid");let n=Vb(r.previousRevision,"Native checkpoint previousRevision"),a=Vb(r.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=ri(r.manifestHash,"Native checkpoint manifestHash",64);if(!Mn.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=xO(o);if(r.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=ri(r.inputHash,"Native checkpoint inputHash",64);if(!Mn.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=ri(r.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=oh(r.artifactCount,"Native checkpoint artifactCount");if(u>Bo.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=ri(r.summary,"Native checkpoint summary"),p=ri(r.nextAction,"Native checkpoint nextAction");if(ct(d)!==d||ct(p)!==p)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:ri(r.id,"Native checkpoint id",128),change:t,phase:i,previousRevision:n,stateRevision:a,summary:d,nextAction:p,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function RO(e,t){let r=bl(e,"Native checkpoint journal");if(kl(r,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),r.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(r.change!==t)throw new Error("Native checkpoint journal change mismatch");let i=Bt(r.previousState),n=Bt(r.nextState),a=Jb(r.checkpoint,t),o=ch(r.manifest,t),s=ri(r.inputHash,"Native checkpoint journal inputHash",64),c=ee(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!Mn.test(s)||s!==a.inputHash||s!==c||r.id!==a.id||r.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(i.name!==t||n.name!==t||n.revision!==i.revision+1||a.previousRevision!==i.revision||a.stateRevision!==n.revision||a.phase!==n.phase||a.manifestHash!==Gb(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:i,nextState:n,checkpoint:a,manifest:o}}async function PO(e,t,r){let i=qn.resolve(e.projectRoot,...t.split("/"));if(!q(e.projectRoot,i)||q(e.nativeRoot,i)||q(e.runtimeDir,i))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=Ed(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await Sp({root:e.projectRoot,file:i,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot,e.runtimeDir],hooks:{afterParentChainCaptured:()=>r?.afterParentChainCaptured?.(t),afterOpen:()=>r?.afterOpen?.(t),beforeRead:()=>r?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function _O(e,t){let r=Wb(e,t),i=we(e,r);await K(i,r);try{return Jb(await sh(i,r,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function AO(e,t,r){let i=zb(e,t,r),n=we(e,i);await K(n,i);let a=await sh(n,i,"Native checkpoint manifest"),o=ch(a,t);if(Ub(e,o),Gb(o)!==r)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function lh(e,t){let r=Fo(e,t),i=we(e,r);await K(i,r);try{let n=RO(await sh(i,r,"Native checkpoint journal"),t);return Ub(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}function Ub(e,t){for(let r of t.artifacts){let i=Ed(e,r.path);if(i)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${i}): ${r.path}`)}}async function Kb(e){let t;try{t=await _O(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:Wb(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let r=[],i=[];t.stateRevision!==e.stateRevision&&r.push("state-revision-changed");let n=null;try{n=await AO(e.paths,e.name,t.manifestHash);let a=ee(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 PO(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&r.push(`artifact-changed:${o.path}`)}catch{r.push(`artifact-unavailable:${o.path}`)}}catch(a){r.push("checkpoint-manifest-invalid"),i.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:zb(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:r.length===0?"fresh":"stale",reasons:r,findings:i}}var Yb=240,Xb=8,Sl=50;function Qb(e){let t=Array.from(e);return t.length<=Yb?e:`${t.slice(0,Yb-1).join("")}…`}function IO(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function TO(e){let t=[...new Set(e.map(IO))],r={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,Xb),reasonCount:e.length,codesTruncated:t.length>Xb};return{inspection:r,inspectionDetails:{...r,reasons:e.slice(0,Sl),reasonsTruncated:e.length>Sl}}}async function Zb(e){let t=null;try{let s=await lh(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:Fo(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:Fo(e.paths,e.state.name)}}let r=await Kb({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),i=t?[t.code,...r.reasons]:r.reasons,n=TO(i);if(!r.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...r.findings]:r.findings,maxCheckpointArtifacts:Bo.maxArtifacts};let a={id:r.checkpoint.id,createdAt:r.checkpoint.createdAt,phase:r.checkpoint.phase,stateRevision:r.checkpoint.stateRevision,summary:Qb(r.checkpoint.summary),nextAction:Qb(r.checkpoint.nextAction),artifactCount:r.checkpoint.artifactCount},o=r.manifest?{...a,summary:r.checkpoint.summary,nextAction:r.checkpoint.nextAction,manifestHash:r.checkpoint.manifestHash,manifestRef:r.checkpoint.manifestRef,artifacts:r.manifest.artifacts,totalBytes:r.manifest.totalBytes}:null;return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...r.findings]:r.findings,maxCheckpointArtifacts:Bo.maxArtifacts}}import{promises as IH}from"node:fs";import wk from"node:path";ue();import ek from"node:path";var jO="comet.native.archive-preflight.v1",$O="comet.native.archive-preflight.v1",OO="comet.native.archive-operation.v1",HO=/^[a-f0-9]{64}$/u,tk=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,DO=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function El(e,t){return e<t?-1:e>t?1:0}function BO(e,t){if(typeof e!="string"||!HO.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function hr(e,t){return e===null?null:BO(e,t)}function FO(e,t){let r=ek.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||ek.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized Native-relative ref`);return e}function LO(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function qO(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,r]of[["change",e.changeBranch],["target",e.targetBranch]])if(r!==null&&(r.length===0||r.trim()!==r||Array.from(r).some(i=>{let n=i.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 MO(e,t){if(!tk.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 r=hr(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),i=hr(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=hr(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&r!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&r===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:r,actualBaseHash:i,proposedHash:n}}function VO(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:hr(e.contractHash,"Native archive contract hash"),acceptanceHash:hr(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:hr(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:hr(e.reportHash,"Native archive report hash"),envelopeHash:hr(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:hr(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(r=>r===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 WO(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(i=>{if(typeof i!="string"||!DO.test(i))throw new Error(`Native archive preflight finding code is invalid: ${String(i)}`);return i}),r=[...new Set(t)].sort(El);if(r.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return r}function zO(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 r of e.specs)r.actualBaseHash!==r.expectedBaseHash&&t.push("spec-base-conflict");return[...new Set(t)].sort(El)}function rk(e){if(!tk.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(MO).sort((l,u)=>El(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 r=t.map(l=>({...l,operationHash:T(OO,l)})),i=VO(e.evidence),n=qO(e.workspace),a=[...new Set([...WO(e.findingCodes??[]),...zO({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:i})])].sort(El),o=LO(e.revision),s=FO(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:r,evidence:i,workspace:n,findingCodes:a};return{schema:jO,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:i.freshness,operationCount:r.length,operations:r,workspace:n,findingCodes:a,preflightHash:T($O,c)}}et();ue();import{createHash as GO}from"node:crypto";import ik from"node:path";var JO="comet.native.conflict-radar.v1",ze=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}),UO="comet.native.conflict-radar.v1",KO="comet.native.conflict-radar-signals.v1",YO=/^[a-f0-9]{64}$/u,ok=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,XO=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),QO=new Set(["capability","operation","baseHash"]),ZO=new Set(["path","kind"]);function Vn(e,t){return e<t?-1:e>t?1:0}function uh(e){return Buffer.byteLength(e,"utf8")}function dh(e,t,r){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${r} must be an object`);let i=e,n=Object.keys(i).filter(a=>!t.has(a));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);return i}function ph(e,t,r){if(typeof e!="string"||e.length===0||e!==e.trim())throw new Error(`${t} must be a non-empty trimmed string`);if(uh(e)>r)throw new Error(`${t} exceeds its byte budget`);return e}function eH(e,t){let r=ph(e,t,ze.maxArtifactPathBytes),i=ik.posix.normalize(r);if(r.includes("\\")||Array.from(r).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(r)||ik.posix.isAbsolute(i)||r.split("/").includes("..")||i!==r||i==="."||r.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return r}function sk(e,t){if(typeof e!="string"||!YO.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function tH(e,t){let r=dh(e,QO,t),i=ph(r.capability,`${t} capability`,ze.maxCapabilityBytes);if(!ok.test(i))throw new Error(`${t} capability is invalid`);if(r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`${t} operation is invalid`);let n=r.baseHash===null?null:sk(r.baseHash,`${t} canonical base hash`);if(r.operation==="create"&&n!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(r.operation!=="create"&&n===null)throw new Error(`${t} ${r.operation} operation requires a canonical base hash`);return{capability:i,operation:r.operation,baseHash:n}}function rH(e,t){let r=dh(e,ZO,t);if(r.kind!=="file"&&r.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:eH(r.path,`${t} path`),kind:r.kind}}function iH(e,t){let r=dh(e,XO,`Conflict radar change ${t}`),i=ph(r.name,`Conflict radar change ${t} name`,ze.maxNameBytes);if(!ok.test(i))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(r.revision)||r.revision<1)throw new Error(`Conflict radar change ${i} revision must be a positive safe integer`);if(!Array.isArray(r.specs))throw new Error(`Conflict radar change ${i} specs must be an array`);if(r.specs.length>ze.maxSpecsPerChange)throw new Error(`Conflict radar change ${i} exceeds the spec budget`);if(!Array.isArray(r.declaredArtifacts))throw new Error(`Conflict radar change ${i} declared artifacts must be an array`);if(r.declaredArtifacts.length>ze.maxArtifactsPerChange)throw new Error(`Conflict radar change ${i} exceeds the declared artifact budget`);let n=r.specs.map((c,l)=>tH(c,`Conflict radar change ${i} spec ${l}`)).sort((c,l)=>Vn(c.capability,l.capability));if(new Set(n.map(c=>c.capability)).size!==n.length)throw new Error(`Conflict radar change ${i} has duplicate capabilities`);let a=r.declaredArtifacts.map((c,l)=>rH(c,`Conflict radar change ${i} artifact ${l}`)).sort((c,l)=>Vn(c.path,l.path)||Vn(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${i} has duplicate or conflicting artifact paths`);let s=r.workspaceIdentityHash===void 0||r.workspaceIdentityHash===null?null:sk(r.workspaceIdentityHash,`Conflict radar change ${i} workspace identity hash`);return{name:i,revision:r.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function nH(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>ze.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(iH).sort((n,a)=>Vn(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)>ze.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>ze.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function aH(e,t){let r=e.baseHash!==null&&e.baseHash===t.baseHash;return{kind:"capability",certainty:e.operation==="create"||t.operation==="create"||r?"definite-conflict":"possible-overlap",capability:e.capability,leftOperation:e.operation,rightOperation:t.operation,leftBaseHash:e.baseHash,rightBaseHash:t.baseHash}}function oH(e,t){let r=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),i=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),n=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!r&&!i&&!n?null:{kind:"artifact",certainty:n?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function sH(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function cH(e,t){let r=[],i=GO("sha256").update(`${KO}
256
+ [`),n=0,a=!1,o=l=>{n>0&&i.update(","),i.update(Xn(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),r.length<ze.maxSignalsPerRelationship&&r.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(aH(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=oH(l,u);d&&o(d)}let c=a?"definite-conflict":n>0?"possible-overlap":"disjoint";return i.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:sH(e,t),signalCount:n,signalHash:i.digest("hex"),signals:r,signalsTruncated:r.length!==n}}function nk(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function lH(e,t){return nk(e.classification)-nk(t.classification)||Vn(e.left,t.left)||Vn(e.right,t.right)}function ak(e,t,r,i){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:JO,workspaceIdentityAdvisoryOnly:!0,changeCount:e.length,relationshipCount:t.length,counts:n,relationships:r,relationshipsTruncated:r.length!==t.length,omittedRelationshipCount:t.length-r.length,radarHash:i}}function ck(e){let t=nH(e),r=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)r.push(cH(t[s],t[c]));r.sort(lH);let i=r.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=T(UO,{changes:t,relationships:i}),a=r.slice(0,ze.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=ak(t,r,a,n);for(;a.length>0&&uh(JSON.stringify(o))>ze.maxSerializedBytes;)a=a.slice(0,-1),o=ak(t,r,a,n);if(uh(JSON.stringify(o))>ze.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}ti();wt();var uH=4096;async function dH(e,t=ze.maxChanges){try{let r=await Ya({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:t});return await r.verify(),r.entries}catch(r){if(r.code==="ENOENT")return[];throw r}}async function lk(e,t){let r=await sr(e,t),[i,n]=await Promise.all([r.implementation_scope?ml(e,t,r.implementation_scope):null,or(e,t).catch(()=>null)]);return{name:r.name,revision:r.revision,specs:r.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:i?.declaredArtifacts??[],workspaceIdentityHash:n?.nativeRootId??null}}async function xl(e,t,r={}){let n=(await dH(e,uH)).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 lk(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await lk(e,c).catch(d=>{if(r.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=ck([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"]:[]]}}Je();U();Wa();et();ti();Nn();Ti();fl();import{execFile as kH}from"node:child_process";Di();Jn();wf();import{promisify as SH}from"node:util";Se();ae();Hf();U();jt();import{constants as fh,promises as ut}from"node:fs";import Wn from"node:path";var fH=/^[a-f0-9]{64}$/u,hH=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u;function mH(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Cl(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Qe(r,i)?G(r,i):G(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function vH(e,t){let r=Wn.resolve(e),i=Wn.resolve(t);if(!q(r,i))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=r;for(let o of["",...Wn.relative(r,i).split(Wn.sep).filter(Boolean)]){o&&(a=Wn.join(a,o));let s=await ut.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await ut.realpath(a);if(n.length>0&&!q(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 dk(e){for(let t of e){let r=await ut.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!mH(t,r)||await ut.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function gH(e){if(!fH.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function wH(e){let t=hH.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function yH(e,t,r){return Or(Y(e,t),gH(r))}async function NH(e,t,r){let i=await vH(r,Wn.dirname(e)),n=await ut.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");let[a,o]=await Promise.all([ut.realpath(t),ut.realpath(e)]);if(!q(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":fh.O_RDONLY|fh.O_NOFOLLOW|fh.O_NONBLOCK,c=await ut.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(),ut.lstat(e),ut.realpath(e)]);if(await dk(i),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Cl(n,l)||!Cl(l,u))throw new Error("Native check receipt changed while opening");let p=[],f=0,m=Buffer.allocUnsafe(16*1024);for(;;){let b=await c.read(m,0,m.length,null);if(b.bytesRead===0)break;f+=b.bytesRead,p.push(Buffer.from(m.subarray(0,b.bytesRead)))}let[h,v,g]=await Promise.all([c.stat(),ut.lstat(e),ut.realpath(e)]);if(await dk(i),!v.isFile()||v.isSymbolicLink()||g!==o||!q(a,g)||!Cl(l,h)||!Cl(l,v))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(p,f).toString("utf8"))}finally{await c.close()}}async function pk(e,t,r){let i=wH(r),n=Y(e,t),a=yH(e,t,i),o=we(e,a);await K(o,a);let s=cb(await NH(a,n,o));if(s.change!==t||s.receiptHash!==i)throw new Error("Native check receipt ref/hash/change mismatch");return s}ti();Se();Pi();var Lo=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};Nn();_o();Ti();var L9=64*1024;var q9=3600*1e3;var M9=SH(kH);var EH=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function fk(e,t){let r=[];for(let i of EH){let n=e.bindings[i],a=t[i];n!==a&&r.push(`${i}: expected ${JSON.stringify(a)}, got ${JSON.stringify(n)}`)}return{ok:r.length===0,mismatches:r}}async function hk(e){if(e.receipt.kind!=="static-inspection")return null;let t=await pk(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}_o();var ii=class extends Error{details;constructor(t){let r=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(i=>`${i.ref}${i.acceptanceId?`[${i.acceptanceId}]`:""} -> ${i.mismatches.join("; ")}`).join(" | ")}`;super(r),this.name="NativeVerificationReceiptBindingError",this.details=t}};function xH(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 CH(e){let t=xH(e.bundle.baseline),r=await jp(e.paths,t,{origin:"explicit",now:e.now});return Af({baseline:t,current:r,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason,externalDrift:e.bundle.authority.externalDrift}).scope.currentProjectionHash}async function vk(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await Ao(e.paths,e.state.name,e.state.implementation_scope),r=await xn({changeDir:Ne(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),i=await CH({paths:e.paths,bundle:t,now:e.now}),n=[];return r.contract.contractHash!==t.scope.contractHash&&n.push("verification-contract-stale"),i!==t.scope.currentProjectionHash&&n.push("verification-implementation-stale"),{bundle:t,contract:r.contract,contractHash:r.contract.contractHash,acceptanceHash:r.contract.acceptanceHash,findingCodes:n}}async function gk(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await vk(e),r=[...new Set(t.findingCodes)].sort();return{freshness:r.length===0?"fresh":"stale",findingCodes:r}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"]}}}async function RH(e){let t=await ne({root:Ne(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:yw(t.text)}}function PH(e){let{receipt:t,implementationScope:r}=e,i=[],n=_f({baseline:r.baseline,current:r.current,declaredArtifacts:r.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!==r.scope.scopeHash||t.implementation.expectedSnapshotHash!==r.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==r.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==r.scope.currentProjectionHash||t.counts.filesSelected!==n.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==n.length||t.counts.bytesScanned!==a))&&i.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&i.push("verification-receipt-outcome-mismatch"),i}function _H(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:Ff(e.implementationScope.scope.declaredArtifacts)}}async function mk(e){let t=await Io(e.paths,e.state.name,e.ref),r=[];t.role!==e.role&&r.push(`role: expected ${e.role}, got ${t.role}`);let i=fk(t,e.expectedBindings);if(r.push(...i.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&r.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),r.length>0)throw new ii([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:r}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let n=await hk({paths:e.paths,state:e.state,receipt:t});if(n){let a=PH({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 AH(e){let t=_H({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),r=[];for(let i of e.requiredReceiptRefs){let n=await mk({...e,ref:i,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof ii)return r.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 i of e.trace.entries)if(i.status!=="missing")for(let n of i.evidenceRefs){let a=await mk({...e,result:i.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:i.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof ii)return r.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(i.status==="failed"&&a.status==="passed")throw new Error("Native failed acceptance evidence must reference a non-passing receipt")}}if(r.length>0)throw new ii(r)}function hh(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function mh(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:hh(e.state.verification_result,"missing"),envelope:null};try{let[t,r]=await Promise.all([vk(e),Dn(e.paths,e.state.name,e.state.verification_evidence)]);if(r.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:hh(e.state.verification_result,"stale"),envelope:null};let i=await RH({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),n=[...t.findingCodes];(i.hash!==r.reportHash||i.ref!==r.reportRef)&&n.push("verification-report-stale"),(r.result!==e.state.verification_result||r.implementationScopeRef!==e.state.implementation_scope||r.partialAllowanceRef!==e.state.partial_allowance||r.sourceRevision>=e.state.revision||r.contractHash!==t.bundle.scope.contractHash||r.acceptanceCriteriaHash!==t.acceptanceHash)&&n.push("verification-state-mismatch");try{await AH({paths:e.paths,state:e.state,result:r.result,trace:r.acceptanceTrace,requiredReceiptRefs:r.requiredReceiptRefs,contractHash:r.contractHash,implementationScope:t.bundle,sourceRevision:r.sourceRevision})}catch{n.push("verification-receipt-invalid")}let a=[...new Set(n)].sort(),o=a.length>0?"stale":r.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:r.contractHash,acceptanceHash:r.acceptanceCriteriaHash,implementationScopeHash:r.implementationScopeHash,reportHash:r.reportHash,envelopeHash:r.envelopeHash,partialAllowanceHash:r.partialAllowanceHash,skippedAcceptanceCount:r.acceptanceTrace.skipped},envelope:r}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:hh(e.state.verification_result,"invalid"),envelope:null}}}function TH(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function yk(e){try{return await IH.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function jH(e,t){try{return(await ne({root:e,ref:t,maxBytes:null})).hash}catch(r){if(r.code==="ENOENT")return null;throw r}}async function $H(e,t,r){let i=so(e,r.capability);if(!q(e.nativeRoot,i))throw new Error(`Native canonical spec escapes its root: ${r.capability}`);let n=wk.relative(e.nativeRoot,i).replaceAll("\\","/"),a=await jH(e.nativeRoot,n),o=null;if(r.operation!=="remove"){if(!r.source)throw new Error(`Native proposed spec is missing: ${r.capability}`);o=(await ne({root:Ne(e,t),ref:r.source,maxBytes:null})).hash}return{capability:r.capability,operation:r.operation,expectedBaseHash:r.operation==="create"?null:r.base_hash,actualBaseHash:a,proposedHash:o}}async function OH(e,t){return yk(Zf(e,t))}async function vh(e){let t=e.now??new Date,r=await sr(e.paths,e.name),i=await or(e.paths,e.name),n=await Te(e.paths.projectRoot),a=TH(r.name,t),o=wk.resolve(e.paths.nativeRoot,...a.split("/"));if(!q(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,p,f]=await Promise.all([Promise.all(r.spec_changes.map(m=>$H(e.paths,r.name,m))),mh({paths:e.paths,state:r,now:t}),xl(e.paths,r.name),qc(e.paths,r.name),Ry(e.paths,r.name),OH(e.paths,r.name),yk(o)]);return rk({change:r.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:r.schema,revision:r.revision,phase:r.phase,archived:r.archived,pendingJournal:u||d||p,targetRef:a,targetExists:f,specs:s,evidence:c.evidence,workspace:i?.schema==="comet.native.workspace.v3"?{schema:i.schema,isolation:i.isolation,changeBranch:i.changeBranch,targetBranch:i.targetBranch,finish:i.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}U();ti();_o();Ti();async function HH(e,t){let r=Y(e,t.name),i=await kn(r);if(!i||!t.run_id||i.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let n=await Oc(r,i.checkpointRef);if(!n||n.runId!==i.runId||n.stateVersion!==i.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await bi(r,i.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:i.runId}}async function DH(e,t){let r=await HH(e,t);return{committed:r,latest:Ib(r),history:Ab(r)}}async function Nk(e,t,r){if(t.phase!=="build"||t.verification_result!=="fail")return null;let i=await DH(e,t),n=i.latest;if(!n)return null;let a=i.history.filter(c=>c.kind==="failure"),o=a.length>=r,s=n.disposition==="hard-stop"&&!o?"continue":n.disposition;return{disposition:o?"hard-stop":s,signatureHash:n.signatureHash,overrideRecorded:i.history.some(c=>c.kind==="override"&&c.signatureHash===n.signatureHash),failedAcceptanceIds:[...n.failedAcceptanceIds],failedCheckIds:[...n.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:r,remainingVerifyFailures:Math.max(0,r-a.length)}}ti();wt();U();function qo(e,t){try{return Da(e,t)}catch{return}}var mr=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function FH(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function LH(e){return(await bb(e))?.change??null}function qH(e,t,r=!1,i){return Nl({state:e,archiveReady:t,evidenceRetreat:r}).command}async function MH(e,t){let r=Ne(e,t.name),i=[...(await Vc(r,t.brief)).findings,...(await Dy(e,t)).findings,...await kb(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await Pc(e,t.name);if(n===null)i.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await ny(e,n);a.complete||i.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){i.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${n.message}`})}if(t.phase==="build")try{let n=await xn({changeDir:r,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==n.contract.contractHash&&i.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){i.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${n.message}`})}try{await qb(e,t.name)&&i.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(n){i.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${n.message}`})}return t.verification_report?i.push(...(await Jp(r,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&i.push({code:"verification-report-missing",message:"Native change has no verification report"}),i}async function gh(e,t,r){let i=await LH(e)===t,n=await Zd(e,t),a=await ro(e,t),o;try{let y=await Vp(e,t);if(y.status==="migration-required"&&y.state)return{name:t,artifacts:qo(e,t),phase:y.state.phase,revision:"revision"in y.state?y.state.revision:null,approval:y.state.approval,verificationResult:y.state.verification_result,specChanges:y.state.spec_changes.length,selected:i,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:y.schema,migrationRequired:!0,minimumRuntimeVersion:y.minimumRuntimeVersion,error:y.message};if(y.status!=="current"||!y.state)return{name:t,artifacts:qo(e,t),phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:i,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:y.schema,minimumRuntimeVersion:y.minimumRuntimeVersion,error:y.message??`Native change ${t} is incompatible`};o=y.state}catch(y){return{name:t,artifacts:qo(e,t),phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:i,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:y.message}}if(n.status!=="available"){let y={code:n.status==="missing"?"runtime-missing":"runtime-storage-invalid",message:n.status==="missing"?`Native Runtime is missing; continue ${o.name} to rebuild local execution state`:n.message??"Native Runtime storage is invalid",path:n.path},C=nh({paths:e,state:o,findings:[y]}),O=Nl({state:o,findings:C});return{name:o.name,artifacts:qo(e,o.name),phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:i,nextCommand:O.command,archiveReady:!1,inspection:{freshness:"stale",codes:[y.code],reasonCount:1,codesTruncated:!1},findingSummary:ah(C),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:O,workspace:a,runtime:n,...r?.details?{findings:C}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:y.message}:{}}}let s=await Zb({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await Nk(e,o,r?.maxVerifyFailures??5),c&&(c.disposition==="manual-stop"||c.disposition==="hard-stop")){let y=c.disposition==="hard-stop"?"repair-iteration-limit":c.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";l.push({code:y,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(r?.details&&(o.phase==="build"||o.phase==="verify"||o.phase==="archive"))try{let y=await xn({changeDir:Ne(e,o.name),briefRef:o.brief,specChanges:o.spec_changes}),C=new Map;if(o.phase==="build"&&o.verification_result==="fail"&&o.verification_evidence){let Q=await Dn(e,o.name,o.verification_evidence);for(let Pe of Q.acceptanceTrace.entries)C.set(Pe.acceptanceId,Pe.status==="failed"?"failed":Pe.status==="missing"?"missing":"satisfied")}let O=vw({criteria:y.contract.acceptance,acceptanceHash:y.contract.acceptanceHash,verificationStatuses:C,failedCheckIds:c?.failedCheckIds??[],...r.acceptanceCursor?{cursor:r.acceptanceCursor}:{}}),j=O.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",O.nextCursor,"--project-root",e.projectRoot]:null;u={...O,...j?{nextPageCommand:FH(j),nextPageArgs:j}:{}}}catch(y){if(r.acceptanceCursor)throw y;u=void 0}let d=[];if(r?.includeConflictFindings!==!1)try{let y=await xl(e,o.name,{tolerateInvalidSiblings:!0});d.push(...y.findingCodes.map(C=>({code:C,message:`Native change overlap is visible in the current root: ${C}`})))}catch{d.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let p=[];try{let y=await or(e,o.name);if(y)if(y.schema==="comet.native.workspace.v3"){let C=await En({paths:e,identity:y});C.state==="drifted"&&C.code&&p.push({code:C.code,message:C.message??"Native workspace binding is no longer valid"})}else{let C=await Bc({paths:e,identity:y});p.push(...C.findingCodes.map(O=>({code:O,message:`Native workspace advisory changed: ${O} (${C.driftComponents.join(", ")||"no-component"})`})))}}catch{p.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let f=[],m=!1;if(o.phase==="verify"){let y=await gk({paths:e,state:o});m=y.freshness!=="fresh",f.push(...y.findingCodes.map(C=>({code:C,message:`Native Verify implementation scope is not current: ${C}`})))}let h=null,v=[];if(o.phase==="archive")try{h=await vh({paths:e,name:o.name}),v.push(...h.findingCodes.map(y=>({code:y,message:`Native Archive is blocked: ${y}`})))}catch{v.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let g=[...await MH(e,o),...s.findings,...d,...p,...f,...l,...v].filter((y,C,O)=>O.findIndex(j=>j.code===y.code&&j.path===y.path)===C),b=nh({paths:e,state:o,findings:g}),k=b.filter(y=>!Sn(y.code)),N=o.phase==="archive"&&h?.ready===!0&&k.length===0,x=m||o.phase==="archive"&&(h?.findingCodes??[]).some(y=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(y)),w=b.some(y=>y.code==="trajectory-tail-incomplete"||y.code==="trajectory-invalid"||y.requiredAction==="return-to-bound-working-directory"||y.requiredAction==="repair-workspace-binding"),S=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",E=b.find(y=>y.severity==="error");return{name:o.name,artifacts:qo(e,o.name),phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:i,nextCommand:w||S?null:qH(o,N,x,r?.clarificationMode),archiveReady:N,inspection:s.inspection,findingSummary:ah(b),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:Nl({state:o,findings:b,archiveReady:N,evidenceRetreat:x,clarificationMode:r?.clarificationMode}),workspace:a,runtime:n,repair:c,...r?.details?{...u?{acceptancePage:u}:{},findings:b.slice(0,50),inspectionDetails:s.inspectionDetails,checkpointDetails:s.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:Sl,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:b.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...E?{error:E.message}:{}}}async function bk(e){let t;try{t=await Ep({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[],i=await BH.opendir(e.changesDir);try{for await(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink())&&(r.push(n.name),r.length>mr.maxChanges))throw new Error(`Native status exceeds ${mr.maxChanges} visible changes`)}finally{await i.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),r.sort()}U();var yh=Kt(It(),1);ot();ue();et();gt();import{promises as VH}from"node:fs";import wh from"node:path";var Rl=class extends Error{};async function _l(e,t){let r=await ne({root:e.nativeRoot,ref:wh.relative(e.nativeRoot,t).replaceAll("\\","/"),maxBytes:null,includeHash:!1}),i=(0,yh.parse)(r.text);if(["comet.native.v1","comet.native.v2","comet.native.v3"].includes(i?.schema))throw new Rl("Historical Native schema");return{projectRoot:e.projectRoot,file:t,state:qe(i)}}async function Sk(e,t,r){let i;try{i=await VH.readdir(e.archiveDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return[];throw a}if(i.length>4096)throw new Error("Native archive discovery exceeds 4096 records");let n=[];for(let a of i){if(!a.isDirectory()||a.isSymbolicLink())continue;let o=/^\d{4}-\d{2}-\d{2}-(.+)$/u.exec(a.name)?.[1];if(r!==void 0&&o!==void 0&&o!==r)continue;let s=wh.join(e.archiveDir,a.name,"comet-state.yaml");try{let c=await _l(e,s);c.state.archived&&c.state.status==="done"&&n.push(c)}catch(c){if(c.code==="ENOENT"||c instanceof Rl)continue;let l=a.name.replace(/^\d{4}-\d{2}-\d{2}-/u,"");t?.(l,`Native archive ${a.name} is unreadable: ${c.message}`)}}return n}function Pl(e){return T("comet.native.status-record.v1",e)}function kk(e){let t=wh.relative(e.projectRoot,e.file).replaceAll("\\","/");try{let r=Ve(e.projectRoot,["log","-1","--format=%H","HEAD","--",t]);if(!r)return null;let i=qe((0,yh.parse)(Ve(e.projectRoot,["show",`${r}:${t}`])));return Pl(i)===Pl(e.state)?r:null}catch{return null}}function Ek(e,t){if(!e.state.archived||e.state.status!=="done"||e.state.name!==t.state.name||e.state.created_at!==t.state.created_at)return!1;let r=kk(e),i=kk(t);if(!r||!i)return!1;try{return Ve(e.projectRoot,["merge-base","--is-ancestor",i,r]),!0}catch{return!1}}function xk(e,t){return e.state.archived&&t.state.archived&&Pl(e.state)===Pl(t.state)}import $k from"node:path";import{promises as Ck}from"node:fs";import WH from"node:path";ue();var zH=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),GH=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),JH=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task","builderFailureCount"]),UH=new Set(["status","summary"]);function Al(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Il(e,t,r,i=new Set){let n=new Set(Object.keys(e)),a=[...t].filter(s=>!n.has(s)&&!i.has(s)),o=[...n].filter(s=>!t.has(s));return a.length===0&&o.length===0?null:`${r} fields must be exact (missing: ${a.join(", ")||"none"}; unexpected: ${o.join(", ")||"none"})`}function KH(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((r,i)=>r===t[i])}function $i(e,t,r){return{status:"incompatible",file:e,snapshot:t,message:r}}function YH(e,t,r,i){let n=Al(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=Il(n,zH,"Native Supervisor overlay");if(a)return a;if(i.stateVersion!==1)return"Native Supervisor overlay stateVersion is not 1";if(i.parent!==t.name)return`Native Supervisor overlay parent ${i.parent} does not match ${t.name}`;let o=Al(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=Il(o,GH,"Native Supervisor integration");if(s)return s;if(i.integration.headCommit!==i.integration.targetCommit)return"Native Supervisor integration headCommit has advanced beyond targetCommit";if(!Array.isArray(n.history)||n.history.length!==0)return"Native Supervisor overlay history is not empty";let c=Al(n.finalVerification,"Native Supervisor finalVerification");if(!c)return"Native Supervisor finalVerification must be an object";let l=Il(c,UH,"Native Supervisor finalVerification");if(l)return l;if(i.finalVerification.status!=="pending"||i.finalVerification.summary!==null)return"Native Supervisor final verification already contains progress";if(!Array.isArray(n.children))return"Native Supervisor children must be an array";if(n.children.length!==r.children.length)return"Native Supervisor child count does not match the legacy children contract";for(let[u,d]of n.children.entries()){let p=Al(d,`Native Supervisor child ${u}`);if(!p)return`Native Supervisor child ${u} must be an object`;let{acceptanceScope:f,contractHash:m,...h}=p,v=Il(h,JH,`Native Supervisor child ${u}`,new Set(["builderFailureCount"]));if(v)return v;let g=r.children[u],b=g.covers.length>0?g.covers.map(N=>({id:N,source:r.acceptance_index?.[N]?.source??"brief.md",text:r.acceptance_index?.[N]?.text??N})):[{id:`child:${g.name}`,source:"children.yaml",text:g.summary??g.name}];if(f!==void 0&&JSON.stringify(f)!==JSON.stringify(b)||m!==void 0&&m!==T("comet.native.supervisor-contract.v1",r))return`Native Supervisor child ${g.name} acceptance scope does not match the legacy contract`;if(p.name!==g.name||p.summary!==g.summary||!KH(p.dependsOn,g.depends_on))return`Native Supervisor child ${g.name} does not match the legacy children contract`;let k=g.depends_on.length===0?"ready":"pending";if(p.status!==k)return`Native Supervisor child ${g.name} has progressed beyond its initial ${k} status`;if(p.baseCommit!==null||p.candidateCommit!==null||p.verifiedCommit!==null||p.integrationCommit!==null||p.verification!==null||p.blocker!==null||p.projectRoot!==null||p.task!==null)return`Native Supervisor child ${g.name} contains execution progress`;if((p.builderFailureCount??0)!==0)return`Native Supervisor child ${g.name} contains Builder failure progress`;if(!Array.isArray(p.checks)||p.checks.length!==0)return`Native Supervisor child ${g.name} contains integration checks`}return null}async function Rk(e){let t=yo(e.paths,e.state.name),r;try{let c=await Ck.lstat(t);if(!c.isFile()||c.isSymbolicLink())return $i(t,"","Native Supervisor overlay is not a regular file");r=await Ck.readFile(t,"utf8")}catch(c){return c.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:$i(t,"",`Native Supervisor overlay cannot be read: ${c.message}`)}let i;try{i=JSON.parse(r)}catch(c){return $i(t,r,`Native Supervisor overlay is invalid JSON: ${c.message}`)}let n=WH.join(e.paths.changesDir,e.state.name),a;try{a=await Vt({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:c})=>c),policy:"advisory"})}catch(c){return $i(t,r,`Native children contract cannot be validated; restore children.yaml and retry next: ${c.message}`)}if(!a||a.contract.schema!=="comet.native.children.v1")return{status:"compatible",file:t,message:"The current Native children contract is not legacy children.v1",snapshot:r};let o;try{o=await Ue(e.paths,e.state.name)}catch(c){return $i(t,r,`Native Supervisor overlay is invalid: ${c.message}`)}if(!o)return $i(t,r,"Native Supervisor overlay disappeared during inspection");let s=YH(i,e.state,a.contract,o);return s?$i(t,r,s):{status:"repairable-legacy-overlay",file:t,message:"An exact unstarted v2 Supervisor overlay is stale beside a legacy children.v1 contract",snapshot:r}}Ga();Ri();function be(e,t,r){return e.language==="zh-CN"?r:t}function XH(e,t,r,i){let n=a=>({required:!1,message:null,suggestedReply:null,agentInstruction:a});if(e.phase==="shape"&&e.status==="await-user"&&e.loop.next_action==="confirm-shape")return t?{required:!0,message:be(e,"Shape is ready. Confirm the complete plan and choose A) Multi-session coordination (recommended), or B) Single-session progression in one reply.","Shape 已整理完成。请确认完整方案,并在同一次回复中选择 A)多会话协作(推荐),或 B)单会话推进。"),suggestedReply:be(e,"Confirm the plan and use A","确认方案,按 A 开始"),agentInstruction:be(e,"First present the target, scope, key decisions, acceptance criteria, non-goals, child responsibilities and dependencies, and both coordination choices. Execute the matching confirm-shape alternative only when the user explicitly accepts this complete Shape and chooses its mode. Choosing a mode alone, additions, or corrections are not full confirmation; retain that choice and ask only for the missing decision. Do not run --confirmed before full confirmation.","先展示目标、范围、关键决定、验收标准、非目标、各 Child 的职责与依赖,以及两种推进方式。只有用户明确同意当前完整 Shape 并选择推进方式后,才执行对应的 confirm-shape 选项。仅选择推进方式、补充或修改要求都不算完整确认;保留已选方式,只补问缺少的决定。完整确认前不要运行 --confirmed。")}:e.language==="zh-CN"?{required:!0,message:"Shape 已整理完成。请确认目标、范围、关键决定、验收标准和非目标是否准确;明确确认后才会进入 Build。",suggestedReply:"确认进入 Build",agentInstruction:"先用自然语言简要展示目标、范围、关键决定、验收标准和非目标,再转述 message 并等待用户明确确认。只有用户明确同意当前完整 Shape 时,才执行 commandAlternatives 中的 confirm-shape;补充或修改要求不算确认。不要展示机器状态或提前运行 --confirmed。"}:{required:!0,message:"Shape is ready. Confirm that the target, scope, key decisions, acceptance criteria, and non-goals are accurate; Build starts only after explicit confirmation.",suggestedReply:"Confirm and enter Build",agentInstruction:"First present a concise natural-language summary of the target, scope, key decisions, acceptance criteria, and non-goals. Then relay message and wait for explicit user confirmation. Run confirm-shape from commandAlternatives only when the user explicitly accepts the complete current Shape; additions or corrections are not confirmation. Do not expose machine state or run --confirmed early."};if(t&&e.phase==="shape"&&e.status==="active")return n(be(e,"Complete the Shape documents and child plan, resolve blocking questions, then execute prepare-shape-confirmation. Its persisted response combines complete Shape confirmation and coordination choice in one user decision. If the user already chose only a mode, include that --coordination-mode when preparing and ask only for complete Shape confirmation afterward.","完成 Shape 文档和 Child 计划,解决阻塞问题后执行 prepare-shape-confirmation。持久化后的响应会让用户一次确认完整 Shape 并选择推进方式。如果用户已经仅选择了推进方式,准备时附上对应的 --coordination-mode,随后只确认完整 Shape。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready"&&e.loop.next_action!=="await-verifier-result")return n(be(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"){let a=i==="confirmed"?be(e,"The Verifier has confirmed startup. Continue waiting on the same host task and use its actual progress.","Verifier 已确认启动。继续等待同一个宿主任务,并使用该任务的实际进度。"):be(e,"Check whether the host accepted the startup call and locate the task for the current verifierExecutionRef. If the call has not been made, start the dispatched task once; if the host accepted it, check that same task and let the Verifier submit its startup receipt. A missing receipt alone does not prove failure. If local startup state is unavailable, recover the host task context before deciding whether startup is needed.","先核实宿主是否接受了启动调用,并找到当前 verifierExecutionRef 对应的任务。尚未调用时启动已派发的任务一次;宿主已接受时检查同一个任务,由 Verifier 提交启动回执。仅缺少回执不能证明执行失败。本地启动记录不可用时,先恢复宿主任务上下文,再判断是否需要启动。");return n(`${a} ${be(e,"Keep the same dispatched Verifier while it is active. A wait-tool timeout is not an execution timeout: check task progress and continue waiting; do not cancel, interrupt, or spawn a replacement just because a wait returned without a result. Request progress without telling the Verifier to stop inspecting. Only after confirmed task failure, a host-reported execution timeout, loss, or termination without a usable result, immediately submit verifier-execution-error. Preserve completed evidence and explain the failure and changed recovery approach before retrying. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Forward the actual report, including risks and incomplete checks; never turn an uninspected candidate into pass. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","已派发的验收任务仍在运行时,继续使用同一个 Verifier。等待工具超时不等于执行超时:检查任务进度并继续等待,不得仅因一次等待没有结果就取消、中断或重新派发。询问进度时不要要求停止核查。仅在确认任务失败、宿主报告执行超时、任务丢失或结束后没有可用结果时,立即提交 verifier-execution-error;保留已完成证据,重试前说明失败原因及恢复方式的变化。只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。忠实传递原始报告,包括风险和未完成检查;没有核查当前候选不能判定通过。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。")}`)}if(e.status==="blocked"&&e.blockers.some(({resolution_action:a})=>a==="retry-verifier"))return e.loop.retry_epoch>=3?e.language==="zh-CN"?{required:!0,message:"自动重试验收已连续多轮未能取得结果,验证环境很可能不可用。请人工检查验证环境(subagent 配额、平台任务队列、网络),或使用 doctor --repair 评估该 change 状态。",suggestedReply:"人工检查验证环境",agentInstruction:"只向用户转述 message,等待用户完成人工检查后再继续。不要自动重试验收。"}:{required:!0,message:"Automatic verification retries have failed across multiple rounds; the verification environment is likely unavailable. Inspect the environment manually (subagent quota, platform task queue, network), or use doctor --repair to assess the change state.",suggestedReply:"Inspect the verification environment",agentInstruction:"Relay message to the user and wait for a manual environment check before continuing. Do not retry verification automatically."}: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 o=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",s=o?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。注意:预算不会重置,选择继续修复后,下一次验收失败会再次暂停。",c=o?"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:s,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:c,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."}}if(e.phase==="verify"&&e.status==="await-user"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass")return{required:!0,message:be(e,"The reported verification passed, but this platform cannot confirm an independent Verifier execution. Review the result and choose whether to accept it for Archive, revise the implementation, or revise the requirements."+(e.workspace.isolation!=="current"&&e.workspace.finish===null?" If accepting, also choose: keep the workspace, merge locally, push the branch, or push and create a PR. You may accept the result and defer the finish choice.":""),"当前验收报告已通过,但当前平台无法确认验收是否独立执行。请检查结果,并选择接受结果进入归档、继续修改实现,或调整需求。"+(e.workspace.isolation!=="current"&&e.workspace.finish===null?" 接受时可一起选择:保留工作区、本地合并、推送分支,或推送并创建 PR;也可以先接受结果,稍后再选择收尾方式。":"")),suggestedReply:be(e,"Accept the result","接受结果"),agentInstruction:be(e,"Summarize the result and verification evidence, relay the message, and wait for an explicit user decision. Only then execute the matching commandAlternative. Do not accept the result on the user’s behalf.","简要说明交付结果和验收证据,转述 message,并等待用户明确选择后再执行对应的 commandAlternative。不要替用户接受结果。")};if(e.phase==="build"&&e.status==="active"){let a=r?.children.some(({status:l})=>l==="blocked")??!1,o=r?.children.some(({status:l})=>l==="needs-reverify")??!1,s=r?.children.some(({status:l})=>l==="ready"||l==="active")??!1,c=r?.children.some(({status:l,builderFailureCount:u})=>l==="blocked"&&(u??0)>=rl)??!1;return a&&!o&&!s&&!c?e.language==="zh-CN"?{required:!0,message:"Supervisor 子任务暂时无法启动,已暂停自动重试以避免流程循环。请先根据子任务 blocker 修复工作区、分支或依赖;修复完成后重新运行最新的 next 继续流程。代码和已有证据已保留。",suggestedReply:"修复 blocker 后继续",agentInstruction:"向用户说明子任务 blocker 和需要先完成的外部修复;不要反复执行 next,也不要创建替代任务。用户确认工作区或依赖已修复后,再重新读取 status 并执行最新 continuation。"}:{required:!0,message:"Supervisor child dispatch is paused because every remaining child is blocked. Automatic retries are stopped to avoid a loop. Resolve the recorded child blocker (workspace, branch, or dependency) first, then read the latest status and continue; code and completed evidence are preserved.",suggestedReply:"Resolve the blocker and continue",agentInstruction:"Explain the child blocker and the required external repair to the user. Do not repeatedly run next or spawn replacement tasks. After the user confirms the workspace or dependency is fixed, read status again and execute the latest continuation."}:n(be(e,"Implement the complete confirmed brief and Spec scope, then review every acceptance ID with its implementation and evidence before handoff. Fill acceptance_review from this audit; derive remaining work from it. Do not submit a partial candidate just to obtain verification feedback. Run focused checks; a separate pre-review is optional. If review is useful, retain the same Reviewer for focused repair follow-ups. Submit the completed candidate for one complete independent verification and release completed helper tasks.","完成已确认的 brief 和 Spec 全部范围,交接前逐项核对所有验收 ID 的实现和证据,填写 acceptance_review,并由这份自查生成剩余工作。不得提交未完成的候选来试探验收反馈。开发期运行相关检查,额外预审为可选项;确需审查时,保留同一个 Reviewer 复核修复及受影响范围。全部完成后提交一次完整独立验收,及时释放已完成的辅助任务。"))}return n(be(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 QH(e){let t=e.workspace.change_branch??"<change-branch>",r=e.workspace.target_branch??"<target-branch>";return e.language==="zh-CN"?{required:!0,message:`当前 change 位于 ${t},目标分支为 ${r}。请选择一次工作区收尾方式:A) 保留工作区;B) 本地合并;C) 推送分支;D) 推送并创建 PR;E) 暂不归档。选择 A-D 后 Runtime 会完成预检,检查通过后按所选方式归档;选择 E 将保留当前 change 等待稍后继续。`,suggestedReply:"回复 A、B、C、D 或 E",agentInstruction:"向用户展示五种收尾方式及实际影响,等待用户选择。选择 A-D 时执行对应 commandAlternatives 的完整命令,Runtime 会在归档前检查状态和证据;选择 E 时停止,不运行 Archive 命令。按用户的明确选择执行 finish。"}:{required:!0,message:`This change is on ${t} and targets ${r}. Choose one workspace finish: A) keep the workspace; B) merge locally; C) push the branch; D) push and create a PR; or E) defer Archive. For A-D, Runtime will run preflight and archive with the selected finish when the checks pass; E keeps the current change for later.`,suggestedReply:"Reply A, B, C, D, or E",agentInstruction:"Show all five finish choices and their actual effects, then wait. For A-D, execute the matching complete commandAlternative; Runtime checks state and evidence before archiving. For E, stop without running an Archive command. Use the finish explicitly selected by the user."}}function ZH(e){return[...[{finish:"keep",name:"keep-workspace",description:["保留当前分支和目录;完成归档提交,不合并、不推送、不创建 PR。","Keep the current branch and directory; create the archive commit without merging, pushing, or creating a PR."]},{finish:"merge",name:"merge-locally",description:["完成归档提交,并把 change 分支本地合并到目标分支;不推送、不创建 PR。","Create the archive commit and merge the change branch locally into the target branch without pushing or creating a PR."]},{finish:"push",name:"push-branch",description:["完成归档提交并推送 change 分支;不合并到目标分支、不创建 PR。","Create the archive commit and push the change branch without merging into the target branch or creating a PR."]},{finish:"pull-request",name:"push-pull-request",description:["完成归档提交、推送 change 分支,并以目标分支为基础创建 PR。","Create the archive commit, push the change branch, and create a PR against the target branch."]}].map(({finish:i,name:n,description:a})=>({name:n,stateVersion:e.state_version,expectedAction:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed","--finish",i,"--expected-state-version",String(e.state_version)],requiredInputs:[],inputOptions:[],description:be(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:be(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function Ik(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Oi(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function Pk(){return{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}}function eD(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function _k(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function tD(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function rD(e){return["comet","native","next",e.change,"--summary","<summary>","--expected-state-version",String(e.stateVersion),"--expected-action","prepare-shape-confirmation"]}function Jt(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:Ik({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Oi("summary","--summary"),eD(e.name,e.flag)]}}function Ak(e,t){return t.some(i=>/^verification\.md is (?:missing|stale|invalid)$/u.test(i))?[{name:"repair-verification-report",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],inputOptions:[],description:be(e,"Rebuild the Runtime-managed verification report, then rerun the Archive dry-run.","重建由 Runtime 管理的 verification.md,然后重新运行 Archive 预检。")}]:[]}function iD(e){return/^verification\.md is (?:missing|stale|invalid)$/u.test(e)}function Tl(e){return[Jt({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Jt({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function nD(e){let t={"request-checks":"Choose when the Verifier needs additional Runtime checks.","final-result":"Choose when the Verifier has a result for every current scope ID.","verifier-execution-error":"Choose when a dispatched Verifier failed, was lost, or ended without a result.","verifier-unavailable":"Choose only when the platform has no usable independent Verifier capability."};return e.flatMap(r=>Array.isArray(r.template)?r.template.map(i=>{let n=i.response?.kind??i.kind;return{...r,name:n,required:!1,exclusiveGroup:"runner-input",description:t[n],template:i}}):[r])}function Mo(e,t,r={}){let i=tD(t)&&e.coordination_mode===void 0,n=XH(e,i,t,r.verifierStartup),a={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],requiresUserDecision:n.required,userCommunication:n},o=s=>({kind:s,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...a,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:o("none")};if(e.status==="await-user")return e.phase==="shape"&&e.loop.next_action==="confirm-shape"?{...a,disposition:"await-user",action:"confirm-shape",commandArgs:null,requiredInputs:["summary","shared-understanding-confirmation",...i?["coordination-choice"]:[]],inputOptions:[Oi("summary","--summary")],commandAlternatives:i?Nw.map(s=>{let c=Jt({name:`confirm-shape-${s}`,change:e.name,stateVersion:e.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"});return{...c,commandArgs:[...c.commandArgs,"--coordination-mode",s],requiredInputs:[...c.requiredInputs,"coordination-choice"],inputOptions:[...c.inputOptions,_k("coordination-mode","--coordination-mode",[s])]}}):[Jt({name:"confirm-shape",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"})],runnerAction:o("none")}:e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...a,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Oi("summary","--summary")],commandAlternatives:[...e.workspace.isolation!=="current"&&e.workspace.finish===null?["keep","merge","push","pull-request"].map(s=>{let c=Jt({name:`accept-result-${s}`,change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"});return{...c,commandArgs:[...c.commandArgs,"--finish",s]}}):[],Jt({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...Tl({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...a,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Oi("summary","--summary")],commandAlternatives:[Jt({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),Jt({name:"confirm-verifier-unavailable",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-verifier-unavailable",flag:"--confirmed",confirmationInput:"user-decision"})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...a,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Oi("summary","--summary")],commandAlternatives:[Jt({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...Tl({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...a,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Oi("summary","--summary")],commandAlternatives:Tl({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,commandAlternatives:Tl({change:e.name,stateVersion:e.state_version}),userCommunication:{...a.userCommunication,required:!0,message:e.blockers.length>0?e.blockers.map(({reason:s})=>s).join("; "):a.userCommunication.message,suggestedReply:e.blockers.length>0?e.blockers[0]?.resolution_action??null:a.userCommunication.suggestedReply},requiredInputs:["resolve-blocker"],runnerAction:o("none")};if(e.status==="blocked"){let s=e.blockers.some(({resolution_action:c})=>c==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?Ik({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:s?["summary"]:["repair-runtime"],inputOptions:s?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:o(s?"retry-verifier":"none")}}if(e.phase==="shape")return{...a,disposition:"continue",action:"prepare-shape-confirmation",commandArgs:rD({change:e.name,stateVersion:e.state_version}),requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...a,disposition:"continue",action:"repair",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["repair-child"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(t.allDone)return{...a,disposition:"continue",action:"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:e.acceptance.map(({id:m})=>m),acceptance_review:e.acceptance.map(({id:m})=>({id:m,status:"not-implemented",evidence:[],note:"<implementation and evidence summary>"})),checks:[{name:"<check-name>",result:"not-run",note:null}],verification_checks:[Pk()],known_limits:[]}}],runnerAction:o("builder-handoff")};let s=t.children.find(({status:m})=>m==="verified");if(s){let m=r.supervisorIntegrationRetryIds;return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["supervisor-integration-checks"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-integrate",child:s.name,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}],...m&&m.length>0?{retry_check_ids:[...m]}:{}}}],runnerAction:o("none")}}let c=t.children.some(({status:m})=>m==="blocked"||m==="needs-reverify"),l=t.children.some(({status:m})=>m==="needs-reverify"),u=t.children.some(({status:m})=>m==="ready"||m==="active"),d=t.supervisorStateVersion===void 0?null:t.children.find(m=>m.status==="blocked"&&(m.builderFailureCount??0)>=rl)??null,p=d===null?null:{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-retry-builder",child:d.name,stateVersion:t.supervisorStateVersion},description:be(e,"Explicitly authorize one fresh Builder attempt after the Builder failure budget was exhausted.","Builder 失败预算已耗尽;明确授权后才能重新开始一次 Builder 尝试。")},f=c&&!l&&!u&&p===null;return{...a,disposition:f?"blocked":"continue",action:"advance-children",commandArgs:f?null:p!==null?["comet","native","next",e.name,"--runner-input","<temporary-json-file>"]:["comet","native","next",e.name,"--summary","<summary>",...e.coordination_mode==="single-session"?["--max-parallel","1"]:[]],requiredInputs:f?[]:p!==null?["supervisor-builder-retry-json-file"]:["ready-children"],inputOptions:f?[]:p!==null?[p]:[Oi("summary","--summary")],runnerAction:o("none")}}return{...a,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:e.acceptance.map(({id:s})=>s),acceptance_review:e.acceptance.map(({id:s})=>{let c=e.builder_handoff?.acceptance_review?.find(l=>l.id===s);return c?{...c,evidence:[...c.evidence],...e.loop.previous_unresolved_ids.includes(s)?{status:"implemented-no-evidence",evidence:[],note:"<current repair and evidence summary>"}:{}}:{id:s,status:"not-implemented",evidence:[],note:"<implementation and evidence summary>"}}),checks:[{name:"<check-name>",result:"not-run",note:null}],verification_checks:[],known_limits:[]}}],runnerAction:o("builder-handoff")}}if(e.phase==="verify"){let s=e.loop.next_action==="await-verifier-result",c=!!e.children_contract_hash,l=Pk();return!s&&r.retryCheckIds&&r.retryCheckIds.length>0?{...a,disposition:"continue",action:"retry-checks",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["retry-checks-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"retry-checks",check_ids:[...r.retryCheckIds]}}],runnerAction:o("retry-checks")}:{...a,userCommunication:!s&&c?{...a.userCommunication,agentInstruction:`${a.userCommunication.agentInstruction} ${be(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:a.userCommunication,disposition:"continue",action:s?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[s?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:nD([{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:s?[{kind:"verifier-response",candidateId:e.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[l]}},{kind:"verifier-response",candidateId:e.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"blocked",acceptance:[{id:"<acceptance-id>",result:"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:r.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:r.verifierExecutionRef??"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:r.verificationCheckPlans?r.verificationCheckPlans.map(u=>({...u,argv:[...u.argv]})):c?[l]:[]}}]),runnerAction:o(s?"await-verifier":"dispatch-verifier")}}if(e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived){let s=r.archiveMode??"archive-ready",l=e.workspace.isolation!=="current"&&e.workspace.finish===null;if(s==="blocked")return{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")};if(s==="preview"){if(r.archiveBlockers&&r.archiveBlockers.length>0){let u=Ak(e,r.archiveBlockers)[0];return u&&r.archiveBlockers.every(d=>iD(d))?{...a,disposition:"continue",action:"repair",commandArgs:u.commandArgs,requiredInputs:[],inputOptions:[],runnerAction:o("none")}:{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],commandAlternatives:Ak(e,r.archiveBlockers),runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}return l?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[_k("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...ZH(e)],userCommunication:QH(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[Jt({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}import Tk from"node:path";function jk(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function Nh(e,t){let r=e.acceptance.reduce((i,n)=>({...i,[n.result]:i[n.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:r,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:jk(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},learning:{failureResolved:e.verification_result==="pass"&&e.history.some(i=>i.outcome==="fail"&&i.goal_cycle===e.loop.goal_cycle),...e.verification?{summary:jk(e.verification.summary.text)}:{},artifactRefs:t?["brief.md",...e.verification_report?[e.verification_report]:[],...e.spec_changes.map(i=>i.source).filter(i=>i!==null)].slice(0,16).map(i=>Tk.relative(t.projectRoot,Tk.join(t.changesDir,e.name,i)).replaceAll("\\","/")):[]},archived:e.archived}}U();function Ok(e,t,r){return`native-details-v2.${e}.${t}.${r.toString(36)}`}function Hk(e,t,r){if(!e)return 0;let i=/^native-details-v2\.(\d+)\.(\d+)\.([0-9a-z]+)$/u.exec(e);if(!i||Number(i[1])!==t||Number(i[2])!==r)throw new Error("Native details cursor is stale or invalid");let n=Number.parseInt(i[3],36);if(!Number.isSafeInteger(n)||n<0)throw new Error("Native details cursor offset is invalid");return n}function Dk(e,t,r){return[...e.acceptance.map(i=>({kind:"acceptance",value:i})),...e.spec_changes.map(i=>({kind:"spec-change",value:i})),...e.builder_handoff?[{kind:"builder-handoff",value:e.builder_handoff}]:[],...e.verification?[{kind:"verification",value:e.verification}]:[],...e.history.map(i=>({kind:"history",value:i})),{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(i=>({kind:"supervisor-child",value:sD(i,r)})),...t.history.map(i=>({kind:"supervisor-history",value:cD(i,r)}))]:[]]}function Bk(e){return e.acceptance.reduce((t,r)=>({...t,[r.result]:t[r.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0})}function aD(e,t){let r=t?.execution;if(e.phase!=="verify"||e.status!=="active"||e.loop.next_action!=="await-verifier-result"||!r||r.stage!=="verifying"||r.actor!=="verifier"||r.status!=="running")return;let i=r.verifierStartedAt??null,n=Qp(e,t??null);if(n===void 0)return;let a=n==="confirmed";return{attempt:e.loop.attempt,registeredAt:r.startedAt,confirmedAt:i,confirmation:a?"confirmed":"unconfirmed",...a?{}:{waitingMinutes:Math.max(0,Math.round((Date.now()-Date.parse(r.startedAt))/6e4))}}}function jl(e,t,r=ve(e.projectRoot)){let i=null;return t.workspace.change_branch!==null&&(r.isGitWorktree?r.currentBranch!==t.workspace.change_branch&&(i=`Expected branch ${t.workspace.change_branch}, current branch is ${r.currentBranch??"(detached)"}.`):i="The Native change requires a registered Git worktree."),i===null&&t.workspace.isolation==="worktree"&&!r.isSecondaryWorktree&&(i="The Native change requires its linked worktree."),{projectRoot:$k.resolve(e.projectRoot),isolation:t.workspace.isolation,bindingState:i===null?"aligned":"mismatch",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:i}}function bh(e){let{state:t,paths:r}=e,i=e.finishJournal??null,n=Nh(t),a=i!==null,o=i?.result?.message??"Native Archive completed, but workspace finish is still pending; retry the recorded finish command.",s=a?{...Mo(t),status:"blocked",disposition:"blocked",action:"archive",requiresUserDecision:!1,commandArgs:i?.result?.recoveryArgs??["comet","native","archive",t.name,"--confirmed"],requiredInputs:[],inputOptions:[],userCommunication:{required:!0,message:o,suggestedReply:null,agentInstruction:"Report the Git blocker and resolve it within the recorded delivery authorization, then retry the recorded Native workspace finish command. Ask the user only when new information or authorization is required; keep delivery pending until it succeeds."},runnerAction:{...Mo(t).runnerAction,kind:"none"}}:Mo(t),c=e.details?Dk(t,null,[]):[],l=Hk(e.cursor,t.state_version,0),u=c.slice(l,l+32),d=l+u.length<c.length?Ok(t.state_version,0,l+u.length):null;return{schema:"comet.native.status.v2",name:t.name,artifacts:Da(r,t.name),phase:t.phase,status:a?"blocked":t.status,stateVersion:t.state_version,archived:!0,archiveRef:$k.relative(r.projectRoot,e.file).replaceAll("\\","/"),loop:t.loop,acceptance:Bk(t),unresolvedAcceptanceIds:n.unresolved_acceptance_ids,verificationResult:t.verification_result,blockers:a?[...n.blockers,{owner:"runtime",reason:o,acceptance_ids:[],resolution_action:"wait-external"}]:n.blockers,workspace:{projectRoot:r.projectRoot,isolation:t.workspace.isolation,bindingState:"aligned",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:null},localExecution:{status:"not-expected",operation:null},continuation:s,...e.details?{details:{stateVersion:t.state_version,items:u,nextCursor:d,nextPageArgs:d?["comet","native","status",t.name,"--details","--cursor",d,"--project-root",r.projectRoot,"--json"]:null}}:{}}}function oD(e,t){return[e.projectRoot,t.integration.worktree,...t.children.flatMap(r=>[r.projectRoot,r.task?.projectRoot])].filter(r=>!!r).map(r=>r.replaceAll("/","\\")).sort((r,i)=>i.length-r.length)}function $l(e,t){return e===null?null:t.reduce((r,i)=>r.replaceAll(i,"<worktree>").replaceAll(i.replaceAll("\\","/"),"<worktree>"),e)}function sD(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:$l(e.blocker,t),task:e.task?{...e.task,projectRoot:"<worktree>",baseCommit:"<redacted>",runId:"<redacted>"}:null}}function cD(e,t){return{...e,runId:e.runId?"<redacted>":null,summary:$l(e.summary,t)??""}}async function Fk(e){let t=await ef(e),r=Nh(t.state),i=t.state.status==="active"&&t.state.loop.stage!=="done",n=await No({paths:e.paths,state:t.state}),a=await Rk({paths:e.paths,state:t.state}),o=a.status==="repairable-legacy-overlay"||a.status==="incompatible"?null:await Ue(e.paths,e.name,{diagnostics:!0}),s=o?{...jl(e.paths,t.state,e.gitContext),projectRoot:"."}:jl(e.paths,t.state,e.gitContext),c=Mo(t.state,n,{verifierExecutionRef:Xp(t.state,t.local),verifierStartup:Qp(t.state,t.localStatus==="available"?t.local:null),...t.local?{verificationCheckPlans:Nb(t.local,t.local.workspace.projectRoot)}:{}}),l=s.bindingState==="mismatch"?{...c,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["return-to-bound-workspace"],runnerAction:{...c.runnerAction,kind:"none"}}:c,u=o?oD(e.paths,o):[],d=o?(()=>{let m=new Map(n?.children.map(w=>[w.name,w.status])??[]),h=w=>m.get(w.name)??w.status,v=o.children.filter(w=>h(w)==="pending"||h(w)==="ready").length,g=o.children.filter(w=>h(w)==="active"||h(w)==="verified").length,b=o.children.filter(w=>h(w)==="integrated"||h(w)==="archived").length,k=o.children.filter(w=>h(w)==="blocked"||h(w)==="needs-reverify").length,N=o.children.filter(w=>h(w)==="active"||h(w)==="blocked"||h(w)==="needs-reverify").slice(0,16).map(w=>({name:w.name,summary:w.summary,projectRoot:w.task?.projectRoot??w.projectRoot?"<worktree>":null,reason:$l(w.blocker,u)})),x=o.children.flatMap(({blocker:w})=>{let S=$l(w,u);return S?[S]:[]}).slice(0,16);return{targetSpecs:t.state.spec_changes.length,implementationChildren:o.children.length,waiting:v,working:g,integrated:b,blocked:k,active:N,agents:{working:o.children.filter(({task:w})=>w!==null).length,completed:b},risks:x,nextAction:o.finalVerification.status==="passed"?"final-delivery":o.finalVerification.status==="pending"&&b===o.children.length?"parent-verification":v>0?"dispatch-ready-child":k>0?"resolve-blocker":"continue-supervisor"}})():null,p=e.details?(()=>{let m=o?.stateVersion??0,h=Dk(t.state,o,u),v=Hk(e.cursor,t.state.state_version,m),g=h.slice(v,v+32),b=v+g.length<h.length?Ok(t.state.state_version,m,v+g.length):null;return{items:g,nextCursor:b,supervisorStateVersion:m}})():null,f=o?{schema:o.schema,parent:o.parent,integration:{branch:o.integration.branch,targetBranch:o.integration.targetBranch},finalVerification:{status:o.finalVerification.status,summary:o.finalVerification.summary},summary:d}:null;return{schema:"comet.native.status.v2",name:t.state.name,artifacts:Da(e.paths,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:Bk(t.state),unresolvedAcceptanceIds:r.unresolved_acceptance_ids,verificationResult:t.state.verification_result,blockers:o?[]:r.blockers,workspace:s,localExecution:(()=>{let m=aD(t.state,t.localStatus==="available"?t.local:null);return{status:i?t.localStatus:"not-expected",operation:t.localStatus==="available"?t.local?.execution??null:null,...m?{verifierStartup:m}:{}}})(),...n?{childSummary:n.children.reduce((m,h)=>({...m,[h.status]:(m[h.status]??0)+1}),{total:n.children.length}),readyChildren:n.readyChildren}:{},...f?{supervisor:f}:{},...a.status==="repairable-legacy-overlay"||a.status==="incompatible"?{supervisorOverlay:{status:a.status,message:a.message,repairCommand:a.status==="repairable-legacy-overlay"?`comet native doctor ${e.name} --repair`:null}}:{},continuation:l,...e.details?{details:{stateVersion:t.state.state_version,...o?{supervisorStateVersion:p.supervisorStateVersion}:{},items:p.items,nextCursor:p.nextCursor,nextPageArgs:p.nextCursor?["comet","native","status",t.state.name,"--details","--cursor",p.nextCursor,"--json","--project-root",e.paths.projectRoot]:null}}:{}}}import{accessSync as O3,constants as H3,promises as kh}from"node:fs";import zn from"node:path";ae();Bi();ot();ol();Bi();var Lk="comet.native.workspace-finish.v1",Mk="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",Vk=new RegExp(`^${Mk}$`,"u"),uD=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,Vo=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function qk(e,t){if(!e.trim()||e.includes("\0"))throw new Error(`${t} must contain non-whitespace text and no NUL character`)}function dD(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace finish journal is invalid");let t=e;if(t.schema!==Lk||typeof t.name!="string"||!Vk.test(t.name)||typeof t.transactionId!="string"||!uD.test(t.transactionId)||t.archiveDir!==null&&(typeof t.archiveDir!="string"||!zn.isAbsolute(t.archiveDir))||!["pending","blocked"].includes(String(t.status))||typeof t.updatedAt!="string"||!Number.isFinite(Date.parse(t.updatedAt)))throw new Error("Native workspace finish journal is invalid");if(t.result!==null){if(!t.result||typeof t.result!="object"||Array.isArray(t.result))throw new Error("Native workspace finish journal result is invalid");let r=t.result;if(!["merge","push","pull-request","keep"].includes(String(r.action))||!["completed","kept","blocked"].includes(String(r.status))||!Array.isArray(r.blockedPaths)||r.blockedPaths.some(i=>typeof i!="string")||r.recoveryArgs!==null&&(!Array.isArray(r.recoveryArgs)||r.recoveryArgs.some(i=>typeof i!="string")))throw new Error("Native workspace finish journal result is invalid")}if(t.plan!==void 0){let r=t.plan;if(!r||typeof r!="object"||!["keep","merge","push","pull-request"].includes(r.finish)||!["current","branch","worktree"].includes(r.isolation)||![r.changeRoot,r.primaryRoot].every(i=>typeof i=="string"&&zn.isAbsolute(i))||![r.changeBranch,r.targetBranch].every(i=>typeof i=="string"&&i.length>0)||r.targetRoot!==null&&(typeof r.targetRoot!="string"||!zn.isAbsolute(r.targetRoot))||r.remote!==null&&typeof r.remote!="string"||typeof r.commitMessage!="string"||r.mergeMessage!==null&&typeof r.mergeMessage!="string")throw new Error("Native workspace finish journal plan is invalid");qk(r.commitMessage,"commit-message"),r.mergeMessage!==null&&qk(r.mergeMessage,"merge-message")}if(t.createdAt!==void 0&&(typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))))throw new Error("Native workspace finish journal creation identity is invalid");if(t.commit!==void 0){let r=t.commit;if(!r||!Vo.test(r.parent)||!Array.isArray(r.paths)||!r.paths.every(i=>typeof i=="string"&&i.length>0&&!zn.posix.isAbsolute(i)&&!zn.win32.isAbsolute(i)&&!i.split("/").includes(".."))||!Array.isArray(r.entries)||!r.entries.every(i=>typeof i=="string")||r.sha!==null&&!Vo.test(r.sha))throw new Error("Native workspace finish journal commit is invalid")}if(t.merge!==void 0){let r=t.merge;if(!r||!Vo.test(r.target)||!Vo.test(r.source)||r.sha!==null&&!Vo.test(r.sha))throw new Error("Native workspace finish journal merge is invalid")}return{schema:Lk,name:t.name,transactionId:t.transactionId,archiveDir:t.archiveDir,status:t.status,result:t.result,updatedAt:t.updatedAt,...t.createdAt===void 0?{}:{createdAt:t.createdAt},...t.plan===void 0?{}:{plan:t.plan},...t.commit===void 0?{}:{commit:t.commit},...t.merge===void 0?{}:{merge:t.merge}}}function pD(e,t){if(!Vk.test(t))throw new Error(`Invalid Native workspace finish journal name: ${t}`);return zn.join(e.transactionsDir,`workspace-finish-${t}.json`)}async function Sh(e,t,r={}){let i=pD(e,t);try{let n=await kh.lstat(i);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native workspace finish journal is not a regular file");let a=dD(JSON.parse(await kh.readFile(i,"utf8")));if(a.name!==t)throw new Error("Native workspace finish journal name is invalid");return a}catch(n){if(n.code==="ENOENT")return null;if(r.onError)return r.onError(t,n instanceof Error?n.message:String(n)),null;throw n}}async function Wk(e,t={}){let r;try{r=await kh.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r){if(!n.isFile()&&!n.isSymbolicLink()||n.isDirectory())continue;let a=new RegExp(`^workspace-finish-(${Mk})\\.json$`,"u").exec(n.name);if(!a)continue;let o=await Sh(e,a[1],t);o&&i.push(o)}return i}var hD=/^native-workspaces-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function Ol(e,t){let r=vr.normalize(Eh(e)),i=vr.normalize(Eh(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function Eh(e){let t=vr.resolve(e);try{return fD.native(t)}catch{return t}}function mD(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function zk(e,t){let r=[];for(let i of await bk(e))t!==void 0&&i!==t||r.push({name:i,kind:await Gc(e,i)?"portable":"legacy"});return r}async function Kk(e,t){let r=vr.resolve(e),i=Uo(e),n=i.map(({root:c})=>c),a=n.length>0?n:[r];a.some(c=>Ol(c,r))||a.push(r);let o=[],s=new Set;for(let c of a.map(l=>vr.resolve(l)).sort()){let l=Ol(c,r)?r:c,u=Eh(l),d=process.platform==="win32"?u.toLowerCase():u;if(s.has(d))continue;s.add(d);let p=await Te(l);if(!p)continue;let f=await tr(l,p.native.artifact_root);o.push({projectRoot:l,config:p,paths:f,gitContext:Yn(l,i)??ve(l),changes:await zk(f,t)})}if(o.length===0){let c=await Te(e);if(!c)throw new Error(".comet/config.yaml was not found in any registered worktree");let l=await tr(e,c.native.artifact_root);o.push({projectRoot:vr.resolve(e),config:c,paths:l,gitContext:Yn(e,i)??ve(e),changes:await zk(l,t)})}for(let c of o){c.archiveErrors=[],c.finishJournalErrors=[],c.archives=await Sk(c.paths,(u,d)=>c.archiveErrors.push({name:u,message:d}),t),t!==void 0&&(c.archives=c.archives.filter(({state:u})=>u.name===t),c.archiveErrors=c.archiveErrors.filter(({name:u})=>u===t));let l=(u,d)=>c.finishJournalErrors.push({name:u,message:d});c.finishJournals=t?[await Sh(c.paths,t,{onError:l})].filter(u=>u!==null):await Wk(c.paths,{onError:l})}return o}function Gk(e,t){return e.workspace.bindingState==="aligned"?0:Ol(e.source.projectRoot,t)?1:e.workspace.bindingState==="legacy"?2:e.workspace.bindingState==="missing"?3:e.workspace.bindingState==="drifted"?4:5}async function Yk(e,t){let r=new Map;for(let n of t){for(let a of n.changes)r.set(a.name,[...r.get(a.name)??[],{source:n,kind:a.kind}]);for(let a of n.archives??[])r.has(a.state.name)||r.set(a.state.name,[]);for(let a of n.archiveErrors??[])r.has(a.name)||r.set(a.name,[]);for(let a of n.finishJournals??[])r.has(a.name)||r.set(a.name,[]);for(let a of n.finishJournalErrors??[])r.has(a.name)||r.set(a.name,[])}let i=[];for(let[n,a]of[...r.entries()].sort(([o],[s])=>o.localeCompare(s))){let o=await Promise.all(a.map(async({source:d,kind:p})=>{let f=d.finishJournalErrors?.find(({name:m})=>m===n);if(p==="portable")try{let m=await St(d.paths,n);return{source:d,name:n,kind:p,workspace:jl(d.paths,m,d.gitContext),portableStatus:null,inspectionError:f?.message??null,finishJournal:d.finishJournals?.find(({name:h})=>h===n)??null}}catch(m){return{source:d,name:n,kind:p,workspace:{projectRoot:d.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:"The portable state could not be inspected."},portableStatus:null,inspectionError:m instanceof Error?m.message:String(m)}}return{source:d,name:n,kind:p,workspace:a.length>1?await ro(d.paths,n):{projectRoot:d.projectRoot,currentBranch:d.gitContext.currentBranch,isSecondaryWorktree:d.gitContext.isSecondaryWorktree,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:null,finish:null},portableStatus:null,inspectionError:f?.message??null}})),s=t.flatMap(d=>(d.archives??[]).filter(({state:p})=>p.name===n).map(p=>{let f=bh({paths:d.paths,...p,finishJournal:d.finishJournals?.find(({name:m})=>m===n)??null});return{source:d,name:n,kind:"portable",workspace:f.workspace,portableStatus:f,inspectionError:d.finishJournalErrors?.find(({name:m})=>m===n)?.message??null,record:p,finishJournal:d.finishJournals?.find(({name:m})=>m===n)??null}})),c=t.flatMap(d=>(d.archiveErrors??[]).filter(p=>p.name===n).map(p=>({source:d,error:p})))[0];if(c){i.push({source:c.source,name:n,kind:"portable",portableStatus:null,inspectionError:c.error.message,workspace:{projectRoot:c.source.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:c.error.message}});continue}let l=t.flatMap(d=>(d.finishJournalErrors??[]).filter(p=>p.name===n).map(p=>({source:d,error:p})))[0];if(l&&o.length===0&&s.length===0){i.push({source:l.source,name:n,kind:"portable",portableStatus:null,inspectionError:l.error.message,workspace:{projectRoot:l.source.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:l.error.message}});continue}if(o.length===0&&s.length===0){let d=t.find(f=>f.finishJournals?.some(({name:m})=>m===n)),p=d?.finishJournals?.find(({name:f})=>f===n);if(d&&p){i.push({source:d,name:n,kind:"portable",portableStatus:null,inspectionError:p.result?.message??"Native workspace finish journal has no matching active or archived change record.",workspace:{projectRoot:d.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:p.result?.message??"Native workspace finish record is orphaned."},finishJournal:p});continue}}if(s.length>0){for(let p of o)if(p.kind==="portable")try{p.record=await _l(p.source.paths,vr.join(p.source.paths.changesDir,n,"comet-state.yaml"))}catch{}let d=s.find(p=>[...o,...s.filter(f=>!xk(p.record,f.record))].every(f=>f.record&&Ek(p.record,f.record)));if(d){i.push(d);continue}i.push({...s[0],inspectionError:`Native change ${n} has conflicting active/archive records; identity and committed Git ancestry do not prove supersession. Resolve the records explicitly.`});continue}o.sort((d,p)=>Gk(d,e)-Gk(p,e)||d.source.projectRoot.localeCompare(p.source.projectRoot));let u=o.filter(d=>d.workspace.bindingState==="aligned");u.length>1?i.push(...u):u.length===0&&o.length>1?i.push({...o[0],inspectionError:`Native change ${n} has conflicting workspace records and no aligned binding`}):i.push(u[0]??o[0])}if(i.length>mr.maxChanges)throw new Error(`Native status discovery exceeds ${mr.maxChanges} visible changes`);return i.sort((n,a)=>`${n.name}\0${n.source.projectRoot}`.localeCompare(`${a.name}\0${a.source.projectRoot}`))}function Jk(e,t){let r=t.toString(36),i=T("comet.native.workspace-status-cursor.v1",{candidatesHash:e,offset:t});return`native-workspaces-v1.${e}.${r}.${i}`}function vD(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=hD.exec(e.cursor);if(!t||t[1]!==e.candidatesHash)throw new Error("Native workspace status cursor is invalid or stale");let r=Number.parseInt(t[2],36);if(!Number.isSafeInteger(r)||r<=0||r>=e.total||r.toString(36)!==t[2])throw new Error("Native workspace status cursor offset is invalid");let i=T("comet.native.workspace-status-cursor.v1",{candidatesHash:e.candidatesHash,offset:r});if(t[3]!==i)throw new Error("Native workspace status cursor integrity failed");return r}function Uk(e,t){let r=t?["comet","native","status","--cursor",t,"--project-root",e,"--json"]:null;return{nextPageCommand:r?mD(r):null,nextPageArgs:r}}async function gD(e,t,r){let i=await ro(e.source.paths,e.name),n=null;try{n=await _y(e.source.paths,e.name)}catch{}return n?.state?{schema:"comet.native.status.v2",name:e.name,phase:n.state.phase,status:"blocked",migrationRequired:!0,legacySchema:n.schema,workspace:i,continuation:{schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:n.state.phase,status:"blocked",disposition:"blocked",action:"none",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],message:"This change uses a legacy schema; the first mutating command performs the deterministic migration. Run the listed next command with a migration summary.",runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0}}}:gh(e.source.paths,e.name,{details:t,...r?{acceptanceCursor:r}:{},clarificationMode:e.source.config.native.clarification_mode,maxVerifyFailures:e.source.config.native.max_verify_failures})}async function xh(e,t,r,i){if(e.inspectionError)return{schema:"comet.native.status.v2",name:e.name,phase:"invalid",status:"blocked",inspectionError:e.inspectionError,workspace:e.workspace,continuation:{schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:"invalid",status:"blocked",disposition:"blocked",action:"none",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],message:`Run the repair command in the workspace holding this change: ${e.source.paths.projectRoot}`,runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0}}};if(e.kind==="portable"){if(r)throw new Error("Portable Native status includes the complete acceptance list");if(!t&&e.portableStatus)return e.portableStatus;if(e.record?.state.archived)return bh({paths:e.source.paths,...e.record,finishJournal:e.finishJournal??null,details:t,cursor:i});try{return await Fk({paths:e.source.paths,name:e.name,details:t,gitContext:e.source.gitContext,...i?{cursor:i}:{}})}catch(n){if(i)throw n;return xh({...e,inspectionError:n instanceof Error?n.message:String(n)},!1)}}return gD(e,t,r)}async function Xk(e){let{sources:t,candidates:r}=await wD(e.projectRoot,e.name);if(r.length===0){let i=t.find(n=>Ol(n.projectRoot,e.projectRoot))??t[0];return e.onSelectedRoot?.(i.projectRoot),gh(i.paths,e.name,{details:e.details,...e.acceptanceCursor?{acceptanceCursor:e.acceptanceCursor}:{},clarificationMode:i.config.native.clarification_mode,maxVerifyFailures:i.config.native.max_verify_failures})}return e.onSelectedRoot?.(r[0].source.projectRoot),xh(r[0],e.details??!1,e.acceptanceCursor,e.detailsCursor)}async function wD(e,t){let r=await Kk(e,t),i=(await Yk(e,r)).filter(n=>n.name===t);if(i.length>1)throw new Error(`Native change ${t} has multiple aligned workspace bindings: ${i.map(n=>n.source.projectRoot).join(", ")}`);return{sources:r,candidates:i}}async function Qk(e){let t=await Kk(e.projectRoot),r=await Yk(e.projectRoot,t),i=T("comet.native.workspace-status-candidates.v1",r.map(u=>({name:u.name,projectRoot:u.source.projectRoot,bindingState:u.workspace.bindingState,kind:u.kind}))),n=vD({candidatesHash:i,total:r.length,cursor:e.cursor}),a=await Promise.all(r.slice(n,n+mr.maxItems).map(u=>xh(u,!1))),o=[],s=r.some(({kind:u})=>u==="portable")?"comet.native.status-page.v2":"comet.native.status-page.v1";for(let u of a){let d=[...o,u],p=n+d.length,f=p<r.length?Jk(i,p):null,m={schema:s,total:r.length,offset:n,items:d,nextCursor:f,...Uk(vr.resolve(e.projectRoot),f),limits:{...mr}};if(Buffer.byteLength(JSON.stringify(m),"utf8")>mr.maxSerializedBytes){if(o.length===0)throw new Error("Native workspace status item exceeds its page serialization budget");break}o.push(u)}let c=n+o.length,l=c<r.length?Jk(i,c):null;return{schema:s,total:r.length,offset:n,items:o,nextCursor:l,...Uk(vr.resolve(e.projectRoot),l),limits:{...mr}}}$a();import Wo from"path";import{realpathSync as DD}from"fs";function Zk(e,t){let r=u=>u!==null&&typeof u=="object"&&!Array.isArray(u)?u:{},i=r(e),n=r(i.entry),a=r(i.state??n.state??i),o=r(i.preparation??i.workspace??n.workspace),s=r(i.continuation??n.continuation),c=typeof o.projectRoot=="string"&&o.projectRoot!=="."?o.projectRoot:t??null,l=a.stateVersion??a.state_version;return{phase:typeof a.phase=="string"?a.phase:null,status:typeof a.status=="string"?a.status:null,stateVersion:typeof l=="number"?l:null,workspace:{cwd:c},continuation:Object.keys(s).length?{...s,cwd:c}:null}}var gr={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function eS(e){return e?e.command?`${gr.next} ${e.command}`:e.ask_user?`${gr.next} ${e.ask_user}`:null:null}function tS(e,t){let r=[e.summary],i=eS(e.next);return i&&r.push(i),e.user_message&&r.push("",gr.relay,e.user_message),t!==void 0&&r.push("",gr.details,JSON.stringify(t,null,2)),`${r.join(`
250
257
  `)}
251
- `}function zk(e,t,r){let i=[e.summary],n=Vk(e.next);return n&&i.push(n),e.user_message&&i.push("",gr.relay,e.user_message),i.push("",`${gr.detail} ${t}`),r!==void 0&&i.push("",gr.details,JSON.stringify(r,null,2)),i.join(`
252
- `)}Lt();wt();ae();jt();U();wt();yc();ae();pi();ti();var x5=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});Lt();Da();Se();U();wt();yc();var jl=class extends Error{constructor(r,i,n,a){super(`Canonical spec conflict for ${r}: expected ${i??"(missing)"}, actual ${n??"(missing)"}`);this.capability=r;this.expectedHash=i;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},$l=class extends Error{constructor(r,i=r.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${r.findingCodes.join(", ")}`){super(i);this.preflight=r;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};U();Je();function L(e,t,r){return e==="zh-CN"?r:t}var kh={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function Gk(e,t){return typeof e=="string"&&kh[e]?L(t,kh[e].en,kh[e].zh):typeof e=="string"?e:""}function Sh(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 lD(e){let t={total:e.length,passed:0,failed:0,blocked:0,pending:0};for(let r of e){if(!r||typeof r!="object")return null;let i=r.result;if(i!=="passed"&&i!=="failed"&&i!=="blocked"&&i!=="pending")return null;t[i]+=1}return t}function Jk(e,t){let r=[];e.failed>0&&r.push(L(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(L(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(L(t,`${e.pending} pending`,`${e.pending} 项待验`));let i=L(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function Uk(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.change!="string"||t.disposition!=="continue"&&t.disposition!=="await-user"&&t.disposition!=="blocked"&&t.disposition!=="done"||t.commandArgs!==null&&t.commandArgs!==void 0&&!Array.isArray(t.commandArgs))return!1;let r=t.userCommunication;return!!(r&&typeof r=="object"&&typeof r.required=="boolean"&&(r.message===null||typeof r.message=="string")&&typeof r.agentInstruction=="string")}function Eh(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function uD(e,t,r){return e==="done"?L(r,"complete","已完成"):e==="await-user"?L(r,"waiting for a user decision","等待用户决定"):e==="blocked"?L(r,"paused: needs attention","已暂停,需要处理"):t?L(r,"waiting for a user decision","等待用户决定"):L(r,"ready to continue","可继续推进")}function dD(e,t,r){let i=Eh(e),n=[];r&&n.push(r);let a=L(i,`Change ${e.change}`,`需求 ${e.change}`),o=Gk(e.phase,i),s=uD(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(Jk(t,i));let c=e.userCommunication,l=Kk(e,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function Kk(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:L(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:L(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(e.disposition==="blocked")return{ask_user:r.required&&r.message?r.agentInstruction:L(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function pD(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function fD(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=Gk(e.phase,t),n=e.status==="await-user"?L(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?L(t,"paused","已暂停"):e.status==="done"?L(t,"complete","已完成"):L(t,"in progress","进行中"),a=Sh(e.acceptance)?`${L(t,", ",",")}${Jk(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function hD(e){for(let t of e){let r=t.continuation;if(r?.userCommunication&&typeof r.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(r.userCommunication.agentInstruction))return"zh-CN"}return"en"}function mD(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 vD(e){if(e.healthy){let i=e.repaired?L("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):L("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=gD(e.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:L("en",r>0?`Diagnostics found ${r} problem${r===1?"":"s"} that need attention before this change can continue.`:"Diagnostics found problems that need attention before this change can continue.",r>0?`诊断发现 ${r} 个需要处理的问题,处理后该需求才能继续。`:"诊断发现需要处理的问题,处理后该需求才能继续。"),next:{ask_user:L("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function gD(e){return Uk(e)?Kk(e,Eh(e)):void 0}function Yk(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(mD(t))return vD(t);if(pD(t)){let i=hD(t.items);return{summary:[t.total===t.items.length?L(i,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):L(i,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>fD(a,i))].join(`
253
- `)}}let r=t.continuation;if(Uk(r)){let i=Eh(r),n=dD(r,wD(t),ND(t,i));return yD(t)==="unconfirmed"?{...n,summary:`${n.summary}${L(i,"; the dispatched Verifier has not confirmed startup yet — verify the subagent actually launched before waiting on it",";已派发的 Verifier 尚未确认启动——先核实子代理确实启动,再继续等待")}`}:n}if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let i=t.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in t;return{summary:L(i,n?`Comet Native artifacts live under ${t.artifactRoot} (state root: ${t.nativeRoot}).`:`Initialized Comet Native at ${t.nativeRoot} (artifacts: ${t.artifactRoot}).`,n?`Comet Native 产物位于 ${t.artifactRoot}(状态根目录:${t.nativeRoot})。`:`Comet Native 已初始化于 ${t.nativeRoot}(产物目录:${t.artifactRoot})。`)}}}function wD(e){if(Sh(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(Sh(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return lD(r.acceptance)}return null}function yD(e){let t=e.localExecution;if(!t||typeof t!="object"||Array.isArray(t))return;let r=t.verifierStartup;if(!(!r||typeof r!="object"||Array.isArray(r)))return r.confirmation}function ND(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return L(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?L(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function Xk(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"document-invalid":return{summary:e.message,...typeof r.change=="string"?{next:{command:`comet native next ${r.change} --summary <summary>`}}:{}};case"conflict":return{summary:L("en","This change was updated elsewhere while the command ran, so the command stopped without changing anything. Nothing was lost — reload the latest state and continue from there.","这条需求刚被另一个会话更新,本次命令未做任何改动。没有工作丢失——重新读取最新状态后继续即可。"),...typeof r.change=="string"?{next:{command:`comet native status ${r.change} --json`}}:{}};case"baseline-incomplete":return{summary:L("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:L("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:L("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:L("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:L("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:L("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:L("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:L("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}uc();dc();var Qk=["--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."],xh=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",agentQuickStart:["Run `comet native status --json` to discover active changes.","Select an existing change with `select`, or create one with `new`.","In `agent.workspace.cwd`, execute the exact `agent.continuation.commandArgs` returned by Runtime.","Use `agent.continuation.inputOptions` templates for JSON input; do not reconstruct fields from memory."],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 disassociate Revoke a capability association through Runtime.","spec remove Record a complete capability removal intent.","spec sync <change-name> <capability> --input <json-file> Audit local Markdown reference corrections.","show <change-name> Read formal artifacts and portable state.","status [<change-name>] Discover stable boundaries and Runner actions.","select <change-name> Select a change in its bound workspace.","next <change-name> Confirm or recover a stable workflow boundary.","archive <change-name> Preview and execute Archive plus workspace finish.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state."],options:Qk,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] [--task <text>] [--capability <id>] [--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.","--task <text> Search Project Knowledge for an existing capability and save a revocable association draft.","--capability <id> Directly validate and associate an existing capability without retrieval.","--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, canonical artifact paths, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN",'comet native new add-sms-login --task "add SMS login to authentication"',"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 disassociate <change-name> --expected-state-version <n> --expected-action disassociate-capability
258
+ `}function rS(e,t,r){let i=[e.summary],n=eS(e.next);return n&&i.push(n),e.user_message&&i.push("",gr.relay,e.user_message),i.push("",`${gr.detail} ${t}`),r!==void 0&&i.push("",gr.details,JSON.stringify(r,null,2)),i.join(`
259
+ `)}Lt();wt();ae();jt();U();wt();bc();ae();fi();ti();var B5=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});Lt();Ba();Se();U();wt();bc();var Hl=class extends Error{constructor(r,i,n,a){super(`Canonical spec conflict for ${r}: expected ${i??"(missing)"}, actual ${n??"(missing)"}`);this.capability=r;this.expectedHash=i;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},Dl=class extends Error{constructor(r,i=r.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${r.findingCodes.join(", ")}`){super(i);this.preflight=r;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};U();Je();function L(e,t,r){return e==="zh-CN"?r:t}var Ch={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function iS(e,t){return typeof e=="string"&&Ch[e]?L(t,Ch[e].en,Ch[e].zh):typeof e=="string"?e:""}function Rh(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 kD(e){let t={total:e.length,passed:0,failed:0,blocked:0,pending:0};for(let r of e){if(!r||typeof r!="object")return null;let i=r.result;if(i!=="passed"&&i!=="failed"&&i!=="blocked"&&i!=="pending")return null;t[i]+=1}return t}function nS(e,t){let r=[];e.failed>0&&r.push(L(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(L(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(L(t,`${e.pending} pending`,`${e.pending} 项待验`));let i=L(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function aS(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.change!="string"||t.disposition!=="continue"&&t.disposition!=="await-user"&&t.disposition!=="blocked"&&t.disposition!=="done"||t.commandArgs!==null&&t.commandArgs!==void 0&&!Array.isArray(t.commandArgs))return!1;let r=t.userCommunication;return!!(r&&typeof r=="object"&&typeof r.required=="boolean"&&(r.message===null||typeof r.message=="string")&&typeof r.agentInstruction=="string")}function Ph(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function SD(e,t,r){return e==="done"?L(r,"complete","已完成"):e==="await-user"?L(r,"waiting for a user decision","等待用户决定"):e==="blocked"?L(r,"paused: needs attention","已暂停,需要处理"):t?L(r,"waiting for a user decision","等待用户决定"):L(r,"ready to continue","可继续推进")}function ED(e,t,r){let i=Ph(e),n=[];r&&n.push(r);let a=L(i,`Change ${e.change}`,`需求 ${e.change}`),o=iS(e.phase,i),s=SD(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(nS(t,i));let c=e.userCommunication,l=oS(e,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function oS(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:L(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:L(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(e.disposition==="blocked")return{ask_user:r.required&&r.message?r.agentInstruction:L(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function xD(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function CD(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=iS(e.phase,t),n=e.status==="await-user"?L(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?L(t,"paused","已暂停"):e.status==="done"?L(t,"complete","已完成"):L(t,"in progress","进行中"),a=Rh(e.acceptance)?`${L(t,", ",",")}${nS(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function RD(e){for(let t of e){let r=t.continuation;if(r?.userCommunication&&typeof r.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(r.userCommunication.agentInstruction))return"zh-CN"}return"en"}function PD(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 _D(e){if(e.healthy){let i=e.repaired?L("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):L("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=AD(e.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:L("en",r>0?`Diagnostics found ${r} problem${r===1?"":"s"} that need attention before this change can continue.`:"Diagnostics found problems that need attention before this change can continue.",r>0?`诊断发现 ${r} 个需要处理的问题,处理后该需求才能继续。`:"诊断发现需要处理的问题,处理后该需求才能继续。"),next:{ask_user:L("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function AD(e){return aS(e)?oS(e,Ph(e)):void 0}function sS(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(PD(t))return _D(t);if(xD(t)){let i=RD(t.items);return{summary:[t.total===t.items.length?L(i,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):L(i,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>CD(a,i))].join(`
260
+ `)}}let r=t.continuation;if(aS(r)){let i=Ph(r),n=ED(r,ID(t),jD(t,i));return TD(t)==="unconfirmed"?{...n,summary:`${n.summary}${L(i,"; the dispatched Verifier has not confirmed startup yet — verify the subagent actually launched before waiting on it",";已派发的 Verifier 尚未确认启动——先核实子代理确实启动,再继续等待")}`}:n}if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let i=t.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in t;return{summary:L(i,n?`Comet Native artifacts live under ${t.artifactRoot} (state root: ${t.nativeRoot}).`:`Initialized Comet Native at ${t.nativeRoot} (artifacts: ${t.artifactRoot}).`,n?`Comet Native 产物位于 ${t.artifactRoot}(状态根目录:${t.nativeRoot})。`:`Comet Native 已初始化于 ${t.nativeRoot}(产物目录:${t.artifactRoot})。`)}}}function ID(e){if(Rh(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(Rh(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return kD(r.acceptance)}return null}function TD(e){let t=e.localExecution;if(!t||typeof t!="object"||Array.isArray(t))return;let r=t.verifierStartup;if(!(!r||typeof r!="object"||Array.isArray(r)))return r.confirmation}function jD(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return L(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?L(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function cS(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"document-invalid":return{summary:e.message,...typeof r.change=="string"?{next:{command:`comet native next ${r.change} --summary <summary>`}}:{}};case"conflict":return{summary:L("en","This change was updated elsewhere while the command ran, so the command stopped without changing anything. Nothing was lost — reload the latest state and continue from there.","这条需求刚被另一个会话更新,本次命令未做任何改动。没有工作丢失——重新读取最新状态后继续即可。"),...typeof r.change=="string"?{next:{command:`comet native status ${r.change} --json`}}:{}};case"baseline-incomplete":return{summary:L("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:L("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:L("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:L("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:L("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:L("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:L("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:L("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}pc();fc();var lS=["--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."],_h=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",agentQuickStart:["Run `comet native status --json` to discover active changes.","Select an existing change with `select`, or create one with `new`.","In `agent.workspace.cwd`, execute the exact `agent.continuation.commandArgs` returned by Runtime.","Use `agent.continuation.inputOptions` templates for JSON input; do not reconstruct fields from memory."],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 disassociate Revoke a capability association through Runtime.","spec remove Record a complete capability removal intent.","spec sync <change-name> <capability> --input <json-file> Audit local Markdown reference corrections.","show <change-name> Read formal artifacts and portable state.","status [<change-name>] Discover stable boundaries and Runner actions.","select <change-name> Select a change in its bound workspace.","next <change-name> Confirm or recover a stable workflow boundary.","archive <change-name> Preview and execute Archive plus workspace finish.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state."],options:lS,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] [--task <text>] [--capability <id>] [--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.","--task <text> Search Project Knowledge for an existing capability and save a revocable association draft.","--capability <id> Directly validate and associate an existing capability without retrieval.","--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, canonical artifact paths, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN",'comet native new add-sms-login --task "add SMS login to authentication"',"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 disassociate <change-name> --expected-state-version <n> --expected-action disassociate-capability
254
261
  comet native spec remove <change-name> <capability>
255
262
  comet native spec sync <change-name> <capability> --input <json-file>`,purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["disassociate <change-name> Revoke a capability association and return to Shape.","remove <change-name> <capability> Record a capability removal.","sync <change-name> <capability> --input <json-file> Audit local Markdown reference corrections without changing prose or acceptance."],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."},"spec disassociate":{usage:"comet native spec disassociate <change-name> --expected-state-version <n> --expected-action disassociate-capability",purpose:"Revoke a capability association through Runtime without hand-editing artifacts.",options:["--expected-state-version <n> State version returned by the latest status response.","--expected-action <action> Must be disassociate-capability."],output:"The updated portable state and continuation with the next Runner action."},"spec sync":{usage:"comet native spec sync <change-name> <capability> --input <json-file>",purpose:"Sync local Markdown link destinations in an already confirmed target spec; semantic edits require Shape.",options:["--input <json-file> Fields: expectedStateVersion, actor, reason, affectedAcceptanceIds, replacements [{from,to}]. Include all acceptance IDs from the affected spec."],output:"The audited portable state, preserved unaffected acceptance results and Build continuation for re-verification."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"A compact summary and NEXT action by default. Use --json to read canonical artifact paths, the portable state, brief, complete proposed Specs, and continuation; legacy state is reported as migration-required. Fill command-template placeholders before executing NEXT commands."},check:{usage:"comet native check <change-name>",purpose:"Legacy-only verification command; not supported for current portable changes.",output:"For current changes, run comet native status <change-name> --json and follow the continuation to dispatch verification through comet native next."},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 canonical artifact paths and local execution availability. Use --details and --cursor to read fixed-size detail pages; parent changes expose childSummary and readyChildren.",examples:["comet native status --json","comet native status session-timeout --details --json"]},select:{usage:"comet native select <change-name>",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next <change-name> --summary <text> [--coordination-mode multi-session|single-session] [--max-parallel <n>] [--expected-state-version <n>] [--expected-action <action>]
256
263
  comet native next <change-name> --summary <text> [--confirmed|--accept-result|--revise-implementation|--revise-requirements|--retry-verifier|--resolve-verifier-blocker] [--expected-state-version <n>] [--expected-action <action>]
257
264
  comet native next <change-name> --runner-input <json-file> [--validate-only]`,purpose:"Confirm or recover an Agent boundary, advance parent child changes, handle Supervisor task operations, or use one skill-coordinated JSON bridge for Builder handoff, check-plan dispatch, and Verifier response/error.",options:["--summary <text> Required transition or recovery summary.","--confirmed Confirm the persisted Shape boundary with both expected guards, or confirm an explicitly degraded verifier-unavailable fallback before Archive.","--coordination-mode multi-session|single-session Choose how a multi-child Supervisor proceeds. Supply it with --confirmed at the persisted Shape boundary to confirm the full plan and mode together, or select it during preparation and confirm the plan afterward.","--accept-result Accept the current skill-coordinated Verify result and make it archive-ready.","--finish keep|merge|push|pull-request With --accept-result, record the explicitly chosen isolated-workspace finish in the same guarded decision.","--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, retry-checks, verifier-response, verifier-started, verifier-execution-error, or verifier-unavailable. Builder/dispatch identity fields are rejected; verifier responses must echo the current candidateId and verifierExecutionRef from the Verifier dispatch.","--validate-only Validate the Runner JSON shape and current boundary without writing state or starting a process; requires --runner-input."," Choose one object template from an inputOptions exclusiveGroup and save it as UTF-8 JSON (BOM accepted). Field errors return issues with JSON pointer, missingFields and unknownFields. Execute agent.continuation in agent.workspace.cwd; Supervisor results use task.returnAction."," builder-handoff fields: kind, summary, addressed_acceptance_ids, acceptance_review, checks, verification_checks, known_limits, optional review. acceptance_review must cover every confirmed ID exactly once with id, status, evidence (concrete references or observations), and note. Only implemented-with-evidence with nonempty evidence is ready for handoff; implemented-no-evidence, not-implemented, and known-fail remain in Build. This Builder declaration does not replace independent verification. checks summarize development feedback. verification_checks is an optional Runtime plan executed after the candidate is frozen; a passing plan returns the Verifier dispatch immediately. Completed Runtime checks can carry to a new candidate only when the implementation, confirmed documents, plan, workspace, environment, and saved evidence still match. If review is supplied, its fields are status=passed, summary, reviewer_execution_ref from a separate read-only review."," dispatch-verifier fields: kind, checks (an explicitly resolved plan; [] is allowed)."," retry-checks fields: kind, check_ids for repeatable interrupted Runtime checks from the current candidate; each check can be retried at most three times."," verifier-response fields: kind, candidateId, verifierExecutionRef, response (request-checks or final-result); copy the two binding fields from the current continuation."," verifier-started fields: kind, candidateId, verifierExecutionRef copied from verifierDispatch; the dispatched Verifier submits it as its first Runtime action so status can distinguish a registered dispatch from a Verifier that actually started. Repeating it is accepted without side effects."," 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)."," supervisor-checks fields: kind, child, runId, checks (non-empty repeatable Runtime check plans), materials [{name,content}], and optional retry_check_ids for interrupted checks from the same candidate, machine and workspace. Returns per-check execution state plus operationId, status and receiptRef. Repeated running plans return the same handle."," supervisor-verifier-result evidence fields: summary, checks (informal notes), acceptance [{id,result,reason}], receiptRef. verdict is pass, fail or blocked; every task acceptance ID must appear exactly once. Runtime receipts determine formal check status; receiptRef may be null for fail or blocked."," supervisor-integrate checks are non-empty Runtime check plans executed after the merge in the integration worktree, not declared statuses."],output:'A compact portable state summary, explicit skill-coordinated label, Runtime-owned check results, scoped verifierDispatch, bounded request-check response, continuation.runnerAction, machine-readable continuation.inputOptions, and continuation.userCommunication with a user-ready message and Agent relay guidance. Read acceptance text and other long fields from paged status --details output. Human-readable verification statuses include "Host independently verified", "Checks completed, but your confirmation is required", "Full verification was unavailable; only automatic checks completed", and "You accepted the incomplete verification result". This generic bridge is not trusted identity attestation: a passing result waits for explicit user confirmation before Archive.',examples:['comet native next session-timeout --summary "Shape confirmed" --confirmed --expected-state-version <n> --expected-action confirm-shape','comet native next session-timeout --summary "Current result accepted" --accept-result','comet native next session-timeout --summary "Implementation needs revision" --revise-implementation','comet native next session-timeout --summary "Acceptance criteria changed" --revise-requirements','comet native next session-timeout --summary "Retry verifier infrastructure" --retry-verifier','comet native next session-timeout --summary "Retry semantic verification" --resolve-verifier-blocker',"comet native next session-timeout --runner-input <temporary-json-file>"]},archive:{usage:`comet native archive <change-name> --dry-run [--finish merge|push|pull-request|keep] [--commit-message <text>] [--merge-message <text>]
258
- comet native archive <change-name> [--confirmed] [--serial-first <current-change>] [--commit-message <text>] [--merge-message <text>]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Run the complete read-only Archive and workspace-finish readiness check; it persists only an explicit --finish choice.","--finish <action> Persist merge, push, pull-request, or keep for an isolated workspace.","--expected-state-version <n> Preserve this continuation-issued guard when confirming a new finish choice; stale choices are rejected before it is recorded.","--commit-message <text> Set the archive commit message; Unicode and multiline text are supported. Git hooks still run.","--merge-message <text> Set the local merge commit message; requires merge finish. Omit it to use Git defaults.","--serial-first <current-change> During execution only, confirm that this change archives before detected capability peers; the value must equal <change-name>.","--confirmed Confirm Archive when project policy requires it."],output:"Readiness, every blocker, actual prepared commitMessages (mergeMessage is null when no merge is planned), and the exact next continuation, or the completed Archive transaction and workspace finish result. Messages are retained for retries. After a Git hook rejects a message, provide a corrected message with --confirmed for the unfinished step; completed commits are never rewritten. Execute the returned confirmed command only after ready is true; Archive does not repeat verification."},doctor:{usage:"comet native doctor [<change-name>] [--repair]",purpose:"Inspect portable state, migrate a legacy active change, or rebuild its local execution overlay.",options:["--repair Apply deterministic migration or rebuild from the portable stable boundary."],output:"Health, migration or recovery details, and the continuation with the next Runner action."}});function Ol(e,t){return`${e}:
265
+ comet native archive <change-name> [--confirmed] [--serial-first <current-change>] [--commit-message <text>] [--merge-message <text>]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Run the complete read-only Archive and workspace-finish readiness check; it persists only an explicit --finish choice.","--finish <action> Persist merge, push, pull-request, or keep for an isolated workspace.","--expected-state-version <n> Preserve this continuation-issued guard when confirming a new finish choice; stale choices are rejected before it is recorded.","--commit-message <text> Set the archive commit message; Unicode and multiline text are supported. Git hooks still run.","--merge-message <text> Set the local merge commit message; requires merge finish. Omit it to use Git defaults.","--serial-first <current-change> During execution only, confirm that this change archives before detected capability peers; the value must equal <change-name>.","--confirmed Confirm Archive when project policy requires it."],output:"Readiness, every blocker, actual prepared commitMessages (mergeMessage is null when no merge is planned), and the exact next continuation, or the completed Archive transaction and workspace finish result. Messages are retained for retries. After a Git hook rejects a message, provide a corrected message with --confirmed for the unfinished step; completed commits are never rewritten. Execute the returned confirmed command only after ready is true; Archive does not repeat verification."},doctor:{usage:"comet native doctor [<change-name>] [--repair]",purpose:"Inspect portable state, migrate a legacy active change, or rebuild its local execution overlay.",options:["--repair Apply deterministic migration or rebuild from the portable stable boundary."],output:"Health, migration or recovery details, and the continuation with the next Runner action."}});function Bl(e,t){return`${e}:
259
266
  ${t.map(r=>` ${r}`).join(`
260
- `)}`}function bD(e){let t=e.filter(i=>i!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return xh[r]||t.length>1&&xh[t[0]]?.subcommands?r:t[0]}function kD(e=[]){let t=bD(e),r=xh[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.agentQuickStart&&i.push("",Ol("Agent Quick Start",r.agentQuickStart)),r.subcommands&&i.push("",Ol("Commands",r.subcommands));let n=t===""?r.options:[...r.options??[],...Qk];return n&&n.length>0&&i.push("",Ol("Options",n)),i.push("",`Output:
261
- ${r.output}`),r.examples&&i.push("",Ol("Examples",r.examples)),t===""&&i.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${i.join(`
267
+ `)}`}function $D(e){let t=e.filter(i=>i!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return _h[r]||t.length>1&&_h[t[0]]?.subcommands?r:t[0]}function OD(e=[]){let t=$D(e),r=_h[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.agentQuickStart&&i.push("",Bl("Agent Quick Start",r.agentQuickStart)),r.subcommands&&i.push("",Bl("Commands",r.subcommands));let n=t===""?r.options:[...r.options??[],...lS];return n&&n.length>0&&i.push("",Bl("Options",n)),i.push("",`Output:
268
+ ${r.output}`),r.examples&&i.push("",Bl("Examples",r.examples)),t===""&&i.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${i.join(`
262
269
  `)}
263
- `}}var SD=kD().usage;var j8=10*1024*1024,Ut=class extends Error{};function Vo(e,t){let r=e.flatMap((i,n)=>i===t?[n]:[]);if(r.length>1)throw new Ut(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function Hl(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new Ut(`${t} may only be provided once`);if(r.length===0)return;let i=r[0],n=e[i+1];if(n===void 0||n.startsWith("--"))throw new Ut(`${t} requires a value`);return e.splice(i,2),n}function eS(e){if(e.length>0)throw new Ut(`Unexpected argument: ${e[0]}`)}function Ch(e,t){let r=Mo.normalize(Zk(e)),i=Mo.normalize(Zk(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function Zk(e){let t=Mo.resolve(e);try{return ED.native(t)}catch{return t}}function xD(e,t){let r=Mo.resolve(t,e),i=ve(t);if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return r;let n=ve(r);return!n.isGitWorktree||n.currentWorktreeRoot===null||n.primaryWorktreeRoot===null||!Ch(i.primaryWorktreeRoot,n.primaryWorktreeRoot)||Ch(i.currentWorktreeRoot,n.currentWorktreeRoot)?r:Ch(t,i.currentWorktreeRoot)?Mo.resolve(t):i.currentWorktreeRoot}async function tS(e,t=process.cwd()){return e?xD(e,t):Gd(t)}function rS(e,t){return e==="status"||e==="show"||e==="root"&&t[0]==="show"}function iS(e){return JSON.stringify(e,null,2)+`
264
- `}function nS(e,t,r){return{command:e,exitCode:0,data:t,text:r??iS(t)}}function CD(e,t){if(t instanceof io)return{command:e,exitCode:65,data:{change:t.change,findings:t.findings},error:{code:"document-invalid",message:t.message}};if(t instanceof ln)return{command:e,exitCode:65,data:{builderReadiness:{ready:!1,missingIds:t.missingIds,incompleteIds:t.incompleteIds}},error:{code:"invalid-data",message:t.message}};if(t instanceof Wa)return{command:e,exitCode:65,error:{code:"invalid-data",message:t.message,issues:t.issues}};if(t instanceof Ut)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof jl)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 $l)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof Dc)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 ro)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 nl)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Bc)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 ii)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof Bo)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let r=t.code;if(r&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(r))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let i=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:i?73:65,error:{code:i?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function aS(e,t){let r=CD(e,t),i=r.error;if(!i)return r;let n=Xk({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function RD(e,t,r=!1){let i=e.envelope??Yk(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,agent:Mk(e.data,e.executionCwd),...i===void 0?{}:{summary:i.summary,...i.next===void 0?{}:{next:i.next},...i.user_message===void 0?{}:{user_message:i.user_message}},...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
265
- `}:e.error?{exitCode:e.exitCode,stderr:i?zk(i,e.error.message,r?e.data:void 0):e.error.message}:i?{exitCode:e.exitCode,stdout:Wk(i,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==iS(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
270
+ `}}var HD=OD().usage;var G8=10*1024*1024,Ut=class extends Error{};function zo(e,t){let r=e.flatMap((i,n)=>i===t?[n]:[]);if(r.length>1)throw new Ut(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function Fl(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new Ut(`${t} may only be provided once`);if(r.length===0)return;let i=r[0],n=e[i+1];if(n===void 0||n.startsWith("--"))throw new Ut(`${t} requires a value`);return e.splice(i,2),n}function dS(e){if(e.length>0)throw new Ut(`Unexpected argument: ${e[0]}`)}function Ah(e,t){let r=Wo.normalize(uS(e)),i=Wo.normalize(uS(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function uS(e){let t=Wo.resolve(e);try{return DD.native(t)}catch{return t}}function BD(e,t){let r=Wo.resolve(t,e),i=ve(t);if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return r;let n=ve(r);return!n.isGitWorktree||n.currentWorktreeRoot===null||n.primaryWorktreeRoot===null||!Ah(i.primaryWorktreeRoot,n.primaryWorktreeRoot)||Ah(i.currentWorktreeRoot,n.currentWorktreeRoot)?r:Ah(t,i.currentWorktreeRoot)?Wo.resolve(t):i.currentWorktreeRoot}async function pS(e,t=process.cwd()){return e?BD(e,t):Yd(t)}function fS(e,t){return e==="status"||e==="show"||e==="root"&&t[0]==="show"}function hS(e){return JSON.stringify(e,null,2)+`
271
+ `}function mS(e,t,r){return{command:e,exitCode:0,data:t,text:r??hS(t)}}function FD(e,t){if(t instanceof no)return{command:e,exitCode:65,data:{change:t.change,findings:t.findings},error:{code:"document-invalid",message:t.message}};if(t instanceof un)return{command:e,exitCode:65,data:{builderReadiness:{ready:!1,missingIds:t.missingIds,incompleteIds:t.incompleteIds}},error:{code:"invalid-data",message:t.message}};if(t instanceof za)return{command:e,exitCode:65,error:{code:"invalid-data",message:t.message,issues:t.issues}};if(t instanceof Ut)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Hl)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 Dl)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof Fc)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 io)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 sl)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Lc)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 ii)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof Lo)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let r=t.code;if(r&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(r))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let i=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:i?73:65,error:{code:i?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function vS(e,t){let r=FD(e,t),i=r.error;if(!i)return r;let n=cS({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function LD(e,t,r=!1){let i=e.envelope??sS(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,agent:Zk(e.data,e.executionCwd),...i===void 0?{}:{summary:i.summary,...i.next===void 0?{}:{next:i.next},...i.user_message===void 0?{}:{user_message:i.user_message}},...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
272
+ `}:e.error?{exitCode:e.exitCode,stderr:i?rS(i,e.error.message,r?e.data:void 0):e.error.message}:i?{exitCode:e.exitCode,stdout:tS(i,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==hS(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
266
273
  ${gr.details}
267
274
  ${JSON.stringify(e.data,null,2)}
268
- `}:{exitCode:e.exitCode,stdout:e.text}}function PD(e,t,r=!1){let i=RD(e,t,r),n=!1;if(i.stdout?.trim())try{let a=JSON.parse(i.stdout);n=!!a&&typeof a=="object"&&!Array.isArray(a)}catch{n=!1}return{output:i,structuredDataVisible:n}}function oS(e,t,r=!1){return PD(e,t,r).output}async function sS(e,t){let r=Vo(e,"--details"),i=Hl(e,"--cursor"),n=e[0]?.startsWith("--")?void 0:e.shift();if(r&&!n)throw new Ut("status --details requires a change name");if(i&&n&&!r)throw new Ut("--cursor for a named status requires --details");eS(e);let a=t,o=n?await Lk({projectRoot:t,name:n,onSelectedRoot:s=>{a=s},details:r,...i?{detailsCursor:i}:{}}):await qk({projectRoot:t,...i?{cursor:i}:{}});return{...nS("status",o),executionCwd:a}}async function cS(e,t,r=process.argv.slice(2)){let i=r.indexOf("--"),n=i<0?[...r]:r.slice(0,i),a=i<0?[]:r.slice(i),o=n.includes("--json"),s=n.includes("--verbose"),c,l;try{Vo(n,"--json"),Vo(n,"--verbose"),c=Hl(n,"--project-root");let d=[...n,...a],p=async()=>{let f=await tS(c);return{executionCwd:f,...await t(d,f)}};l=rS(e,d)?await jh(p):await p()}catch(d){l=aS(e,d)}let u=oS(l,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
275
+ `}:{exitCode:e.exitCode,stdout:e.text}}function qD(e,t,r=!1){let i=LD(e,t,r),n=!1;if(i.stdout?.trim())try{let a=JSON.parse(i.stdout);n=!!a&&typeof a=="object"&&!Array.isArray(a)}catch{n=!1}return{output:i,structuredDataVisible:n}}function gS(e,t,r=!1){return qD(e,t,r).output}async function wS(e,t){let r=zo(e,"--details"),i=Fl(e,"--cursor"),n=e[0]?.startsWith("--")?void 0:e.shift();if(r&&!n)throw new Ut("status --details requires a change name");if(i&&n&&!r)throw new Ut("--cursor for a named status requires --details");dS(e);let a=t,o=n?await Xk({projectRoot:t,name:n,onSelectedRoot:s=>{a=s},details:r,...i?{detailsCursor:i}:{}}):await Qk({projectRoot:t,...i?{cursor:i}:{}});return{...mS("status",o),executionCwd:a}}async function yS(e,t,r=process.argv.slice(2)){let i=r.indexOf("--"),n=i<0?[...r]:r.slice(0,i),a=i<0?[]:r.slice(i),o=n.includes("--json"),s=n.includes("--verbose"),c,l;try{zo(n,"--json"),zo(n,"--verbose"),c=Fl(n,"--project-root");let d=[...n,...a],p=async()=>{let f=await pS(c);return{executionCwd:f,...await t(d,f)}};l=fS(e,d)?await Dh(p):await p()}catch(d){l=vS(e,d)}let u=gS(l,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
269
276
  `)?"":`
270
- `)),u.exitCode}process.exitCode=await cS("status",sS);
277
+ `)),u.exitCode}process.exitCode=await yS("status",wS);