@rpamis/comet 0.4.0-rc.4 → 0.4.0-rc.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 (196) hide show
  1. package/LICENSE +21 -21
  2. package/assets/manifest.json +1 -1
  3. package/assets/skills/comet/scripts/comet-hook-router.mjs +158 -155
  4. package/assets/skills/comet-native/scripts/comet-native-archive.mjs +59 -59
  5. package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +84 -84
  6. package/assets/skills/comet-native/scripts/comet-native-next.mjs +63 -63
  7. package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +123 -123
  8. package/assets/skills/comet-native/scripts/comet-native-select.mjs +71 -71
  9. package/assets/skills/comet-native/scripts/comet-native-status.mjs +68 -68
  10. package/dist/app/cli/index.js +16 -0
  11. package/dist/app/cli/index.js.map +1 -1
  12. package/dist/app/commands/comet-task.d.ts +3 -0
  13. package/dist/app/commands/comet-task.d.ts.map +1 -1
  14. package/dist/app/commands/comet-task.js +21 -0
  15. package/dist/app/commands/comet-task.js.map +1 -1
  16. package/dist/app/commands/native.js +2 -0
  17. package/dist/app/commands/native.js.map +1 -1
  18. package/dist/app/commands/personal-memory.d.ts.map +1 -1
  19. package/dist/app/commands/personal-memory.js +1 -0
  20. package/dist/app/commands/personal-memory.js.map +1 -1
  21. package/dist/app/commands/project-knowledge.d.ts +3 -0
  22. package/dist/app/commands/project-knowledge.d.ts.map +1 -1
  23. package/dist/app/commands/project-knowledge.js +39 -1
  24. package/dist/app/commands/project-knowledge.js.map +1 -1
  25. package/dist/domains/agent-learning/context-director.d.ts +14 -5
  26. package/dist/domains/agent-learning/context-director.d.ts.map +1 -1
  27. package/dist/domains/agent-learning/context-director.js +106 -26
  28. package/dist/domains/agent-learning/context-director.js.map +1 -1
  29. package/dist/domains/comet-entry/plugin-context.d.ts +2 -1
  30. package/dist/domains/comet-entry/plugin-context.d.ts.map +1 -1
  31. package/dist/domains/comet-entry/plugin-context.js +10 -1
  32. package/dist/domains/comet-entry/plugin-context.js.map +1 -1
  33. package/dist/domains/comet-memory/personal-memory.d.ts.map +1 -1
  34. package/dist/domains/comet-memory/personal-memory.js +86 -34
  35. package/dist/domains/comet-memory/personal-memory.js.map +1 -1
  36. package/dist/domains/comet-memory/plugin.js +3 -1
  37. package/dist/domains/comet-memory/plugin.js.map +1 -1
  38. package/dist/domains/comet-native/native-archive-command.d.ts.map +1 -1
  39. package/dist/domains/comet-native/native-archive-command.js +5 -0
  40. package/dist/domains/comet-native/native-archive-command.js.map +1 -1
  41. package/dist/domains/comet-native/native-experience.d.ts.map +1 -1
  42. package/dist/domains/comet-native/native-experience.js +23 -10
  43. package/dist/domains/comet-native/native-experience.js.map +1 -1
  44. package/dist/domains/comet-native/native-next-command.js +12 -12
  45. package/dist/domains/comet-native/native-next-command.js.map +1 -1
  46. package/dist/domains/comet-native/native-portable-summary.d.ts +7 -1
  47. package/dist/domains/comet-native/native-portable-summary.d.ts.map +1 -1
  48. package/dist/domains/comet-native/native-portable-summary.js +20 -1
  49. package/dist/domains/comet-native/native-portable-summary.js.map +1 -1
  50. package/dist/domains/comet-plugin/integration.d.ts +2 -2
  51. package/dist/domains/comet-plugin/integration.d.ts.map +1 -1
  52. package/dist/domains/comet-plugin/integration.js +22 -4
  53. package/dist/domains/comet-plugin/integration.js.map +1 -1
  54. package/dist/domains/dashboard/web/assets/{abnfDiagram-VCTEODGH-Bql0JkFh.js → abnfDiagram-VCTEODGH-DktP_xx6.js} +1 -1
  55. package/dist/domains/dashboard/web/assets/{arc-CCUY9L8x.js → arc-Bn1VKVxB.js} +1 -1
  56. package/dist/domains/dashboard/web/assets/architecture-7GRP2DOG-Doz1cLoT.js +1 -0
  57. package/dist/domains/dashboard/web/assets/{architectureDiagram-5GKGNRK7-iYP_D3CC.js → architectureDiagram-5GKGNRK7-B968UcrU.js} +1 -1
  58. package/dist/domains/dashboard/web/assets/{blockDiagram-I7D4REHJ-DyW07-ad.js → blockDiagram-I7D4REHJ-Ben_8wAV.js} +1 -1
  59. package/dist/domains/dashboard/web/assets/{c4Diagram-7LVT6UL2-DDD_Y9Gj.js → c4Diagram-7LVT6UL2-Dob7HfzV.js} +1 -1
  60. package/dist/domains/dashboard/web/assets/channel-CVf4X4BV.js +1 -0
  61. package/dist/domains/dashboard/web/assets/{chunk-4HAMMTFA-cZryt4d4.js → chunk-4HAMMTFA-WLtkq7Gw.js} +1 -1
  62. package/dist/domains/dashboard/web/assets/{chunk-75Z2AOVW-Ciqzt_fM.js → chunk-75Z2AOVW-DPRWDP1s.js} +1 -1
  63. package/dist/domains/dashboard/web/assets/{chunk-DU6HZSFF-0EtIdyLT.js → chunk-DU6HZSFF-B4Z8Mce9.js} +1 -1
  64. package/dist/domains/dashboard/web/assets/{chunk-F27PBJKO-B09yMHfO.js → chunk-F27PBJKO-D5FH4UPb.js} +1 -1
  65. package/dist/domains/dashboard/web/assets/{chunk-GMAD6QVW-D_hJqXpD.js → chunk-GMAD6QVW-D0gALUpa.js} +1 -1
  66. package/dist/domains/dashboard/web/assets/{chunk-GVQU2GXP-DIvLb3as.js → chunk-GVQU2GXP-Cz71fWUR.js} +1 -1
  67. package/dist/domains/dashboard/web/assets/{chunk-IMKFNOWR-B_oII0H5.js → chunk-IMKFNOWR-Bqryqw0r.js} +1 -1
  68. package/dist/domains/dashboard/web/assets/{chunk-L3NEJ4N5-BALKwnUb.js → chunk-L3NEJ4N5-CJKqYHaP.js} +1 -1
  69. package/dist/domains/dashboard/web/assets/{chunk-OSK3NFVY-zA0G74ff.js → chunk-OSK3NFVY-C-anVJYL.js} +1 -1
  70. package/dist/domains/dashboard/web/assets/{chunk-P2QGCYS3-B9FFBdWw.js → chunk-P2QGCYS3-D-IhFZGl.js} +1 -1
  71. package/dist/domains/dashboard/web/assets/{chunk-POPQ4Y6H-Fwh05sRj.js → chunk-POPQ4Y6H-DHZ2x8cS.js} +1 -1
  72. package/dist/domains/dashboard/web/assets/{chunk-PWAF6VOD-cCaczJjE.js → chunk-PWAF6VOD-DfS3bSOb.js} +1 -1
  73. package/dist/domains/dashboard/web/assets/{chunk-SHT3W25Y-ffjS5Q53.js → chunk-SHT3W25Y-D3iDzF3T.js} +1 -1
  74. package/dist/domains/dashboard/web/assets/{chunk-SVP7TREG-IDmA7lw7.js → chunk-SVP7TREG-BQunJ2lh.js} +1 -1
  75. package/dist/domains/dashboard/web/assets/{chunk-TICWLB2K-8Gmmm4In.js → chunk-TICWLB2K-BaqCQLlB.js} +1 -1
  76. package/dist/domains/dashboard/web/assets/{chunk-XXDRQBXY-DS9V6N2-.js → chunk-XXDRQBXY-mmlWRTLt.js} +1 -1
  77. package/dist/domains/dashboard/web/assets/classDiagram-ZZMXUADV-DXerFgpQ.js +1 -0
  78. package/dist/domains/dashboard/web/assets/classDiagram-v2-VYDZK3BY-DXerFgpQ.js +1 -0
  79. package/dist/domains/dashboard/web/assets/{cose-bilkent-JH36ORCC-DTBreOtW.js → cose-bilkent-JH36ORCC-D3cS4IXf.js} +1 -1
  80. package/dist/domains/dashboard/web/assets/{cynefin-OW5HDTMX-DQuEyCa9.js → cynefin-OW5HDTMX-DE1IHUyY.js} +1 -1
  81. package/dist/domains/dashboard/web/assets/{cynefinDiagram-5FMLGOSQ-Bb0YxnR5.js → cynefinDiagram-5FMLGOSQ-DzqK0Tbz.js} +1 -1
  82. package/dist/domains/dashboard/web/assets/{dagre-GXQ25YYZ-DCdqnZ1z.js → dagre-GXQ25YYZ-AI4ZWaO2.js} +1 -1
  83. package/dist/domains/dashboard/web/assets/{demo-DrJ2uuUL.js → demo-COS52Sbp.js} +8 -8
  84. package/dist/domains/dashboard/web/assets/{diagram-S7CK7UJ4-CBO5Oebq.js → diagram-S7CK7UJ4-g0XXZtEw.js} +1 -1
  85. package/dist/domains/dashboard/web/assets/{diagram-UQ7AKVKN-Do5KGiae.js → diagram-UQ7AKVKN-Cms0TctP.js} +1 -1
  86. package/dist/domains/dashboard/web/assets/{diagram-VSXAHHWV-4Xskky28.js → diagram-VSXAHHWV-1FH11lSW.js} +1 -1
  87. package/dist/domains/dashboard/web/assets/{diagram-VX7I27RA-DHaxCMg1.js → diagram-VX7I27RA-6k2xns6T.js} +1 -1
  88. package/dist/domains/dashboard/web/assets/{diagram-Z3DM3KII-_b0C8RCs.js → diagram-Z3DM3KII-7VmVYxMS.js} +1 -1
  89. package/dist/domains/dashboard/web/assets/{dist-D_v6faRz.js → dist-C3Eu0v0t.js} +1 -1
  90. package/dist/domains/dashboard/web/assets/{ebnfDiagram-PWID7BFC-BlWWQsBx.js → ebnfDiagram-PWID7BFC-CIbiadEp.js} +1 -1
  91. package/dist/domains/dashboard/web/assets/{erDiagram-RLTQ6QDP-CaZks0yu.js → erDiagram-RLTQ6QDP-Cge5wrQ7.js} +1 -1
  92. package/dist/domains/dashboard/web/assets/{es-DMM6Y5Bv.js → es-BBSVi8Cm.js} +1 -1
  93. package/dist/domains/dashboard/web/assets/eventmodeling-NTZA5JFV-BNDjhcIe.js +1 -0
  94. package/dist/domains/dashboard/web/assets/flowDiagram-HODETNUW-BfAyylTq.js +1 -0
  95. package/dist/domains/dashboard/web/assets/{ganttDiagram-EL5Y4UJY-BSjOQ_Cg.js → ganttDiagram-EL5Y4UJY-Dr4gcis6.js} +1 -1
  96. package/dist/domains/dashboard/web/assets/{gitGraph-4MIJSDKK-DYwq3-1L.js → gitGraph-4MIJSDKK-DzFO7GXq.js} +1 -1
  97. package/dist/domains/dashboard/web/assets/{gitGraphDiagram-WWUBYQGX-oVngpACZ.js → gitGraphDiagram-WWUBYQGX-jCmQLI23.js} +1 -1
  98. package/dist/domains/dashboard/web/assets/{index-7epoYLF6.js → index-Cu7ImK90.js} +25 -25
  99. package/dist/domains/dashboard/web/assets/index-st3h1lQU.css +1 -0
  100. package/dist/domains/dashboard/web/assets/{info-A6RAGUB7-CLoje88f.js → info-A6RAGUB7-CFW1R5j4.js} +1 -1
  101. package/dist/domains/dashboard/web/assets/{infoDiagram-27XIBGKW-sS6zp9EL.js → infoDiagram-27XIBGKW-DXRLxyIw.js} +1 -1
  102. package/dist/domains/dashboard/web/assets/{ishikawaDiagram-5VMMS53U-kETJqqgb.js → ishikawaDiagram-5VMMS53U-27Bkcq65.js} +1 -1
  103. package/dist/domains/dashboard/web/assets/{journeyDiagram-3NMN7TZE-ByJPB5Tw.js → journeyDiagram-3NMN7TZE-CNTUOJev.js} +1 -1
  104. package/dist/domains/dashboard/web/assets/{kanban-definition-UXKFOSKX-JKqPn1FZ.js → kanban-definition-UXKFOSKX-wxkpxo_z.js} +1 -1
  105. package/dist/domains/dashboard/web/assets/{line-CnHo6lWD.js → line-COcnxdlo.js} +1 -1
  106. package/dist/domains/dashboard/web/assets/{linear-B2pLEjo4.js → linear-BYi1bTXs.js} +1 -1
  107. package/dist/domains/dashboard/web/assets/{mermaid-parser.core-OtNk5rQN.js → mermaid-parser.core-j8j63RgF.js} +3 -3
  108. package/dist/domains/dashboard/web/assets/{mermaid.core-D1ElL3aM.js → mermaid.core-BU_qb_8K.js} +4 -4
  109. package/dist/domains/dashboard/web/assets/{mindmap-definition-YA3MSWOX-BxJqN_qn.js → mindmap-definition-YA3MSWOX-G0BDXvKi.js} +1 -1
  110. package/dist/domains/dashboard/web/assets/{packet-AYTQ26CC-DM9DL0wE.js → packet-AYTQ26CC-JORyJlKy.js} +1 -1
  111. package/dist/domains/dashboard/web/assets/{pegDiagram-XKGWAZYB-BDe-x6aH.js → pegDiagram-XKGWAZYB-hA0fUEjQ.js} +1 -1
  112. package/dist/domains/dashboard/web/assets/{pie-WAS4IAKB-ClmkkApZ.js → pie-WAS4IAKB-gWVXoOeL.js} +1 -1
  113. package/dist/domains/dashboard/web/assets/{pieDiagram-E7YTZNPT-DSFQ6yQn.js → pieDiagram-E7YTZNPT-_NamTf64.js} +1 -1
  114. package/dist/domains/dashboard/web/assets/{quadrantDiagram-AXDQQJYC-CV2lLCpu.js → quadrantDiagram-AXDQQJYC-BUU5A24c.js} +1 -1
  115. package/dist/domains/dashboard/web/assets/{radar-RG4KPBEZ-BduOvwgQ.js → radar-RG4KPBEZ-BHdo5LzP.js} +1 -1
  116. package/dist/domains/dashboard/web/assets/{railroad-74A4TZTK-BYnUo_HE.js → railroad-74A4TZTK-DT_vTugC.js} +1 -1
  117. package/dist/domains/dashboard/web/assets/railroad-abnf-HS5TGJTU-CADAqTZD.js +1 -0
  118. package/dist/domains/dashboard/web/assets/railroad-ebnf-LZEXJU2U-6x_wNdA6.js +1 -0
  119. package/dist/domains/dashboard/web/assets/railroad-peg-WCYAUIDC-D2Az23Om.js +1 -0
  120. package/dist/domains/dashboard/web/assets/{railroadDiagram-O6MQD6OU-Y0OnScVm.js → railroadDiagram-O6MQD6OU-BdOuWAHc.js} +1 -1
  121. package/dist/domains/dashboard/web/assets/{requirementDiagram-BXWQKSXE-Dqs0b-_F.js → requirementDiagram-BXWQKSXE-oNwG2AbA.js} +1 -1
  122. package/dist/domains/dashboard/web/assets/{sankeyDiagram-P5KCCOFB-DafYyCgJ.js → sankeyDiagram-P5KCCOFB-DfAhDJhA.js} +1 -1
  123. package/dist/domains/dashboard/web/assets/{sequenceDiagram-WJ2MYXX4-DEu4sb48.js → sequenceDiagram-WJ2MYXX4-IlotrNmf.js} +1 -1
  124. package/dist/domains/dashboard/web/assets/{src-je_XM8Ul.js → src-Dcq60QMV.js} +1 -1
  125. package/dist/domains/dashboard/web/assets/{stateDiagram-D77RDMKH-vHbZoYCK.js → stateDiagram-D77RDMKH-7_W4JVdo.js} +1 -1
  126. package/dist/domains/dashboard/web/assets/stateDiagram-v2-MP3YSRHH-Co817OY3.js +1 -0
  127. package/dist/domains/dashboard/web/assets/{swimlanes-42K2YHIH-DxEqhoUX.js → swimlanes-42K2YHIH-d31leTl1.js} +1 -1
  128. package/dist/domains/dashboard/web/assets/swimlanesDiagram-VR7AAH4N-DYbLacQM.js +8 -0
  129. package/dist/domains/dashboard/web/assets/{timeline-definition-24CTP7MA-B4XpTytf.js → timeline-definition-24CTP7MA-nWxcdycl.js} +1 -1
  130. package/dist/domains/dashboard/web/assets/{treeView-Q6P3EWNA-CrismRW3.js → treeView-Q6P3EWNA-5Mutr1Nu.js} +1 -1
  131. package/dist/domains/dashboard/web/assets/{treemap-WGGIJYW6-BGFmknIY.js → treemap-WGGIJYW6-C36e-gzl.js} +1 -1
  132. package/dist/domains/dashboard/web/assets/{vennDiagram-4TSXK5OY-DphMzj7N.js → vennDiagram-4TSXK5OY-DozZoQRR.js} +1 -1
  133. package/dist/domains/dashboard/web/assets/{wardley-WFR3VGLG-DmeLufag.js → wardley-WFR3VGLG-Bz4TuX9w.js} +1 -1
  134. package/dist/domains/dashboard/web/assets/{wardleyDiagram-VM6X3IG4-BUDxONKk.js → wardleyDiagram-VM6X3IG4-DwSpGS7T.js} +1 -1
  135. package/dist/domains/dashboard/web/assets/{xychartDiagram-S5SC5T6Z-BjqVHkW2.js → xychartDiagram-S5SC5T6Z-DZ3ysAHJ.js} +1 -1
  136. package/dist/domains/dashboard/web/index.html +16 -16
  137. package/dist/domains/eval/agent-learning-eval.js +1 -1
  138. package/dist/domains/eval/agent-learning-eval.js.map +1 -1
  139. package/dist/domains/project-knowledge/corpus.d.ts.map +1 -1
  140. package/dist/domains/project-knowledge/corpus.js +13 -13
  141. package/dist/domains/project-knowledge/corpus.js.map +1 -1
  142. package/dist/domains/project-knowledge/deterministic-extractors.d.ts +5 -0
  143. package/dist/domains/project-knowledge/deterministic-extractors.d.ts.map +1 -1
  144. package/dist/domains/project-knowledge/deterministic-extractors.js +374 -178
  145. package/dist/domains/project-knowledge/deterministic-extractors.js.map +1 -1
  146. package/dist/domains/project-knowledge/host-review.d.ts +19 -0
  147. package/dist/domains/project-knowledge/host-review.d.ts.map +1 -0
  148. package/dist/domains/project-knowledge/host-review.js +87 -0
  149. package/dist/domains/project-knowledge/host-review.js.map +1 -0
  150. package/dist/domains/project-knowledge/index-store.d.ts.map +1 -1
  151. package/dist/domains/project-knowledge/index-store.js +2 -2
  152. package/dist/domains/project-knowledge/index-store.js.map +1 -1
  153. package/dist/domains/project-knowledge/index.d.ts +1 -0
  154. package/dist/domains/project-knowledge/index.d.ts.map +1 -1
  155. package/dist/domains/project-knowledge/index.js +1 -0
  156. package/dist/domains/project-knowledge/index.js.map +1 -1
  157. package/dist/domains/project-knowledge/learning.d.ts.map +1 -1
  158. package/dist/domains/project-knowledge/learning.js +15 -9
  159. package/dist/domains/project-knowledge/learning.js.map +1 -1
  160. package/dist/domains/project-knowledge/local-provider.d.ts.map +1 -1
  161. package/dist/domains/project-knowledge/local-provider.js +34 -10
  162. package/dist/domains/project-knowledge/local-provider.js.map +1 -1
  163. package/dist/domains/project-knowledge/local-store.d.ts +3 -0
  164. package/dist/domains/project-knowledge/local-store.d.ts.map +1 -1
  165. package/dist/domains/project-knowledge/local-store.js +298 -108
  166. package/dist/domains/project-knowledge/local-store.js.map +1 -1
  167. package/dist/domains/project-knowledge/plugin.d.ts.map +1 -1
  168. package/dist/domains/project-knowledge/plugin.js +31 -33
  169. package/dist/domains/project-knowledge/plugin.js.map +1 -1
  170. package/dist/domains/project-knowledge/query.d.ts.map +1 -1
  171. package/dist/domains/project-knowledge/query.js +32 -3
  172. package/dist/domains/project-knowledge/query.js.map +1 -1
  173. package/dist/domains/project-knowledge/readiness.d.ts +10 -0
  174. package/dist/domains/project-knowledge/readiness.d.ts.map +1 -0
  175. package/dist/domains/project-knowledge/readiness.js +65 -0
  176. package/dist/domains/project-knowledge/readiness.js.map +1 -0
  177. package/dist/platform/install/project-registry.d.ts.map +1 -1
  178. package/dist/platform/install/project-registry.js +76 -5
  179. package/dist/platform/install/project-registry.js.map +1 -1
  180. package/dist/platform/paths/project-path-selector.d.ts +3 -0
  181. package/dist/platform/paths/project-path-selector.d.ts.map +1 -0
  182. package/dist/platform/paths/project-path-selector.js +32 -0
  183. package/dist/platform/paths/project-path-selector.js.map +1 -0
  184. package/package.json +2 -1
  185. package/dist/domains/dashboard/web/assets/architecture-7GRP2DOG-F2w5dggy.js +0 -1
  186. package/dist/domains/dashboard/web/assets/channel-DLABCQMO.js +0 -1
  187. package/dist/domains/dashboard/web/assets/classDiagram-ZZMXUADV-DJ9Y8TBe.js +0 -1
  188. package/dist/domains/dashboard/web/assets/classDiagram-v2-VYDZK3BY-DJ9Y8TBe.js +0 -1
  189. package/dist/domains/dashboard/web/assets/eventmodeling-NTZA5JFV-LE_eXkBk.js +0 -1
  190. package/dist/domains/dashboard/web/assets/flowDiagram-HODETNUW-Dhg9N1uf.js +0 -1
  191. package/dist/domains/dashboard/web/assets/index-C5iz4lns.css +0 -1
  192. package/dist/domains/dashboard/web/assets/railroad-abnf-HS5TGJTU-CPiOAGi2.js +0 -1
  193. package/dist/domains/dashboard/web/assets/railroad-ebnf-LZEXJU2U-DOuNY-jw.js +0 -1
  194. package/dist/domains/dashboard/web/assets/railroad-peg-WCYAUIDC-DjNccNww.js +0 -1
  195. package/dist/domains/dashboard/web/assets/stateDiagram-v2-MP3YSRHH-C4dywNHK.js +0 -1
  196. package/dist/domains/dashboard/web/assets/swimlanesDiagram-VR7AAH4N-CHhHUVep.js +0 -8
@@ -1,17 +1,17 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cometCreateRequire } from 'module';
3
3
  const require = __cometCreateRequire(import.meta.url);
4
- var zy=Object.create;var Md=Object.defineProperty;var Jy=Object.getOwnPropertyDescriptor;var Gy=Object.getOwnPropertyNames;var Uy=Object.getPrototypeOf,Ky=Object.prototype.hasOwnProperty;var aa=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,i)=>(typeof require<"u"?require:t)[i]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var P=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}};var Yy=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Gy(t))!Ky.call(e,n)&&n!==i&&Md(e,n,{get:()=>t[n],enumerable:!(r=Jy(t,n))||r.enumerable});return e};var Or=(e,t,i)=>(i=e!=null?zy(Uy(e)):{},Yy(t||!e||!e.__esModule?Md(i,"default",{value:e,enumerable:!0}):i,e));var F=P(fe=>{"use strict";var Ms=Symbol.for("yaml.alias"),Jd=Symbol.for("yaml.document"),ca=Symbol.for("yaml.map"),Gd=Symbol.for("yaml.pair"),Ws=Symbol.for("yaml.scalar"),la=Symbol.for("yaml.seq"),kt=Symbol.for("yaml.node.type"),eN=e=>!!e&&typeof e=="object"&&e[kt]===Ms,tN=e=>!!e&&typeof e=="object"&&e[kt]===Jd,iN=e=>!!e&&typeof e=="object"&&e[kt]===ca,rN=e=>!!e&&typeof e=="object"&&e[kt]===Gd,Ud=e=>!!e&&typeof e=="object"&&e[kt]===Ws,nN=e=>!!e&&typeof e=="object"&&e[kt]===la;function Kd(e){if(e&&typeof e=="object")switch(e[kt]){case ca:case la:return!0}return!1}function aN(e){if(e&&typeof e=="object")switch(e[kt]){case Ms:case ca:case Ws:case la:return!0}return!1}var oN=e=>(Ud(e)||Kd(e))&&!!e.anchor;fe.ALIAS=Ms;fe.DOC=Jd;fe.MAP=ca;fe.NODE_TYPE=kt;fe.PAIR=Gd;fe.SCALAR=Ws;fe.SEQ=la;fe.hasAnchor=oN;fe.isAlias=eN;fe.isCollection=Kd;fe.isDocument=tN;fe.isMap=iN;fe.isNode=aN;fe.isPair=rN;fe.isScalar=Ud;fe.isSeq=nN});var Hr=P(zs=>{"use strict";var ce=F(),ke=Symbol("break visit"),Yd=Symbol("skip children"),ut=Symbol("remove node");function ua(e,t){let i=Xd(t);ce.isDocument(e)?Vi(null,e.contents,i,Object.freeze([e]))===ut&&(e.contents=null):Vi(null,e,i,Object.freeze([]))}ua.BREAK=ke;ua.SKIP=Yd;ua.REMOVE=ut;function Vi(e,t,i,r){let n=Qd(e,t,i,r);if(ce.isNode(n)||ce.isPair(n))return Zd(e,r,n),Vi(e,n,i,r);if(typeof n!="symbol"){if(ce.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=Vi(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===ke)return ke;o===ut&&(t.items.splice(a,1),a-=1)}}}else if(ce.isPair(t)){r=Object.freeze(r.concat(t));let a=Vi("key",t.key,i,r);if(a===ke)return ke;a===ut&&(t.key=null);let o=Vi("value",t.value,i,r);if(o===ke)return ke;o===ut&&(t.value=null)}}return n}async function da(e,t){let i=Xd(t);ce.isDocument(e)?await Fi(null,e.contents,i,Object.freeze([e]))===ut&&(e.contents=null):await Fi(null,e,i,Object.freeze([]))}da.BREAK=ke;da.SKIP=Yd;da.REMOVE=ut;async function Fi(e,t,i,r){let n=await Qd(e,t,i,r);if(ce.isNode(n)||ce.isPair(n))return Zd(e,r,n),Fi(e,n,i,r);if(typeof n!="symbol"){if(ce.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=await Fi(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===ke)return ke;o===ut&&(t.items.splice(a,1),a-=1)}}}else if(ce.isPair(t)){r=Object.freeze(r.concat(t));let a=await Fi("key",t.key,i,r);if(a===ke)return ke;a===ut&&(t.key=null);let o=await Fi("value",t.value,i,r);if(o===ke)return ke;o===ut&&(t.value=null)}}return n}function Xd(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 Qd(e,t,i,r){if(typeof i=="function")return i(e,t,r);if(ce.isMap(t))return i.Map?.(e,t,r);if(ce.isSeq(t))return i.Seq?.(e,t,r);if(ce.isPair(t))return i.Pair?.(e,t,r);if(ce.isScalar(t))return i.Scalar?.(e,t,r);if(ce.isAlias(t))return i.Alias?.(e,t,r)}function Zd(e,t,i){let r=t[t.length-1];if(ce.isCollection(r))r.items[e]=i;else if(ce.isPair(r))e==="key"?r.key=i:r.value=i;else if(ce.isDocument(r))r.contents=i;else{let n=ce.isAlias(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}zs.visit=ua;zs.visitAsync=da});var Js=P(tf=>{"use strict";var ef=F(),sN=Hr(),cN={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},lN=e=>e.replace(/[!,[\]{}]/g,t=>cN[t]),Dr=class e{constructor(t,i){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,i)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,i){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let r=t.trim().split(/[ \t]+/),n=r.shift();switch(n){case"%TAG":{if(r.length!==2&&(i(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[a,o]=r;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return i(0,"%YAML directive should contain exactly one part"),!1;let[a]=r;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return i(6,`Unsupported YAML version ${a}`,o),!1}}default:return i(0,`Unknown directive ${n}`,!0),!1}}tagName(t,i){if(t==="!")return"!";if(t[0]!=="!")return i(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(i(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&i("Verbatim tags must end with a >"),o)}let[,r,n]=t.match(/^(.*!)([^!]*)$/s);n||i(`The ${t} tag has no suffix`);let a=this.tags[r];if(a)try{return a+decodeURIComponent(n)}catch(o){return i(String(o)),null}return r==="!"?t:(i(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[i,r]of Object.entries(this.tags))if(t.startsWith(r))return i+lN(t.substring(r.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let i=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),n;if(t&&r.length>0&&ef.isNode(t.contents)){let a={};sN.visit(t.contents,(o,s)=>{ef.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of r)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&i.push(`%TAG ${a} ${o}`);return i.join(`
5
- `)}};Dr.defaultYaml={explicit:!1,version:"1.2"};Dr.defaultTags={"!!":"tag:yaml.org,2002:"};tf.Directives=Dr});var fa=P(Br=>{"use strict";var rf=F(),uN=Hr();function dN(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let i=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(i)}return!0}function nf(e){let t=new Set;return uN.visit(e,{Value(i,r){r.anchor&&t.add(r.anchor)}}),t}function af(e,t){for(let i=1;;++i){let r=`${e}${i}`;if(!t.has(r))return r}}function fN(e,t){let i=[],r=new Map,n=null;return{onAnchor:a=>{i.push(a),n??(n=nf(e));let o=af(t,n);return n.add(o),o},setAnchors:()=>{for(let a of i){let o=r.get(a);if(typeof o=="object"&&o.anchor&&(rf.isScalar(o.node)||rf.isCollection(o.node)))o.node.anchor=o.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=a,s}}},sourceObjects:r}}Br.anchorIsValid=dN;Br.anchorNames=nf;Br.createNodeAnchors=fN;Br.findNewAnchor=af});var Gs=P(of=>{"use strict";function Lr(e,t,i,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let n=0,a=r.length;n<a;++n){let o=r[n],s=Lr(e,r,String(n),o);s===void 0?delete r[n]:s!==o&&(r[n]=s)}else if(r instanceof Map)for(let n of Array.from(r.keys())){let a=r.get(n),o=Lr(e,r,n,a);o===void 0?r.delete(n):o!==a&&r.set(n,o)}else if(r instanceof Set)for(let n of Array.from(r)){let a=Lr(e,r,n,n);a===void 0?r.delete(n):a!==n&&(r.delete(n),r.add(a))}else for(let[n,a]of Object.entries(r)){let o=Lr(e,r,n,a);o===void 0?delete r[n]:o!==a&&(r[n]=o)}return e.call(t,i,r)}of.applyReviver=Lr});var Ft=P(cf=>{"use strict";var pN=F();function sf(e,t,i){if(Array.isArray(e))return e.map((r,n)=>sf(r,String(n),i));if(e&&typeof e.toJSON=="function"){if(!i||!pN.hasAnchor(e))return e.toJSON(t,i);let r={aliasCount:0,count:1,res:void 0};i.anchors.set(e,r),i.onCreate=a=>{r.res=a,delete i.onCreate};let n=e.toJSON(t,i);return i.onCreate&&i.onCreate(n),n}return typeof e=="bigint"&&!i?.keep?Number(e):e}cf.toJS=sf});var pa=P(uf=>{"use strict";var hN=Gs(),lf=F(),mN=Ft(),Us=class{constructor(t){Object.defineProperty(this,lf.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:i,maxAliasCount:r,onAnchor:n,reviver:a}={}){if(!lf.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},s=mN.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?hN.applyReviver(a,{"":s},"",s):s}};uf.NodeBase=Us});var Vr=P(df=>{"use strict";var vN=fa(),gN=Hr(),qi=F(),wN=pa(),yN=Ft(),Ks=class extends wN.NodeBase{constructor(t){super(qi.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,i){if(i?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;i?.aliasResolveCache?r=i.aliasResolveCache:(r=[],gN.visit(t,{Node:(a,o)=>{(qi.isAlias(o)||qi.hasAnchor(o))&&r.push(o)}}),i&&(i.aliasResolveCache=r));let n;for(let a of r){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,i){if(!i)return{source:this.source};let{anchors:r,doc:n,maxAliasCount:a}=i,o=this.resolve(n,i);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=r.get(o);if(s||(yN.toJS(o,null,i),s=r.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=ha(n,o,r)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,i,r){let n=`*${this.source}`;if(t){if(vN.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 ha(e,t,i){if(qi.isAlias(t)){let r=t.resolve(e),n=i&&r&&i.get(r);return n?n.count*n.aliasCount:0}else if(qi.isCollection(t)){let r=0;for(let n of t.items){let a=ha(e,n,i);a>r&&(r=a)}return r}else if(qi.isPair(t)){let r=ha(e,t.key,i),n=ha(e,t.value,i);return Math.max(r,n)}return 1}df.Alias=Ks});var ne=P(Ys=>{"use strict";var NN=F(),bN=pa(),kN=Ft(),SN=e=>!e||typeof e!="function"&&typeof e!="object",qt=class extends bN.NodeBase{constructor(t){super(NN.SCALAR),this.value=t}toJSON(t,i){return i?.keep?this.value:kN.toJS(this.value,t,i)}toString(){return String(this.value)}};qt.BLOCK_FOLDED="BLOCK_FOLDED";qt.BLOCK_LITERAL="BLOCK_LITERAL";qt.PLAIN="PLAIN";qt.QUOTE_DOUBLE="QUOTE_DOUBLE";qt.QUOTE_SINGLE="QUOTE_SINGLE";Ys.Scalar=qt;Ys.isScalarValue=SN});var Fr=P(pf=>{"use strict";var EN=Vr(),wi=F(),ff=ne(),CN="tag:yaml.org,2002:";function xN(e,t,i){if(t){let r=i.filter(a=>a.tag===t),n=r.find(a=>!a.format)??r[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return i.find(r=>r.identify?.(e)&&!r.format)}function PN(e,t,i){if(wi.isDocument(e)&&(e=e.contents),wi.isNode(e))return e;if(wi.isPair(e)){let d=i.schema[wi.MAP].createNode?.(i.schema,null,i);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=i,c;if(r&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new EN.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=CN+t.slice(2));let l=xN(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new ff.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[wi.MAP]:Symbol.iterator in Object(e)?o[wi.SEQ]:o[wi.MAP]}a&&(a(l),delete i.onTagObj);let u=l?.createNode?l.createNode(i.schema,e,i):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(i.schema,e,i):new ff.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}pf.createNode=PN});var va=P(ma=>{"use strict";var RN=Fr(),dt=F(),AN=pa();function Xs(e,t,i){let r=i;for(let n=t.length-1;n>=0;--n){let a=t[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=r,r=o}else r=new Map([[a,r]])}return RN.createNode(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var hf=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Qs=class extends AN.NodeBase{constructor(t,i){super(t),Object.defineProperty(this,"schema",{value:i,configurable:!0,enumerable:!1,writable:!0})}clone(t){let i=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(i.schema=t),i.items=i.items.map(r=>dt.isNode(r)||dt.isPair(r)?r.clone(t):r),this.range&&(i.range=this.range.slice()),i}addIn(t,i){if(hf(t))this.add(i);else{let[r,...n]=t,a=this.get(r,!0);if(dt.isCollection(a))a.addIn(n,i);else if(a===void 0&&this.schema)this.set(r,Xs(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}deleteIn(t){let[i,...r]=t;if(r.length===0)return this.delete(i);let n=this.get(i,!0);if(dt.isCollection(n))return n.deleteIn(r);throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}getIn(t,i){let[r,...n]=t,a=this.get(r,!0);return n.length===0?!i&&dt.isScalar(a)?a.value:a:dt.isCollection(a)?a.getIn(n,i):void 0}hasAllNullValues(t){return this.items.every(i=>{if(!dt.isPair(i))return!1;let r=i.value;return r==null||t&&dt.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(t){let[i,...r]=t;if(r.length===0)return this.has(i);let n=this.get(i,!0);return dt.isCollection(n)?n.hasIn(r):!1}setIn(t,i){let[r,...n]=t;if(n.length===0)this.set(r,i);else{let a=this.get(r,!0);if(dt.isCollection(a))a.setIn(n,i);else if(a===void 0&&this.schema)this.set(r,Xs(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}};ma.Collection=Qs;ma.collectionFromPath=Xs;ma.isEmptyPath=hf});var qr=P(ga=>{"use strict";var _N=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Zs(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var IN=(e,t,i)=>e.endsWith(`
4
+ var Gy=Object.create;var Md=Object.defineProperty;var Uy=Object.getOwnPropertyDescriptor;var Ky=Object.getOwnPropertyNames;var Yy=Object.getPrototypeOf,Xy=Object.prototype.hasOwnProperty;var aa=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,i)=>(typeof require<"u"?require:t)[i]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var P=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}};var Qy=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Ky(t))!Xy.call(e,n)&&n!==i&&Md(e,n,{get:()=>t[n],enumerable:!(r=Uy(t,n))||r.enumerable});return e};var Or=(e,t,i)=>(i=e!=null?Gy(Yy(e)):{},Qy(t||!e||!e.__esModule?Md(i,"default",{value:e,enumerable:!0}):i,e));var F=P(fe=>{"use strict";var Ms=Symbol.for("yaml.alias"),Jd=Symbol.for("yaml.document"),ca=Symbol.for("yaml.map"),Gd=Symbol.for("yaml.pair"),Ws=Symbol.for("yaml.scalar"),la=Symbol.for("yaml.seq"),kt=Symbol.for("yaml.node.type"),iN=e=>!!e&&typeof e=="object"&&e[kt]===Ms,rN=e=>!!e&&typeof e=="object"&&e[kt]===Jd,nN=e=>!!e&&typeof e=="object"&&e[kt]===ca,aN=e=>!!e&&typeof e=="object"&&e[kt]===Gd,Ud=e=>!!e&&typeof e=="object"&&e[kt]===Ws,oN=e=>!!e&&typeof e=="object"&&e[kt]===la;function Kd(e){if(e&&typeof e=="object")switch(e[kt]){case ca:case la:return!0}return!1}function sN(e){if(e&&typeof e=="object")switch(e[kt]){case Ms:case ca:case Ws:case la:return!0}return!1}var cN=e=>(Ud(e)||Kd(e))&&!!e.anchor;fe.ALIAS=Ms;fe.DOC=Jd;fe.MAP=ca;fe.NODE_TYPE=kt;fe.PAIR=Gd;fe.SCALAR=Ws;fe.SEQ=la;fe.hasAnchor=cN;fe.isAlias=iN;fe.isCollection=Kd;fe.isDocument=rN;fe.isMap=nN;fe.isNode=sN;fe.isPair=aN;fe.isScalar=Ud;fe.isSeq=oN});var Hr=P(zs=>{"use strict";var ce=F(),ke=Symbol("break visit"),Yd=Symbol("skip children"),ut=Symbol("remove node");function ua(e,t){let i=Xd(t);ce.isDocument(e)?Vi(null,e.contents,i,Object.freeze([e]))===ut&&(e.contents=null):Vi(null,e,i,Object.freeze([]))}ua.BREAK=ke;ua.SKIP=Yd;ua.REMOVE=ut;function Vi(e,t,i,r){let n=Qd(e,t,i,r);if(ce.isNode(n)||ce.isPair(n))return Zd(e,r,n),Vi(e,n,i,r);if(typeof n!="symbol"){if(ce.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=Vi(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===ke)return ke;o===ut&&(t.items.splice(a,1),a-=1)}}}else if(ce.isPair(t)){r=Object.freeze(r.concat(t));let a=Vi("key",t.key,i,r);if(a===ke)return ke;a===ut&&(t.key=null);let o=Vi("value",t.value,i,r);if(o===ke)return ke;o===ut&&(t.value=null)}}return n}async function da(e,t){let i=Xd(t);ce.isDocument(e)?await Fi(null,e.contents,i,Object.freeze([e]))===ut&&(e.contents=null):await Fi(null,e,i,Object.freeze([]))}da.BREAK=ke;da.SKIP=Yd;da.REMOVE=ut;async function Fi(e,t,i,r){let n=await Qd(e,t,i,r);if(ce.isNode(n)||ce.isPair(n))return Zd(e,r,n),Fi(e,n,i,r);if(typeof n!="symbol"){if(ce.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=await Fi(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===ke)return ke;o===ut&&(t.items.splice(a,1),a-=1)}}}else if(ce.isPair(t)){r=Object.freeze(r.concat(t));let a=await Fi("key",t.key,i,r);if(a===ke)return ke;a===ut&&(t.key=null);let o=await Fi("value",t.value,i,r);if(o===ke)return ke;o===ut&&(t.value=null)}}return n}function Xd(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 Qd(e,t,i,r){if(typeof i=="function")return i(e,t,r);if(ce.isMap(t))return i.Map?.(e,t,r);if(ce.isSeq(t))return i.Seq?.(e,t,r);if(ce.isPair(t))return i.Pair?.(e,t,r);if(ce.isScalar(t))return i.Scalar?.(e,t,r);if(ce.isAlias(t))return i.Alias?.(e,t,r)}function Zd(e,t,i){let r=t[t.length-1];if(ce.isCollection(r))r.items[e]=i;else if(ce.isPair(r))e==="key"?r.key=i:r.value=i;else if(ce.isDocument(r))r.contents=i;else{let n=ce.isAlias(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}zs.visit=ua;zs.visitAsync=da});var Js=P(tf=>{"use strict";var ef=F(),lN=Hr(),uN={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},dN=e=>e.replace(/[!,[\]{}]/g,t=>uN[t]),Dr=class e{constructor(t,i){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,i)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,i){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let r=t.trim().split(/[ \t]+/),n=r.shift();switch(n){case"%TAG":{if(r.length!==2&&(i(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[a,o]=r;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return i(0,"%YAML directive should contain exactly one part"),!1;let[a]=r;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return i(6,`Unsupported YAML version ${a}`,o),!1}}default:return i(0,`Unknown directive ${n}`,!0),!1}}tagName(t,i){if(t==="!")return"!";if(t[0]!=="!")return i(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(i(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&i("Verbatim tags must end with a >"),o)}let[,r,n]=t.match(/^(.*!)([^!]*)$/s);n||i(`The ${t} tag has no suffix`);let a=this.tags[r];if(a)try{return a+decodeURIComponent(n)}catch(o){return i(String(o)),null}return r==="!"?t:(i(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[i,r]of Object.entries(this.tags))if(t.startsWith(r))return i+dN(t.substring(r.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let i=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),n;if(t&&r.length>0&&ef.isNode(t.contents)){let a={};lN.visit(t.contents,(o,s)=>{ef.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of r)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&i.push(`%TAG ${a} ${o}`);return i.join(`
5
+ `)}};Dr.defaultYaml={explicit:!1,version:"1.2"};Dr.defaultTags={"!!":"tag:yaml.org,2002:"};tf.Directives=Dr});var fa=P(Br=>{"use strict";var rf=F(),fN=Hr();function pN(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let i=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(i)}return!0}function nf(e){let t=new Set;return fN.visit(e,{Value(i,r){r.anchor&&t.add(r.anchor)}}),t}function af(e,t){for(let i=1;;++i){let r=`${e}${i}`;if(!t.has(r))return r}}function hN(e,t){let i=[],r=new Map,n=null;return{onAnchor:a=>{i.push(a),n??(n=nf(e));let o=af(t,n);return n.add(o),o},setAnchors:()=>{for(let a of i){let o=r.get(a);if(typeof o=="object"&&o.anchor&&(rf.isScalar(o.node)||rf.isCollection(o.node)))o.node.anchor=o.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=a,s}}},sourceObjects:r}}Br.anchorIsValid=pN;Br.anchorNames=nf;Br.createNodeAnchors=hN;Br.findNewAnchor=af});var Gs=P(of=>{"use strict";function Lr(e,t,i,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let n=0,a=r.length;n<a;++n){let o=r[n],s=Lr(e,r,String(n),o);s===void 0?delete r[n]:s!==o&&(r[n]=s)}else if(r instanceof Map)for(let n of Array.from(r.keys())){let a=r.get(n),o=Lr(e,r,n,a);o===void 0?r.delete(n):o!==a&&r.set(n,o)}else if(r instanceof Set)for(let n of Array.from(r)){let a=Lr(e,r,n,n);a===void 0?r.delete(n):a!==n&&(r.delete(n),r.add(a))}else for(let[n,a]of Object.entries(r)){let o=Lr(e,r,n,a);o===void 0?delete r[n]:o!==a&&(r[n]=o)}return e.call(t,i,r)}of.applyReviver=Lr});var Ft=P(cf=>{"use strict";var mN=F();function sf(e,t,i){if(Array.isArray(e))return e.map((r,n)=>sf(r,String(n),i));if(e&&typeof e.toJSON=="function"){if(!i||!mN.hasAnchor(e))return e.toJSON(t,i);let r={aliasCount:0,count:1,res:void 0};i.anchors.set(e,r),i.onCreate=a=>{r.res=a,delete i.onCreate};let n=e.toJSON(t,i);return i.onCreate&&i.onCreate(n),n}return typeof e=="bigint"&&!i?.keep?Number(e):e}cf.toJS=sf});var pa=P(uf=>{"use strict";var vN=Gs(),lf=F(),gN=Ft(),Us=class{constructor(t){Object.defineProperty(this,lf.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:i,maxAliasCount:r,onAnchor:n,reviver:a}={}){if(!lf.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},s=gN.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?vN.applyReviver(a,{"":s},"",s):s}};uf.NodeBase=Us});var Vr=P(df=>{"use strict";var wN=fa(),yN=Hr(),qi=F(),NN=pa(),bN=Ft(),Ks=class extends NN.NodeBase{constructor(t){super(qi.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,i){if(i?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;i?.aliasResolveCache?r=i.aliasResolveCache:(r=[],yN.visit(t,{Node:(a,o)=>{(qi.isAlias(o)||qi.hasAnchor(o))&&r.push(o)}}),i&&(i.aliasResolveCache=r));let n;for(let a of r){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,i){if(!i)return{source:this.source};let{anchors:r,doc:n,maxAliasCount:a}=i,o=this.resolve(n,i);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=r.get(o);if(s||(bN.toJS(o,null,i),s=r.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=ha(n,o,r)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,i,r){let n=`*${this.source}`;if(t){if(wN.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 ha(e,t,i){if(qi.isAlias(t)){let r=t.resolve(e),n=i&&r&&i.get(r);return n?n.count*n.aliasCount:0}else if(qi.isCollection(t)){let r=0;for(let n of t.items){let a=ha(e,n,i);a>r&&(r=a)}return r}else if(qi.isPair(t)){let r=ha(e,t.key,i),n=ha(e,t.value,i);return Math.max(r,n)}return 1}df.Alias=Ks});var ne=P(Ys=>{"use strict";var kN=F(),SN=pa(),EN=Ft(),CN=e=>!e||typeof e!="function"&&typeof e!="object",qt=class extends SN.NodeBase{constructor(t){super(kN.SCALAR),this.value=t}toJSON(t,i){return i?.keep?this.value:EN.toJS(this.value,t,i)}toString(){return String(this.value)}};qt.BLOCK_FOLDED="BLOCK_FOLDED";qt.BLOCK_LITERAL="BLOCK_LITERAL";qt.PLAIN="PLAIN";qt.QUOTE_DOUBLE="QUOTE_DOUBLE";qt.QUOTE_SINGLE="QUOTE_SINGLE";Ys.Scalar=qt;Ys.isScalarValue=CN});var Fr=P(pf=>{"use strict";var xN=Vr(),wi=F(),ff=ne(),PN="tag:yaml.org,2002:";function RN(e,t,i){if(t){let r=i.filter(a=>a.tag===t),n=r.find(a=>!a.format)??r[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return i.find(r=>r.identify?.(e)&&!r.format)}function AN(e,t,i){if(wi.isDocument(e)&&(e=e.contents),wi.isNode(e))return e;if(wi.isPair(e)){let d=i.schema[wi.MAP].createNode?.(i.schema,null,i);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=i,c;if(r&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new xN.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=PN+t.slice(2));let l=RN(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new ff.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[wi.MAP]:Symbol.iterator in Object(e)?o[wi.SEQ]:o[wi.MAP]}a&&(a(l),delete i.onTagObj);let u=l?.createNode?l.createNode(i.schema,e,i):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(i.schema,e,i):new ff.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}pf.createNode=AN});var va=P(ma=>{"use strict";var _N=Fr(),dt=F(),IN=pa();function Xs(e,t,i){let r=i;for(let n=t.length-1;n>=0;--n){let a=t[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=r,r=o}else r=new Map([[a,r]])}return _N.createNode(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var hf=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Qs=class extends IN.NodeBase{constructor(t,i){super(t),Object.defineProperty(this,"schema",{value:i,configurable:!0,enumerable:!1,writable:!0})}clone(t){let i=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(i.schema=t),i.items=i.items.map(r=>dt.isNode(r)||dt.isPair(r)?r.clone(t):r),this.range&&(i.range=this.range.slice()),i}addIn(t,i){if(hf(t))this.add(i);else{let[r,...n]=t,a=this.get(r,!0);if(dt.isCollection(a))a.addIn(n,i);else if(a===void 0&&this.schema)this.set(r,Xs(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}deleteIn(t){let[i,...r]=t;if(r.length===0)return this.delete(i);let n=this.get(i,!0);if(dt.isCollection(n))return n.deleteIn(r);throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}getIn(t,i){let[r,...n]=t,a=this.get(r,!0);return n.length===0?!i&&dt.isScalar(a)?a.value:a:dt.isCollection(a)?a.getIn(n,i):void 0}hasAllNullValues(t){return this.items.every(i=>{if(!dt.isPair(i))return!1;let r=i.value;return r==null||t&&dt.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(t){let[i,...r]=t;if(r.length===0)return this.has(i);let n=this.get(i,!0);return dt.isCollection(n)?n.hasIn(r):!1}setIn(t,i){let[r,...n]=t;if(n.length===0)this.set(r,i);else{let a=this.get(r,!0);if(dt.isCollection(a))a.setIn(n,i);else if(a===void 0&&this.schema)this.set(r,Xs(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}};ma.Collection=Qs;ma.collectionFromPath=Xs;ma.isEmptyPath=hf});var qr=P(ga=>{"use strict";var TN=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Zs(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var jN=(e,t,i)=>e.endsWith(`
6
6
  `)?Zs(i,t):i.includes(`
7
7
  `)?`
8
- `+Zs(i,t):(e.endsWith(" ")?"":" ")+i;ga.indentComment=Zs;ga.lineComment=IN;ga.stringifyComment=_N});var vf=P(Mr=>{"use strict";var TN="flow",ec="block",wa="quoted";function jN(e,t,i="flow",{indentAtStart:r,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;n<a&&(a=0);let c=Math.max(1+a,1+n-t.length);if(e.length<=c)return e;let l=[],u={},d=n-t.length;typeof r=="number"&&(r>n-Math.max(2,a)?l.push(0):d=n-r);let f,p,v=!1,h=-1,m=-1,S=-1;i===ec&&(h=mf(e,h,t.length),h!==-1&&(d=h+c));for(let k;k=e[h+=1];){if(i===wa&&k==="\\"){switch(m=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}S=h}if(k===`
8
+ `+Zs(i,t):(e.endsWith(" ")?"":" ")+i;ga.indentComment=Zs;ga.lineComment=jN;ga.stringifyComment=TN});var vf=P(Mr=>{"use strict";var $N="flow",ec="block",wa="quoted";function ON(e,t,i="flow",{indentAtStart:r,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;n<a&&(a=0);let c=Math.max(1+a,1+n-t.length);if(e.length<=c)return e;let l=[],u={},d=n-t.length;typeof r=="number"&&(r>n-Math.max(2,a)?l.push(0):d=n-r);let f,p,v=!1,h=-1,m=-1,S=-1;i===ec&&(h=mf(e,h,t.length),h!==-1&&(d=h+c));for(let k;k=e[h+=1];){if(i===wa&&k==="\\"){switch(m=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}S=h}if(k===`
9
9
  `)i===ec&&(h=mf(e,h,t.length)),d=h+t.length+c,f=void 0;else{if(k===" "&&p&&p!==" "&&p!==`
10
10
  `&&p!==" "){let N=e[h+1];N&&N!==" "&&N!==`
11
11
  `&&N!==" "&&(f=h)}if(h>=d)if(f)l.push(f),d=f+c,f=void 0;else if(i===wa){for(;p===" "||p===" ";)p=k,k=e[h+=1],v=!0;let N=h>S+1?h-2:m-1;if(u[N])return e;l.push(N),u[N]=!0,d=N+c,f=void 0}else v=!0}p=k}if(v&&s&&s(),l.length===0)return e;o&&o();let y=e.slice(0,l[0]);for(let k=0;k<l.length;++k){let N=l[k],E=l[k+1]||e.length;N===0?y=`
12
12
  ${t}${e.slice(0,E)}`:(i===wa&&u[N]&&(y+=`${e[N]}\\`),y+=`
13
13
  ${t}${e.slice(N+1,E)}`)}return y}function mf(e,t,i){let r=t,n=t+1,a=e[n];for(;a===" "||a===" ";)if(t<n+i)a=e[++t];else{do a=e[++t];while(a&&a!==`
14
- `);r=t,n=t+1,a=e[n]}return r}Mr.FOLD_BLOCK=ec;Mr.FOLD_FLOW=TN;Mr.FOLD_QUOTED=wa;Mr.foldFlowLines=jN});var zr=P(gf=>{"use strict";var Ue=ne(),Mt=vf(),Na=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),ba=e=>/^(%|---|\.\.\.)/m.test(e);function $N(e,t,i){if(!t||t<0)return!1;let r=t-i,n=e.length;if(n<=r)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
14
+ `);r=t,n=t+1,a=e[n]}return r}Mr.FOLD_BLOCK=ec;Mr.FOLD_FLOW=$N;Mr.FOLD_QUOTED=wa;Mr.foldFlowLines=ON});var zr=P(gf=>{"use strict";var Ue=ne(),Mt=vf(),Na=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),ba=e=>/^(%|---|\.\.\.)/m.test(e);function HN(e,t,i){if(!t||t<0)return!1;let r=t-i,n=e.length;if(n<=r)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
15
15
  `){if(a-o>r)return!0;if(o=a+1,n-o<=r)return!1}return!0}function Wr(e,t){let i=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return i;let{implicitKey:r}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(ba(e)?" ":""),o="",s=0;for(let c=0,l=i[c];l;l=i[++c])if(l===" "&&i[c+1]==="\\"&&i[c+2]==="n"&&(o+=i.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(i[c+1]){case"u":{o+=i.slice(s,c);let u=i.substr(c+2,4);switch(u){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=i.substr(c,6)}c+=5,s=c+1}break;case"n":if(r||i[c+2]==='"'||i.length<n)c+=1;else{for(o+=i.slice(s,c)+`
16
16
 
17
17
  `;i[c+2]==="\\"&&i[c+3]==="n"&&i[c+4]!=='"';)o+=`
@@ -20,7 +20,7 @@ ${t}${e.slice(N+1,E)}`)}return y}function mf(e,t,i){let r=t,n=t+1,a=e[n];for(;a=
20
20
  ${i}`)+"'";return t.implicitKey?r:Mt.foldFlowLines(r,i,Mt.FOLD_FLOW,Na(t,!1))}function Mi(e,t){let{singleQuote:i}=t.options,r;if(i===!1)r=Wr;else{let n=e.includes('"'),a=e.includes("'");n&&!a?r=tc:a&&!n?r=Wr:r=i?tc:Wr}return r(e,t)}var ic;try{ic=new RegExp(`(^|(?<!
21
21
  ))
22
22
  +(?!
23
- |$)`,"g")}catch{ic=/\n+(?!\n|$)/g}function ya({comment:e,type:t,value:i},r,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(i))return Mi(i,r);let l=r.indent||(r.forceBlockIndent||ba(i)?" ":""),u=o==="literal"?!0:o==="folded"||t===Ue.Scalar.BLOCK_FOLDED?!1:t===Ue.Scalar.BLOCK_LITERAL?!0:!$N(i,c,l.length);if(!i)return u?`|
23
+ |$)`,"g")}catch{ic=/\n+(?!\n|$)/g}function ya({comment:e,type:t,value:i},r,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(i))return Mi(i,r);let l=r.indent||(r.forceBlockIndent||ba(i)?" ":""),u=o==="literal"?!0:o==="folded"||t===Ue.Scalar.BLOCK_FOLDED?!1:t===Ue.Scalar.BLOCK_LITERAL?!0:!HN(i,c,l.length);if(!i)return u?`|
24
24
  `:`>
25
25
  `;let d,f;for(f=i.length;f>0;--f){let E=i[f-1];if(E!==`
26
26
  `&&E!==" "&&E!==" ")break}let p=i.substring(f),v=p.indexOf(`
@@ -29,12 +29,12 @@ ${i}`)+"'";return t.implicitKey?r:Mt.foldFlowLines(r,i,Mt.FOLD_FLOW,Na(t,!1))}fu
29
29
  `)S=m;else break}let y=i.substring(0,S<m?S+1:m);y&&(i=i.substring(y.length),y=y.replace(/\n+/g,`$&${l}`));let N=(h?l?"2":"1":"")+d;if(e&&(N+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!u){let E=i.replace(/\n+/g,`
30
30
  $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),b=!1,x=Na(r,!0);o!=="folded"&&t!==Ue.Scalar.BLOCK_FOLDED&&(x.onOverflow=()=>{b=!0});let g=Mt.foldFlowLines(`${y}${E}${p}`,l,Mt.FOLD_BLOCK,x);if(!b)return`>${N}
31
31
  ${l}${g}`}return i=i.replace(/\n+/g,`$&${l}`),`|${N}
32
- ${l}${y}${i}${p}`}function ON(e,t,i,r){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
32
+ ${l}${y}${i}${p}`}function DN(e,t,i,r){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
33
33
  `)||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(`
34
34
  `)?Mi(a,t):ya(e,t,i,r);if(!s&&!u&&n!==Ue.Scalar.PLAIN&&a.includes(`
35
35
  `))return ya(e,t,i,r);if(ba(a)){if(c==="")return t.forceBlockIndent=!0,ya(e,t,i,r);if(s&&c===l)return Mi(a,t)}let d=a.replace(/\n+/g,`$&
36
- ${c}`);if(o){let f=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:p,tags:v}=t.doc.schema;if(v.some(f)||p?.some(f))return Mi(a,t)}return s?d:Mt.foldFlowLines(d,c,Mt.FOLD_FLOW,Na(t,!1))}function HN(e,t,i,r){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==Ue.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=Ue.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case Ue.Scalar.BLOCK_FOLDED:case Ue.Scalar.BLOCK_LITERAL:return n||a?Mi(o.value,t):ya(o,t,i,r);case Ue.Scalar.QUOTE_DOUBLE:return Wr(o.value,t);case Ue.Scalar.QUOTE_SINGLE:return tc(o.value,t);case Ue.Scalar.PLAIN:return ON(o,t,i,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:d}=t.options,f=n&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}gf.stringifyString=HN});var Jr=P(rc=>{"use strict";var DN=fa(),Wt=F(),BN=qr(),LN=zr();function VN(e,t){let i=Object.assign({blockQuote:!0,commentString:BN.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),r;switch(i.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:i.flowCollectionPadding?" ":"",indent:"",indentStep:typeof i.indent=="number"?" ".repeat(i.indent):" ",inFlow:r,options:i}}function FN(e,t){if(t.tag){let n=e.filter(a=>a.tag===t.tag);if(n.length>0)return n.find(a=>a.format===t.format)??n[0]}let i,r;if(Wt.isScalar(t)){r=t.value;let n=e.filter(a=>a.identify?.(r));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}i=n.find(a=>a.format===t.format)??n.find(a=>!a.format)}else r=t,i=e.find(n=>n.nodeClass&&r instanceof n.nodeClass);if(!i){let n=r?.constructor?.name??(r===null?"null":typeof r);throw new Error(`Tag not resolved for ${n} value`)}return i}function qN(e,t,{anchors:i,doc:r}){if(!r.directives)return"";let n=[],a=(Wt.isScalar(e)||Wt.isCollection(e))&&e.anchor;a&&DN.anchorIsValid(a)&&(i.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(r.directives.tagString(o)),n.join(" ")}function MN(e,t,i,r){if(Wt.isPair(e))return e.toString(t,i,r);if(Wt.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let n,a=Wt.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=FN(t.doc.schema.tags,a));let o=qN(a,n,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,t,i,r):Wt.isScalar(a)?LN.stringifyString(a,t,i,r):a.toString(t,i,r);return o?Wt.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
- ${t.indent}${s}`:s}rc.createStringifyContext=VN;rc.stringify=MN});var bf=P(Nf=>{"use strict";var St=F(),wf=ne(),yf=Jr(),Gr=qr();function WN({key:e,value:t},i,r,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=i,f=St.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(St.isCollection(e)||!St.isNode(e)&&typeof e=="object"){let x="With simple keys, collection cannot be used as a key value";throw new Error(x)}}let p=!d&&(!e||f&&t==null&&!i.inFlow||St.isCollection(e)||(St.isScalar(e)?e.type===wf.Scalar.BLOCK_FOLDED||e.type===wf.Scalar.BLOCK_LITERAL:typeof e=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let v=!1,h=!1,m=yf.stringify(e,i,()=>v=!0,()=>h=!0);if(!p&&!i.inFlow&&m.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(i.inFlow){if(a||t==null)return v&&r&&r(),m===""?"?":p?`? ${m}`:m}else if(a&&!d||t==null&&p)return m=`? ${m}`,f&&!v?m+=Gr.lineComment(m,i.indent,l(f)):h&&n&&n(),m;v&&(f=null),p?(f&&(m+=Gr.lineComment(m,i.indent,l(f))),m=`? ${m}
36
+ ${c}`);if(o){let f=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:p,tags:v}=t.doc.schema;if(v.some(f)||p?.some(f))return Mi(a,t)}return s?d:Mt.foldFlowLines(d,c,Mt.FOLD_FLOW,Na(t,!1))}function BN(e,t,i,r){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==Ue.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=Ue.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case Ue.Scalar.BLOCK_FOLDED:case Ue.Scalar.BLOCK_LITERAL:return n||a?Mi(o.value,t):ya(o,t,i,r);case Ue.Scalar.QUOTE_DOUBLE:return Wr(o.value,t);case Ue.Scalar.QUOTE_SINGLE:return tc(o.value,t);case Ue.Scalar.PLAIN:return DN(o,t,i,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:d}=t.options,f=n&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}gf.stringifyString=BN});var Jr=P(rc=>{"use strict";var LN=fa(),Wt=F(),VN=qr(),FN=zr();function qN(e,t){let i=Object.assign({blockQuote:!0,commentString:VN.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),r;switch(i.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:i.flowCollectionPadding?" ":"",indent:"",indentStep:typeof i.indent=="number"?" ".repeat(i.indent):" ",inFlow:r,options:i}}function MN(e,t){if(t.tag){let n=e.filter(a=>a.tag===t.tag);if(n.length>0)return n.find(a=>a.format===t.format)??n[0]}let i,r;if(Wt.isScalar(t)){r=t.value;let n=e.filter(a=>a.identify?.(r));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}i=n.find(a=>a.format===t.format)??n.find(a=>!a.format)}else r=t,i=e.find(n=>n.nodeClass&&r instanceof n.nodeClass);if(!i){let n=r?.constructor?.name??(r===null?"null":typeof r);throw new Error(`Tag not resolved for ${n} value`)}return i}function WN(e,t,{anchors:i,doc:r}){if(!r.directives)return"";let n=[],a=(Wt.isScalar(e)||Wt.isCollection(e))&&e.anchor;a&&LN.anchorIsValid(a)&&(i.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(r.directives.tagString(o)),n.join(" ")}function zN(e,t,i,r){if(Wt.isPair(e))return e.toString(t,i,r);if(Wt.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let n,a=Wt.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=MN(t.doc.schema.tags,a));let o=WN(a,n,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,t,i,r):Wt.isScalar(a)?FN.stringifyString(a,t,i,r):a.toString(t,i,r);return o?Wt.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
+ ${t.indent}${s}`:s}rc.createStringifyContext=qN;rc.stringify=zN});var bf=P(Nf=>{"use strict";var St=F(),wf=ne(),yf=Jr(),Gr=qr();function JN({key:e,value:t},i,r,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=i,f=St.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(St.isCollection(e)||!St.isNode(e)&&typeof e=="object"){let x="With simple keys, collection cannot be used as a key value";throw new Error(x)}}let p=!d&&(!e||f&&t==null&&!i.inFlow||St.isCollection(e)||(St.isScalar(e)?e.type===wf.Scalar.BLOCK_FOLDED||e.type===wf.Scalar.BLOCK_LITERAL:typeof e=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let v=!1,h=!1,m=yf.stringify(e,i,()=>v=!0,()=>h=!0);if(!p&&!i.inFlow&&m.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(i.inFlow){if(a||t==null)return v&&r&&r(),m===""?"?":p?`? ${m}`:m}else if(a&&!d||t==null&&p)return m=`? ${m}`,f&&!v?m+=Gr.lineComment(m,i.indent,l(f)):h&&n&&n(),m;v&&(f=null),p?(f&&(m+=Gr.lineComment(m,i.indent,l(f))),m=`? ${m}
38
38
  ${s}:`):(m=`${m}:`,f&&(m+=Gr.lineComment(m,i.indent,l(f))));let S,y,k;St.isNode(t)?(S=!!t.spaceBefore,y=t.commentBefore,k=t.comment):(S=!1,y=null,k=null,t&&typeof t=="object"&&(t=o.createNode(t))),i.implicitKey=!1,!p&&!f&&St.isScalar(t)&&(i.indentAtStart=m.length+1),h=!1,!u&&c.length>=2&&!i.inFlow&&!p&&St.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(i.indent=i.indent.substring(2));let N=!1,E=yf.stringify(t,i,()=>N=!0,()=>h=!0),b=" ";if(f||S||y){if(b=S?`
39
39
  `:"",y){let x=l(y);b+=`
40
40
  ${Gr.indentComment(x,i.indent)}`}E===""&&!i.inFlow?b===`
@@ -44,32 +44,32 @@ ${Gr.indentComment(x,i.indent)}`}E===""&&!i.inFlow?b===`
44
44
  ${i.indent}`}else if(!p&&St.isCollection(t)){let x=E[0],g=E.indexOf(`
45
45
  `),w=g!==-1,C=i.inFlow??t.flow??t.items.length===0;if(w||!C){let $=!1;if(w&&(x==="&"||x==="!")){let T=E.indexOf(" ");x==="&"&&T!==-1&&T<g&&E[T+1]==="!"&&(T=E.indexOf(" ",T+1)),(T===-1||g<T)&&($=!0)}$||(b=`
46
46
  ${i.indent}`)}}else(E===""||E[0]===`
47
- `)&&(b="");return m+=b+E,i.inFlow?N&&r&&r():k&&!N?m+=Gr.lineComment(m,i.indent,l(k)):h&&n&&n(),m}Nf.stringifyPair=WN});var ac=P(nc=>{"use strict";var kf=aa("process");function zN(e,...t){e==="debug"&&console.log(...t)}function JN(e,t){(e==="debug"||e==="warn")&&(typeof kf.emitWarning=="function"?kf.emitWarning(t):console.warn(t))}nc.debug=zN;nc.warn=JN});var xa=P(Ca=>{"use strict";var Ea=F(),Sf=ne(),ka="<<",Sa={identify:e=>e===ka||typeof e=="symbol"&&e.description===ka,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Sf.Scalar(Symbol(ka)),{addToJSMap:Ef}),stringify:()=>ka},GN=(e,t)=>(Sa.identify(t)||Ea.isScalar(t)&&(!t.type||t.type===Sf.Scalar.PLAIN)&&Sa.identify(t.value))&&e?.doc.schema.tags.some(i=>i.tag===Sa.tag&&i.default);function Ef(e,t,i){let r=Cf(e,i);if(Ea.isSeq(r))for(let n of r.items)oc(e,t,n);else if(Array.isArray(r))for(let n of r)oc(e,t,n);else oc(e,t,r)}function oc(e,t,i){let r=Cf(e,i);if(!Ea.isMap(r))throw new Error("Merge sources must be maps or map aliases");let n=r.toJSON(null,e,Map);for(let[a,o]of n)t instanceof Map?t.has(a)||t.set(a,o):t instanceof Set?t.add(a):Object.prototype.hasOwnProperty.call(t,a)||Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function Cf(e,t){return e&&Ea.isAlias(t)?t.resolve(e.doc,e):t}Ca.addMergeToJSMap=Ef;Ca.isMergeKey=GN;Ca.merge=Sa});var cc=P(Rf=>{"use strict";var UN=ac(),xf=xa(),KN=Jr(),Pf=F(),sc=Ft();function YN(e,t,{key:i,value:r}){if(Pf.isNode(i)&&i.addToJSMap)i.addToJSMap(e,t,r);else if(xf.isMergeKey(e,i))xf.addMergeToJSMap(e,t,r);else{let n=sc.toJS(i,"",e);if(t instanceof Map)t.set(n,sc.toJS(r,n,e));else if(t instanceof Set)t.add(n);else{let a=XN(i,n,e),o=sc.toJS(r,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function XN(e,t,i){if(t===null)return"";if(typeof t!="object")return String(t);if(Pf.isNode(e)&&i?.doc){let r=KN.createStringifyContext(i.doc,{});r.anchors=new Set;for(let a of i.anchors.keys())r.anchors.add(a.anchor);r.inFlow=!0,r.inStringifyKey=!0;let n=e.toString(r);if(!i.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),UN.warn(i.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),i.mapKeyWarned=!0}return n}return JSON.stringify(t)}Rf.addPairToJSMap=YN});var zt=P(lc=>{"use strict";var Af=Fr(),QN=bf(),ZN=cc(),Pa=F();function eb(e,t,i){let r=Af.createNode(e,void 0,i),n=Af.createNode(t,void 0,i);return new Ra(r,n)}var Ra=class e{constructor(t,i=null){Object.defineProperty(this,Pa.NODE_TYPE,{value:Pa.PAIR}),this.key=t,this.value=i}clone(t){let{key:i,value:r}=this;return Pa.isNode(i)&&(i=i.clone(t)),Pa.isNode(r)&&(r=r.clone(t)),new e(i,r)}toJSON(t,i){let r=i?.mapAsMap?new Map:{};return ZN.addPairToJSMap(i,r,this)}toString(t,i,r){return t?.doc?QN.stringifyPair(this,t,i,r):JSON.stringify(this)}};lc.Pair=Ra;lc.createPair=eb});var uc=P(If=>{"use strict";var yi=F(),_f=Jr(),Aa=qr();function tb(e,t,i){return(t.inFlow??e.flow?rb:ib)(e,t,i)}function ib({comment:e,items:t},i,{blockItemPrefix:r,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=i,u=Object.assign({},i,{indent:a,type:null}),d=!1,f=[];for(let v=0;v<t.length;++v){let h=t[v],m=null;if(yi.isNode(h))!d&&h.spaceBefore&&f.push(""),_a(i,f,h.commentBefore,d),h.comment&&(m=h.comment);else if(yi.isPair(h)){let y=yi.isNode(h.key)?h.key:null;y&&(!d&&y.spaceBefore&&f.push(""),_a(i,f,y.commentBefore,d))}d=!1;let S=_f.stringify(h,u,()=>m=null,()=>d=!0);m&&(S+=Aa.lineComment(S,a,l(m))),d&&m&&(d=!1),f.push(r+S)}let p;if(f.length===0)p=n.start+n.end;else{p=f[0];for(let v=1;v<f.length;++v){let h=f[v];p+=h?`
47
+ `)&&(b="");return m+=b+E,i.inFlow?N&&r&&r():k&&!N?m+=Gr.lineComment(m,i.indent,l(k)):h&&n&&n(),m}Nf.stringifyPair=JN});var ac=P(nc=>{"use strict";var kf=aa("process");function GN(e,...t){e==="debug"&&console.log(...t)}function UN(e,t){(e==="debug"||e==="warn")&&(typeof kf.emitWarning=="function"?kf.emitWarning(t):console.warn(t))}nc.debug=GN;nc.warn=UN});var xa=P(Ca=>{"use strict";var Ea=F(),Sf=ne(),ka="<<",Sa={identify:e=>e===ka||typeof e=="symbol"&&e.description===ka,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Sf.Scalar(Symbol(ka)),{addToJSMap:Ef}),stringify:()=>ka},KN=(e,t)=>(Sa.identify(t)||Ea.isScalar(t)&&(!t.type||t.type===Sf.Scalar.PLAIN)&&Sa.identify(t.value))&&e?.doc.schema.tags.some(i=>i.tag===Sa.tag&&i.default);function Ef(e,t,i){let r=Cf(e,i);if(Ea.isSeq(r))for(let n of r.items)oc(e,t,n);else if(Array.isArray(r))for(let n of r)oc(e,t,n);else oc(e,t,r)}function oc(e,t,i){let r=Cf(e,i);if(!Ea.isMap(r))throw new Error("Merge sources must be maps or map aliases");let n=r.toJSON(null,e,Map);for(let[a,o]of n)t instanceof Map?t.has(a)||t.set(a,o):t instanceof Set?t.add(a):Object.prototype.hasOwnProperty.call(t,a)||Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function Cf(e,t){return e&&Ea.isAlias(t)?t.resolve(e.doc,e):t}Ca.addMergeToJSMap=Ef;Ca.isMergeKey=KN;Ca.merge=Sa});var cc=P(Rf=>{"use strict";var YN=ac(),xf=xa(),XN=Jr(),Pf=F(),sc=Ft();function QN(e,t,{key:i,value:r}){if(Pf.isNode(i)&&i.addToJSMap)i.addToJSMap(e,t,r);else if(xf.isMergeKey(e,i))xf.addMergeToJSMap(e,t,r);else{let n=sc.toJS(i,"",e);if(t instanceof Map)t.set(n,sc.toJS(r,n,e));else if(t instanceof Set)t.add(n);else{let a=ZN(i,n,e),o=sc.toJS(r,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function ZN(e,t,i){if(t===null)return"";if(typeof t!="object")return String(t);if(Pf.isNode(e)&&i?.doc){let r=XN.createStringifyContext(i.doc,{});r.anchors=new Set;for(let a of i.anchors.keys())r.anchors.add(a.anchor);r.inFlow=!0,r.inStringifyKey=!0;let n=e.toString(r);if(!i.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),YN.warn(i.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),i.mapKeyWarned=!0}return n}return JSON.stringify(t)}Rf.addPairToJSMap=QN});var zt=P(lc=>{"use strict";var Af=Fr(),eb=bf(),tb=cc(),Pa=F();function ib(e,t,i){let r=Af.createNode(e,void 0,i),n=Af.createNode(t,void 0,i);return new Ra(r,n)}var Ra=class e{constructor(t,i=null){Object.defineProperty(this,Pa.NODE_TYPE,{value:Pa.PAIR}),this.key=t,this.value=i}clone(t){let{key:i,value:r}=this;return Pa.isNode(i)&&(i=i.clone(t)),Pa.isNode(r)&&(r=r.clone(t)),new e(i,r)}toJSON(t,i){let r=i?.mapAsMap?new Map:{};return tb.addPairToJSMap(i,r,this)}toString(t,i,r){return t?.doc?eb.stringifyPair(this,t,i,r):JSON.stringify(this)}};lc.Pair=Ra;lc.createPair=ib});var uc=P(If=>{"use strict";var yi=F(),_f=Jr(),Aa=qr();function rb(e,t,i){return(t.inFlow??e.flow?ab:nb)(e,t,i)}function nb({comment:e,items:t},i,{blockItemPrefix:r,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=i,u=Object.assign({},i,{indent:a,type:null}),d=!1,f=[];for(let v=0;v<t.length;++v){let h=t[v],m=null;if(yi.isNode(h))!d&&h.spaceBefore&&f.push(""),_a(i,f,h.commentBefore,d),h.comment&&(m=h.comment);else if(yi.isPair(h)){let y=yi.isNode(h.key)?h.key:null;y&&(!d&&y.spaceBefore&&f.push(""),_a(i,f,y.commentBefore,d))}d=!1;let S=_f.stringify(h,u,()=>m=null,()=>d=!0);m&&(S+=Aa.lineComment(S,a,l(m))),d&&m&&(d=!1),f.push(r+S)}let p;if(f.length===0)p=n.start+n.end;else{p=f[0];for(let v=1;v<f.length;++v){let h=f[v];p+=h?`
48
48
  ${c}${h}`:`
49
49
  `}}return e?(p+=`
50
- `+Aa.indentComment(l(e),c),s&&s()):d&&o&&o(),p}function rb({items:e},t,{flowChars:i,itemIndent:r}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;r+=a;let c=Object.assign({},t,{indent:r,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let v=0;v<e.length;++v){let h=e[v],m=null;if(yi.isNode(h))h.spaceBefore&&d.push(""),_a(t,d,h.commentBefore,!1),h.comment&&(m=h.comment);else if(yi.isPair(h)){let y=yi.isNode(h.key)?h.key:null;y&&(y.spaceBefore&&d.push(""),_a(t,d,y.commentBefore,!1),y.comment&&(l=!0));let k=yi.isNode(h.value)?h.value:null;k?(k.comment&&(m=k.comment),k.commentBefore&&(l=!0)):h.value==null&&y?.comment&&(m=y.comment)}m&&(l=!0);let S=_f.stringify(h,c,()=>m=null);l||(l=d.length>u||S.includes(`
50
+ `+Aa.indentComment(l(e),c),s&&s()):d&&o&&o(),p}function ab({items:e},t,{flowChars:i,itemIndent:r}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;r+=a;let c=Object.assign({},t,{indent:r,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let v=0;v<e.length;++v){let h=e[v],m=null;if(yi.isNode(h))h.spaceBefore&&d.push(""),_a(t,d,h.commentBefore,!1),h.comment&&(m=h.comment);else if(yi.isPair(h)){let y=yi.isNode(h.key)?h.key:null;y&&(y.spaceBefore&&d.push(""),_a(t,d,y.commentBefore,!1),y.comment&&(l=!0));let k=yi.isNode(h.value)?h.value:null;k?(k.comment&&(m=k.comment),k.commentBefore&&(l=!0)):h.value==null&&y?.comment&&(m=y.comment)}m&&(l=!0);let S=_f.stringify(h,c,()=>m=null);l||(l=d.length>u||S.includes(`
51
51
  `)),v<e.length-1?S+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((y,k)=>y+k.length+2,2)+(S.length+2)>t.options.lineWidth)),l&&(S+=",")),m&&(S+=Aa.lineComment(S,r,s(m))),d.push(S),u=d.length}let{start:f,end:p}=i;if(d.length===0)return f+p;if(!l){let v=d.reduce((h,m)=>h+m.length+2,2);l=t.options.lineWidth>0&&v>t.options.lineWidth}if(l){let v=f;for(let h of d)v+=h?`
52
52
  ${a}${n}${h}`:`
53
53
  `;return`${v}
54
- ${n}${p}`}else return`${f}${o}${d.join(" ")}${o}${p}`}function _a({indent:e,options:{commentString:t}},i,r,n){if(r&&n&&(r=r.replace(/^\n+/,"")),r){let a=Aa.indentComment(t(r),e);i.push(a.trimStart())}}If.stringifyCollection=tb});var Gt=P(fc=>{"use strict";var nb=uc(),ab=cc(),ob=va(),Jt=F(),Ia=zt(),sb=ne();function Ur(e,t){let i=Jt.isScalar(t)?t.value:t;for(let r of e)if(Jt.isPair(r)&&(r.key===t||r.key===i||Jt.isScalar(r.key)&&r.key.value===i))return r}var dc=class extends ob.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Jt.MAP,t),this.items=[]}static from(t,i,r){let{keepUndefined:n,replacer:a}=r,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(i,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||n)&&o.items.push(Ia.createPair(c,l,r))};if(i instanceof Map)for(let[c,l]of i)s(c,l);else if(i&&typeof i=="object")for(let c of Object.keys(i))s(c,i[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,i){let r;Jt.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new Ia.Pair(t,t?.value):r=new Ia.Pair(t.key,t.value);let n=Ur(this.items,r.key),a=this.schema?.sortMapEntries;if(n){if(!i)throw new Error(`Key ${r.key} already set`);Jt.isScalar(n.value)&&sb.isScalarValue(r.value)?n.value.value=r.value:n.value=r.value}else if(a){let o=this.items.findIndex(s=>a(r,s)<0);o===-1?this.items.push(r):this.items.splice(o,0,r)}else this.items.push(r)}delete(t){let i=Ur(this.items,t);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(t,i){let n=Ur(this.items,t)?.value;return(!i&&Jt.isScalar(n)?n.value:n)??void 0}has(t){return!!Ur(this.items,t)}set(t,i){this.add(new Ia.Pair(t,i),!0)}toJSON(t,i,r){let n=r?new r:i?.mapAsMap?new Map:{};i?.onCreate&&i.onCreate(n);for(let a of this.items)ab.addPairToJSMap(i,n,a);return n}toString(t,i,r){if(!t)return JSON.stringify(this);for(let n of this.items)if(!Jt.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})),nb.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:i})}};fc.YAMLMap=dc;fc.findPair=Ur});var Wi=P(jf=>{"use strict";var cb=F(),Tf=Gt(),lb={collection:"map",default:!0,nodeClass:Tf.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return cb.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,i)=>Tf.YAMLMap.from(e,t,i)};jf.map=lb});var Ut=P($f=>{"use strict";var ub=Fr(),db=uc(),fb=va(),ja=F(),pb=ne(),hb=Ft(),pc=class extends fb.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(ja.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let i=Ta(t);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(t,i){let r=Ta(t);if(typeof r!="number")return;let n=this.items[r];return!i&&ja.isScalar(n)?n.value:n}has(t){let i=Ta(t);return typeof i=="number"&&i<this.items.length}set(t,i){let r=Ta(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[r];ja.isScalar(n)&&pb.isScalarValue(i)?n.value=i:this.items[r]=i}toJSON(t,i){let r=[];i?.onCreate&&i.onCreate(r);let n=0;for(let a of this.items)r.push(hb.toJS(a,String(n++),i));return r}toString(t,i,r){return t?db.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:r,onComment:i}):JSON.stringify(this)}static from(t,i,r){let{replacer:n}=r,a=new this(t);if(i&&Symbol.iterator in Object(i)){let o=0;for(let s of i){if(typeof n=="function"){let c=i instanceof Set?s:String(o++);s=n.call(i,c,s)}a.items.push(ub.createNode(s,void 0,r))}}return a}};function Ta(e){let t=ja.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}$f.YAMLSeq=pc});var zi=P(Hf=>{"use strict";var mb=F(),Of=Ut(),vb={collection:"seq",default:!0,nodeClass:Of.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return mb.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,i)=>Of.YAMLSeq.from(e,t,i)};Hf.seq=vb});var Kr=P(Df=>{"use strict";var gb=zr(),wb={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,i,r){return t=Object.assign({actualString:!0},t),gb.stringifyString(e,t,i,r)}};Df.string=wb});var $a=P(Vf=>{"use strict";var Bf=ne(),Lf={identify:e=>e==null,createNode:()=>new Bf.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Bf.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Lf.test.test(e)?e:t.options.nullStr};Vf.nullTag=Lf});var hc=P(qf=>{"use strict";var yb=ne(),Ff={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new yb.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},i){if(e&&Ff.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?i.options.trueStr:i.options.falseStr}};qf.boolTag=Ff});var Ji=P(Mf=>{"use strict";function Nb({format:e,minFractionDigits:t,tag:i,value:r}){if(typeof r=="bigint")return String(r);let n=typeof r=="number"?r:Number(r);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let a=Object.is(r,-0)?"-0":JSON.stringify(r);if(!e&&t&&(!i||i==="tag:yaml.org,2002:float")&&/^-?\d/.test(a)&&!a.includes("e")){let o=a.indexOf(".");o<0&&(o=a.length,a+=".");let s=t-(a.length-o-1);for(;s-- >0;)a+="0"}return a}Mf.stringifyNumber=Nb});var vc=P(Oa=>{"use strict";var bb=ne(),mc=Ji(),kb={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:mc.stringifyNumber},Sb={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():mc.stringifyNumber(e)}},Eb={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 bb.Scalar(parseFloat(e)),i=e.indexOf(".");return i!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-i-1),t},stringify:mc.stringifyNumber};Oa.float=Eb;Oa.floatExp=Sb;Oa.floatNaN=kb});var wc=P(Da=>{"use strict";var Wf=Ji(),Ha=e=>typeof e=="bigint"||Number.isInteger(e),gc=(e,t,i,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),i);function zf(e,t,i){let{value:r}=e;return Ha(r)&&r>=0?i+r.toString(t):Wf.stringifyNumber(e)}var Cb={identify:e=>Ha(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,i)=>gc(e,2,8,i),stringify:e=>zf(e,8,"0o")},xb={identify:Ha,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,i)=>gc(e,0,10,i),stringify:Wf.stringifyNumber},Pb={identify:e=>Ha(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,i)=>gc(e,2,16,i),stringify:e=>zf(e,16,"0x")};Da.int=xb;Da.intHex=Pb;Da.intOct=Cb});var Gf=P(Jf=>{"use strict";var Rb=Wi(),Ab=$a(),_b=zi(),Ib=Kr(),Tb=hc(),yc=vc(),Nc=wc(),jb=[Rb.map,_b.seq,Ib.string,Ab.nullTag,Tb.boolTag,Nc.intOct,Nc.int,Nc.intHex,yc.floatNaN,yc.floatExp,yc.float];Jf.schema=jb});var Yf=P(Kf=>{"use strict";var $b=ne(),Ob=Wi(),Hb=zi();function Uf(e){return typeof e=="bigint"||Number.isInteger(e)}var Ba=({value:e})=>JSON.stringify(e),Db=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Ba},{identify:e=>e==null,createNode:()=>new $b.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Ba},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Ba},{identify:Uf,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:i})=>i?BigInt(e):parseInt(e,10),stringify:({value:e})=>Uf(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:Ba}],Bb={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},Lb=[Ob.map,Hb.seq].concat(Db,Bb);Kf.schema=Lb});var kc=P(Xf=>{"use strict";var Yr=aa("buffer"),bc=ne(),Vb=zr(),Fb={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Yr.Buffer=="function")return Yr.Buffer.from(e,"base64");if(typeof atob=="function"){let i=atob(e.replace(/[\n\r]/g,"")),r=new Uint8Array(i.length);for(let n=0;n<i.length;++n)r[n]=i.charCodeAt(n);return r}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:i},r,n,a){if(!i)return"";let o=i,s;if(typeof Yr.Buffer=="function")s=o instanceof Yr.Buffer?o.toString("base64"):Yr.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=bc.Scalar.BLOCK_LITERAL),t!==bc.Scalar.QUOTE_DOUBLE){let c=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),l=Math.ceil(s.length/c),u=new Array(l);for(let d=0,f=0;d<l;++d,f+=c)u[d]=s.substr(f,c);s=u.join(t===bc.Scalar.BLOCK_LITERAL?`
55
- `:" ")}return Vb.stringifyString({comment:e,type:t,value:s},r,n,a)}};Xf.binary=Fb});var Fa=P(Va=>{"use strict";var La=F(),Sc=zt(),qb=ne(),Mb=Ut();function Qf(e,t){if(La.isSeq(e))for(let i=0;i<e.items.length;++i){let r=e.items[i];if(!La.isPair(r)){if(La.isMap(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");let n=r.items[0]||new Sc.Pair(new qb.Scalar(null));if(r.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${r.commentBefore}
54
+ ${n}${p}`}else return`${f}${o}${d.join(" ")}${o}${p}`}function _a({indent:e,options:{commentString:t}},i,r,n){if(r&&n&&(r=r.replace(/^\n+/,"")),r){let a=Aa.indentComment(t(r),e);i.push(a.trimStart())}}If.stringifyCollection=rb});var Gt=P(fc=>{"use strict";var ob=uc(),sb=cc(),cb=va(),Jt=F(),Ia=zt(),lb=ne();function Ur(e,t){let i=Jt.isScalar(t)?t.value:t;for(let r of e)if(Jt.isPair(r)&&(r.key===t||r.key===i||Jt.isScalar(r.key)&&r.key.value===i))return r}var dc=class extends cb.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Jt.MAP,t),this.items=[]}static from(t,i,r){let{keepUndefined:n,replacer:a}=r,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(i,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||n)&&o.items.push(Ia.createPair(c,l,r))};if(i instanceof Map)for(let[c,l]of i)s(c,l);else if(i&&typeof i=="object")for(let c of Object.keys(i))s(c,i[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,i){let r;Jt.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new Ia.Pair(t,t?.value):r=new Ia.Pair(t.key,t.value);let n=Ur(this.items,r.key),a=this.schema?.sortMapEntries;if(n){if(!i)throw new Error(`Key ${r.key} already set`);Jt.isScalar(n.value)&&lb.isScalarValue(r.value)?n.value.value=r.value:n.value=r.value}else if(a){let o=this.items.findIndex(s=>a(r,s)<0);o===-1?this.items.push(r):this.items.splice(o,0,r)}else this.items.push(r)}delete(t){let i=Ur(this.items,t);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(t,i){let n=Ur(this.items,t)?.value;return(!i&&Jt.isScalar(n)?n.value:n)??void 0}has(t){return!!Ur(this.items,t)}set(t,i){this.add(new Ia.Pair(t,i),!0)}toJSON(t,i,r){let n=r?new r:i?.mapAsMap?new Map:{};i?.onCreate&&i.onCreate(n);for(let a of this.items)sb.addPairToJSMap(i,n,a);return n}toString(t,i,r){if(!t)return JSON.stringify(this);for(let n of this.items)if(!Jt.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})),ob.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:i})}};fc.YAMLMap=dc;fc.findPair=Ur});var Wi=P(jf=>{"use strict";var ub=F(),Tf=Gt(),db={collection:"map",default:!0,nodeClass:Tf.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return ub.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,i)=>Tf.YAMLMap.from(e,t,i)};jf.map=db});var Ut=P($f=>{"use strict";var fb=Fr(),pb=uc(),hb=va(),ja=F(),mb=ne(),vb=Ft(),pc=class extends hb.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(ja.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let i=Ta(t);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(t,i){let r=Ta(t);if(typeof r!="number")return;let n=this.items[r];return!i&&ja.isScalar(n)?n.value:n}has(t){let i=Ta(t);return typeof i=="number"&&i<this.items.length}set(t,i){let r=Ta(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[r];ja.isScalar(n)&&mb.isScalarValue(i)?n.value=i:this.items[r]=i}toJSON(t,i){let r=[];i?.onCreate&&i.onCreate(r);let n=0;for(let a of this.items)r.push(vb.toJS(a,String(n++),i));return r}toString(t,i,r){return t?pb.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:r,onComment:i}):JSON.stringify(this)}static from(t,i,r){let{replacer:n}=r,a=new this(t);if(i&&Symbol.iterator in Object(i)){let o=0;for(let s of i){if(typeof n=="function"){let c=i instanceof Set?s:String(o++);s=n.call(i,c,s)}a.items.push(fb.createNode(s,void 0,r))}}return a}};function Ta(e){let t=ja.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}$f.YAMLSeq=pc});var zi=P(Hf=>{"use strict";var gb=F(),Of=Ut(),wb={collection:"seq",default:!0,nodeClass:Of.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return gb.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,i)=>Of.YAMLSeq.from(e,t,i)};Hf.seq=wb});var Kr=P(Df=>{"use strict";var yb=zr(),Nb={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,i,r){return t=Object.assign({actualString:!0},t),yb.stringifyString(e,t,i,r)}};Df.string=Nb});var $a=P(Vf=>{"use strict";var Bf=ne(),Lf={identify:e=>e==null,createNode:()=>new Bf.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Bf.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Lf.test.test(e)?e:t.options.nullStr};Vf.nullTag=Lf});var hc=P(qf=>{"use strict";var bb=ne(),Ff={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new bb.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},i){if(e&&Ff.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?i.options.trueStr:i.options.falseStr}};qf.boolTag=Ff});var Ji=P(Mf=>{"use strict";function kb({format:e,minFractionDigits:t,tag:i,value:r}){if(typeof r=="bigint")return String(r);let n=typeof r=="number"?r:Number(r);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let a=Object.is(r,-0)?"-0":JSON.stringify(r);if(!e&&t&&(!i||i==="tag:yaml.org,2002:float")&&/^-?\d/.test(a)&&!a.includes("e")){let o=a.indexOf(".");o<0&&(o=a.length,a+=".");let s=t-(a.length-o-1);for(;s-- >0;)a+="0"}return a}Mf.stringifyNumber=kb});var vc=P(Oa=>{"use strict";var Sb=ne(),mc=Ji(),Eb={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:mc.stringifyNumber},Cb={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():mc.stringifyNumber(e)}},xb={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 Sb.Scalar(parseFloat(e)),i=e.indexOf(".");return i!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-i-1),t},stringify:mc.stringifyNumber};Oa.float=xb;Oa.floatExp=Cb;Oa.floatNaN=Eb});var wc=P(Da=>{"use strict";var Wf=Ji(),Ha=e=>typeof e=="bigint"||Number.isInteger(e),gc=(e,t,i,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),i);function zf(e,t,i){let{value:r}=e;return Ha(r)&&r>=0?i+r.toString(t):Wf.stringifyNumber(e)}var Pb={identify:e=>Ha(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,i)=>gc(e,2,8,i),stringify:e=>zf(e,8,"0o")},Rb={identify:Ha,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,i)=>gc(e,0,10,i),stringify:Wf.stringifyNumber},Ab={identify:e=>Ha(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,i)=>gc(e,2,16,i),stringify:e=>zf(e,16,"0x")};Da.int=Rb;Da.intHex=Ab;Da.intOct=Pb});var Gf=P(Jf=>{"use strict";var _b=Wi(),Ib=$a(),Tb=zi(),jb=Kr(),$b=hc(),yc=vc(),Nc=wc(),Ob=[_b.map,Tb.seq,jb.string,Ib.nullTag,$b.boolTag,Nc.intOct,Nc.int,Nc.intHex,yc.floatNaN,yc.floatExp,yc.float];Jf.schema=Ob});var Yf=P(Kf=>{"use strict";var Hb=ne(),Db=Wi(),Bb=zi();function Uf(e){return typeof e=="bigint"||Number.isInteger(e)}var Ba=({value:e})=>JSON.stringify(e),Lb=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Ba},{identify:e=>e==null,createNode:()=>new Hb.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Ba},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Ba},{identify:Uf,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:i})=>i?BigInt(e):parseInt(e,10),stringify:({value:e})=>Uf(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:Ba}],Vb={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},Fb=[Db.map,Bb.seq].concat(Lb,Vb);Kf.schema=Fb});var kc=P(Xf=>{"use strict";var Yr=aa("buffer"),bc=ne(),qb=zr(),Mb={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Yr.Buffer=="function")return Yr.Buffer.from(e,"base64");if(typeof atob=="function"){let i=atob(e.replace(/[\n\r]/g,"")),r=new Uint8Array(i.length);for(let n=0;n<i.length;++n)r[n]=i.charCodeAt(n);return r}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:i},r,n,a){if(!i)return"";let o=i,s;if(typeof Yr.Buffer=="function")s=o instanceof Yr.Buffer?o.toString("base64"):Yr.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=bc.Scalar.BLOCK_LITERAL),t!==bc.Scalar.QUOTE_DOUBLE){let c=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),l=Math.ceil(s.length/c),u=new Array(l);for(let d=0,f=0;d<l;++d,f+=c)u[d]=s.substr(f,c);s=u.join(t===bc.Scalar.BLOCK_LITERAL?`
55
+ `:" ")}return qb.stringifyString({comment:e,type:t,value:s},r,n,a)}};Xf.binary=Mb});var Fa=P(Va=>{"use strict";var La=F(),Sc=zt(),Wb=ne(),zb=Ut();function Qf(e,t){if(La.isSeq(e))for(let i=0;i<e.items.length;++i){let r=e.items[i];if(!La.isPair(r)){if(La.isMap(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");let n=r.items[0]||new Sc.Pair(new Wb.Scalar(null));if(r.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${r.commentBefore}
56
56
  ${n.key.commentBefore}`:r.commentBefore),r.comment){let a=n.value??n.key;a.comment=a.comment?`${r.comment}
57
- ${a.comment}`:r.comment}r=n}e.items[i]=La.isPair(r)?r:new Sc.Pair(r)}}else t("Expected a sequence for this tag");return e}function Zf(e,t,i){let{replacer:r}=i,n=new Mb.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof r=="function"&&(o=r.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(Sc.createPair(s,c,i))}return n}var Wb={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Qf,createNode:Zf};Va.createPairs=Zf;Va.pairs=Wb;Va.resolvePairs=Qf});var xc=P(Cc=>{"use strict";var ep=F(),Ec=Ft(),Xr=Gt(),zb=Ut(),tp=Fa(),Ni=class e extends zb.YAMLSeq{constructor(){super(),this.add=Xr.YAMLMap.prototype.add.bind(this),this.delete=Xr.YAMLMap.prototype.delete.bind(this),this.get=Xr.YAMLMap.prototype.get.bind(this),this.has=Xr.YAMLMap.prototype.has.bind(this),this.set=Xr.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,i){if(!i)return super.toJSON(t);let r=new Map;i?.onCreate&&i.onCreate(r);for(let n of this.items){let a,o;if(ep.isPair(n)?(a=Ec.toJS(n.key,"",i),o=Ec.toJS(n.value,a,i)):a=Ec.toJS(n,"",i),r.has(a))throw new Error("Ordered maps must not include duplicate keys");r.set(a,o)}return r}static from(t,i,r){let n=tp.createPairs(t,i,r),a=new this;return a.items=n.items,a}};Ni.tag="tag:yaml.org,2002:omap";var Jb={collection:"seq",identify:e=>e instanceof Map,nodeClass:Ni,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=tp.resolvePairs(e,t),r=[];for(let{key:n}of i.items)ep.isScalar(n)&&(r.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new Ni,i)},createNode:(e,t,i)=>Ni.from(e,t,i)};Cc.YAMLOMap=Ni;Cc.omap=Jb});var op=P(Pc=>{"use strict";var ip=ne();function rp({value:e,source:t},i){return t&&(e?np:ap).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var np={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 ip.Scalar(!0),stringify:rp},ap={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 ip.Scalar(!1),stringify:rp};Pc.falseTag=ap;Pc.trueTag=np});var sp=P(qa=>{"use strict";var Gb=ne(),Rc=Ji(),Ub={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:Rc.stringifyNumber},Kb={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():Rc.stringifyNumber(e)}},Yb={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 Gb.Scalar(parseFloat(e.replace(/_/g,""))),i=e.indexOf(".");if(i!==-1){let r=e.substring(i+1).replace(/_/g,"");r[r.length-1]==="0"&&(t.minFractionDigits=r.length)}return t},stringify:Rc.stringifyNumber};qa.float=Yb;qa.floatExp=Kb;qa.floatNaN=Ub});var lp=P(Zr=>{"use strict";var cp=Ji(),Qr=e=>typeof e=="bigint"||Number.isInteger(e);function Ma(e,t,i,{intAsBigInt:r}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),r){switch(i){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return n==="-"?BigInt(-1)*o:o}let a=parseInt(e,i);return n==="-"?-1*a:a}function Ac(e,t,i){let{value:r}=e;if(Qr(r)){let n=r.toString(t);return r<0?"-"+i+n.substr(1):i+n}return cp.stringifyNumber(e)}var Xb={identify:Qr,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>Ma(e,2,2,i),stringify:e=>Ac(e,2,"0b")},Qb={identify:Qr,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>Ma(e,1,8,i),stringify:e=>Ac(e,8,"0")},Zb={identify:Qr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>Ma(e,0,10,i),stringify:cp.stringifyNumber},ek={identify:Qr,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>Ma(e,2,16,i),stringify:e=>Ac(e,16,"0x")};Zr.int=Zb;Zr.intBin=Xb;Zr.intHex=ek;Zr.intOct=Qb});var Ic=P(_c=>{"use strict";var Ja=F(),Wa=zt(),za=Gt(),bi=class e extends za.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;Ja.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new Wa.Pair(t.key,null):i=new Wa.Pair(t,null),za.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let r=za.findPair(this.items,t);return!i&&Ja.isPair(r)?Ja.isScalar(r.key)?r.key.value:r.key:r}set(t,i){if(typeof i!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof i}`);let r=za.findPair(this.items,t);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new Wa.Pair(t))}toJSON(t,i){return super.toJSON(t,i,Set)}toString(t,i,r){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),i,r);throw new Error("Set items must all have null values")}static from(t,i,r){let{replacer:n}=r,a=new this(t);if(i&&Symbol.iterator in Object(i))for(let o of i)typeof n=="function"&&(o=n.call(i,o,o)),a.items.push(Wa.createPair(o,null,r));return a}};bi.tag="tag:yaml.org,2002:set";var tk={collection:"map",identify:e=>e instanceof Set,nodeClass:bi,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>bi.from(e,t,i),resolve(e,t){if(Ja.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new bi,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};_c.YAMLSet=bi;_c.set=tk});var jc=P(Ga=>{"use strict";var ik=Ji();function Tc(e,t){let i=e[0],r=i==="-"||i==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=r.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return i==="-"?n(-1)*a:a}function up(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return ik.stringifyNumber(e);let r="";t<0&&(r="-",t*=i(-1));let n=i(60),a=[t%n];return t<60?a.unshift(0):(t=(t-a[0])/n,a.unshift(t%n),t>=60&&(t=(t-a[0])/n,a.unshift(t))),r+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var rk={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:i})=>Tc(e,i),stringify:up},nk={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=>Tc(e,!1),stringify:up},dp={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(dp.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,i,r,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(i,r-1,n,a||0,o||0,s||0,c),u=t[8];if(u&&u!=="Z"){let d=Tc(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$/,"")??""};Ga.floatTime=nk;Ga.intTime=rk;Ga.timestamp=dp});var hp=P(pp=>{"use strict";var ak=Wi(),ok=$a(),sk=zi(),ck=Kr(),lk=kc(),fp=op(),$c=sp(),Ua=lp(),uk=xa(),dk=xc(),fk=Fa(),pk=Ic(),Oc=jc(),hk=[ak.map,sk.seq,ck.string,ok.nullTag,fp.trueTag,fp.falseTag,Ua.intBin,Ua.intOct,Ua.int,Ua.intHex,$c.floatNaN,$c.floatExp,$c.float,lk.binary,uk.merge,dk.omap,fk.pairs,pk.set,Oc.intTime,Oc.floatTime,Oc.timestamp];pp.schema=hk});var Ep=P(Bc=>{"use strict";var wp=Wi(),mk=$a(),yp=zi(),vk=Kr(),gk=hc(),Hc=vc(),Dc=wc(),wk=Gf(),yk=Yf(),Np=kc(),en=xa(),bp=xc(),kp=Fa(),mp=hp(),Sp=Ic(),Ka=jc(),vp=new Map([["core",wk.schema],["failsafe",[wp.map,yp.seq,vk.string]],["json",yk.schema],["yaml11",mp.schema],["yaml-1.1",mp.schema]]),gp={binary:Np.binary,bool:gk.boolTag,float:Hc.float,floatExp:Hc.floatExp,floatNaN:Hc.floatNaN,floatTime:Ka.floatTime,int:Dc.int,intHex:Dc.intHex,intOct:Dc.intOct,intTime:Ka.intTime,map:wp.map,merge:en.merge,null:mk.nullTag,omap:bp.omap,pairs:kp.pairs,seq:yp.seq,set:Sp.set,timestamp:Ka.timestamp},Nk={"tag:yaml.org,2002:binary":Np.binary,"tag:yaml.org,2002:merge":en.merge,"tag:yaml.org,2002:omap":bp.omap,"tag:yaml.org,2002:pairs":kp.pairs,"tag:yaml.org,2002:set":Sp.set,"tag:yaml.org,2002:timestamp":Ka.timestamp};function bk(e,t,i){let r=vp.get(t);if(r&&!e)return i&&!r.includes(en.merge)?r.concat(en.merge):r.slice();let n=r;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(vp.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${a} or define customTags array`)}if(Array.isArray(e))for(let a of e)n=n.concat(a);else typeof e=="function"&&(n=e(n.slice()));return i&&(n=n.concat(en.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?gp[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(gp).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},[])}Bc.coreKnownTags=Nk;Bc.getTags=bk});var Fc=P(Cp=>{"use strict";var Lc=F(),kk=Wi(),Sk=zi(),Ek=Kr(),Ya=Ep(),Ck=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Vc=class e{constructor({compat:t,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Ya.getTags(t,"compat"):t?Ya.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Ya.coreKnownTags:{},this.tags=Ya.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,Lc.MAP,{value:kk.map}),Object.defineProperty(this,Lc.SCALAR,{value:Ek.string}),Object.defineProperty(this,Lc.SEQ,{value:Sk.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Ck:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Cp.Schema=Vc});var Pp=P(xp=>{"use strict";var xk=F(),qc=Jr(),tn=qr();function Pk(e,t){let i=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(i.push(c),r=!0):e.directives.docStart&&(r=!0)}r&&i.push("---");let n=qc.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(tn.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(xk.isNode(e.contents)){if(e.contents.spaceBefore&&r&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(tn.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=qc.stringify(e.contents,n,()=>s=null,c);s&&(l+=tn.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(qc.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
57
+ ${a.comment}`:r.comment}r=n}e.items[i]=La.isPair(r)?r:new Sc.Pair(r)}}else t("Expected a sequence for this tag");return e}function Zf(e,t,i){let{replacer:r}=i,n=new zb.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof r=="function"&&(o=r.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(Sc.createPair(s,c,i))}return n}var Jb={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Qf,createNode:Zf};Va.createPairs=Zf;Va.pairs=Jb;Va.resolvePairs=Qf});var xc=P(Cc=>{"use strict";var ep=F(),Ec=Ft(),Xr=Gt(),Gb=Ut(),tp=Fa(),Ni=class e extends Gb.YAMLSeq{constructor(){super(),this.add=Xr.YAMLMap.prototype.add.bind(this),this.delete=Xr.YAMLMap.prototype.delete.bind(this),this.get=Xr.YAMLMap.prototype.get.bind(this),this.has=Xr.YAMLMap.prototype.has.bind(this),this.set=Xr.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,i){if(!i)return super.toJSON(t);let r=new Map;i?.onCreate&&i.onCreate(r);for(let n of this.items){let a,o;if(ep.isPair(n)?(a=Ec.toJS(n.key,"",i),o=Ec.toJS(n.value,a,i)):a=Ec.toJS(n,"",i),r.has(a))throw new Error("Ordered maps must not include duplicate keys");r.set(a,o)}return r}static from(t,i,r){let n=tp.createPairs(t,i,r),a=new this;return a.items=n.items,a}};Ni.tag="tag:yaml.org,2002:omap";var Ub={collection:"seq",identify:e=>e instanceof Map,nodeClass:Ni,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=tp.resolvePairs(e,t),r=[];for(let{key:n}of i.items)ep.isScalar(n)&&(r.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new Ni,i)},createNode:(e,t,i)=>Ni.from(e,t,i)};Cc.YAMLOMap=Ni;Cc.omap=Ub});var op=P(Pc=>{"use strict";var ip=ne();function rp({value:e,source:t},i){return t&&(e?np:ap).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var np={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 ip.Scalar(!0),stringify:rp},ap={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 ip.Scalar(!1),stringify:rp};Pc.falseTag=ap;Pc.trueTag=np});var sp=P(qa=>{"use strict";var Kb=ne(),Rc=Ji(),Yb={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:Rc.stringifyNumber},Xb={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():Rc.stringifyNumber(e)}},Qb={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new Kb.Scalar(parseFloat(e.replace(/_/g,""))),i=e.indexOf(".");if(i!==-1){let r=e.substring(i+1).replace(/_/g,"");r[r.length-1]==="0"&&(t.minFractionDigits=r.length)}return t},stringify:Rc.stringifyNumber};qa.float=Qb;qa.floatExp=Xb;qa.floatNaN=Yb});var lp=P(Zr=>{"use strict";var cp=Ji(),Qr=e=>typeof e=="bigint"||Number.isInteger(e);function Ma(e,t,i,{intAsBigInt:r}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),r){switch(i){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return n==="-"?BigInt(-1)*o:o}let a=parseInt(e,i);return n==="-"?-1*a:a}function Ac(e,t,i){let{value:r}=e;if(Qr(r)){let n=r.toString(t);return r<0?"-"+i+n.substr(1):i+n}return cp.stringifyNumber(e)}var Zb={identify:Qr,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>Ma(e,2,2,i),stringify:e=>Ac(e,2,"0b")},ek={identify:Qr,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>Ma(e,1,8,i),stringify:e=>Ac(e,8,"0")},tk={identify:Qr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>Ma(e,0,10,i),stringify:cp.stringifyNumber},ik={identify:Qr,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>Ma(e,2,16,i),stringify:e=>Ac(e,16,"0x")};Zr.int=tk;Zr.intBin=Zb;Zr.intHex=ik;Zr.intOct=ek});var Ic=P(_c=>{"use strict";var Ja=F(),Wa=zt(),za=Gt(),bi=class e extends za.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;Ja.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new Wa.Pair(t.key,null):i=new Wa.Pair(t,null),za.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let r=za.findPair(this.items,t);return!i&&Ja.isPair(r)?Ja.isScalar(r.key)?r.key.value:r.key:r}set(t,i){if(typeof i!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof i}`);let r=za.findPair(this.items,t);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new Wa.Pair(t))}toJSON(t,i){return super.toJSON(t,i,Set)}toString(t,i,r){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),i,r);throw new Error("Set items must all have null values")}static from(t,i,r){let{replacer:n}=r,a=new this(t);if(i&&Symbol.iterator in Object(i))for(let o of i)typeof n=="function"&&(o=n.call(i,o,o)),a.items.push(Wa.createPair(o,null,r));return a}};bi.tag="tag:yaml.org,2002:set";var rk={collection:"map",identify:e=>e instanceof Set,nodeClass:bi,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>bi.from(e,t,i),resolve(e,t){if(Ja.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new bi,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};_c.YAMLSet=bi;_c.set=rk});var jc=P(Ga=>{"use strict";var nk=Ji();function Tc(e,t){let i=e[0],r=i==="-"||i==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=r.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return i==="-"?n(-1)*a:a}function up(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return nk.stringifyNumber(e);let r="";t<0&&(r="-",t*=i(-1));let n=i(60),a=[t%n];return t<60?a.unshift(0):(t=(t-a[0])/n,a.unshift(t%n),t>=60&&(t=(t-a[0])/n,a.unshift(t))),r+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var ak={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:i})=>Tc(e,i),stringify:up},ok={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=>Tc(e,!1),stringify:up},dp={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(dp.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,i,r,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(i,r-1,n,a||0,o||0,s||0,c),u=t[8];if(u&&u!=="Z"){let d=Tc(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$/,"")??""};Ga.floatTime=ok;Ga.intTime=ak;Ga.timestamp=dp});var hp=P(pp=>{"use strict";var sk=Wi(),ck=$a(),lk=zi(),uk=Kr(),dk=kc(),fp=op(),$c=sp(),Ua=lp(),fk=xa(),pk=xc(),hk=Fa(),mk=Ic(),Oc=jc(),vk=[sk.map,lk.seq,uk.string,ck.nullTag,fp.trueTag,fp.falseTag,Ua.intBin,Ua.intOct,Ua.int,Ua.intHex,$c.floatNaN,$c.floatExp,$c.float,dk.binary,fk.merge,pk.omap,hk.pairs,mk.set,Oc.intTime,Oc.floatTime,Oc.timestamp];pp.schema=vk});var Ep=P(Bc=>{"use strict";var wp=Wi(),gk=$a(),yp=zi(),wk=Kr(),yk=hc(),Hc=vc(),Dc=wc(),Nk=Gf(),bk=Yf(),Np=kc(),en=xa(),bp=xc(),kp=Fa(),mp=hp(),Sp=Ic(),Ka=jc(),vp=new Map([["core",Nk.schema],["failsafe",[wp.map,yp.seq,wk.string]],["json",bk.schema],["yaml11",mp.schema],["yaml-1.1",mp.schema]]),gp={binary:Np.binary,bool:yk.boolTag,float:Hc.float,floatExp:Hc.floatExp,floatNaN:Hc.floatNaN,floatTime:Ka.floatTime,int:Dc.int,intHex:Dc.intHex,intOct:Dc.intOct,intTime:Ka.intTime,map:wp.map,merge:en.merge,null:gk.nullTag,omap:bp.omap,pairs:kp.pairs,seq:yp.seq,set:Sp.set,timestamp:Ka.timestamp},kk={"tag:yaml.org,2002:binary":Np.binary,"tag:yaml.org,2002:merge":en.merge,"tag:yaml.org,2002:omap":bp.omap,"tag:yaml.org,2002:pairs":kp.pairs,"tag:yaml.org,2002:set":Sp.set,"tag:yaml.org,2002:timestamp":Ka.timestamp};function Sk(e,t,i){let r=vp.get(t);if(r&&!e)return i&&!r.includes(en.merge)?r.concat(en.merge):r.slice();let n=r;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(vp.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${a} or define customTags array`)}if(Array.isArray(e))for(let a of e)n=n.concat(a);else typeof e=="function"&&(n=e(n.slice()));return i&&(n=n.concat(en.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?gp[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(gp).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},[])}Bc.coreKnownTags=kk;Bc.getTags=Sk});var Fc=P(Cp=>{"use strict";var Lc=F(),Ek=Wi(),Ck=zi(),xk=Kr(),Ya=Ep(),Pk=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Vc=class e{constructor({compat:t,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Ya.getTags(t,"compat"):t?Ya.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Ya.coreKnownTags:{},this.tags=Ya.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,Lc.MAP,{value:Ek.map}),Object.defineProperty(this,Lc.SCALAR,{value:xk.string}),Object.defineProperty(this,Lc.SEQ,{value:Ck.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Pk:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Cp.Schema=Vc});var Pp=P(xp=>{"use strict";var Rk=F(),qc=Jr(),tn=qr();function Ak(e,t){let i=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(i.push(c),r=!0):e.directives.docStart&&(r=!0)}r&&i.push("---");let n=qc.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(tn.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(Rk.isNode(e.contents)){if(e.contents.spaceBefore&&r&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(tn.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=qc.stringify(e.contents,n,()=>s=null,c);s&&(l+=tn.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(qc.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
58
58
  `)?(i.push("..."),i.push(tn.indentComment(c,""))):i.push(`... ${c}`)}else i.push("...");else{let c=e.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&i[i.length-1]!==""&&i.push(""),i.push(tn.indentComment(a(c),"")))}return i.join(`
59
59
  `)+`
60
- `}xp.stringifyDocument=Pk});var rn=P(Rp=>{"use strict";var Rk=Vr(),Gi=va(),He=F(),Ak=zt(),_k=Ft(),Ik=Fc(),Tk=Pp(),Mc=fa(),jk=Gs(),$k=Fr(),Wc=Js(),zc=class e{constructor(t,i,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,He.NODE_TYPE,{value:He.DOC});let n=null;typeof i=="function"||Array.isArray(i)?n=i:r===void 0&&i&&(r=i,i=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=a;let{version:o}=a;r?._directives?(this.directives=r._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new Wc.Directives({version:o}),this.setSchema(o,r),this.contents=t===void 0?null:this.createNode(t,n,r)}clone(){let t=Object.create(e.prototype,{[He.NODE_TYPE]:{value:He.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=He.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){Ui(this.contents)&&this.contents.add(t)}addIn(t,i){Ui(this.contents)&&this.contents.addIn(t,i)}createAlias(t,i){if(!t.anchor){let r=Mc.anchorNames(this);t.anchor=!i||r.has(i)?Mc.findNewAnchor(i||"a",r):i}return new Rk.Alias(t.anchor)}createNode(t,i,r){let n;if(typeof i=="function")t=i.call({"":t},"",t),n=i;else if(Array.isArray(i)){let m=y=>typeof y=="number"||y instanceof String||y instanceof Number,S=i.filter(m).map(String);S.length>0&&(i=i.concat(S)),n=i}else r===void 0&&i&&(r=i,i=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:u}=r??{},{onAnchor:d,setAnchors:f,sourceObjects:p}=Mc.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:p},h=$k.createNode(t,u,v);return s&&He.isCollection(h)&&(h.flow=!0),f(),h}createPair(t,i,r={}){let n=this.createNode(t,null,r),a=this.createNode(i,null,r);return new Ak.Pair(n,a)}delete(t){return Ui(this.contents)?this.contents.delete(t):!1}deleteIn(t){return Gi.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Ui(this.contents)?this.contents.deleteIn(t):!1}get(t,i){return He.isCollection(this.contents)?this.contents.get(t,i):void 0}getIn(t,i){return Gi.isEmptyPath(t)?!i&&He.isScalar(this.contents)?this.contents.value:this.contents:He.isCollection(this.contents)?this.contents.getIn(t,i):void 0}has(t){return He.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return Gi.isEmptyPath(t)?this.contents!==void 0:He.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,i){this.contents==null?this.contents=Gi.collectionFromPath(this.schema,[t],i):Ui(this.contents)&&this.contents.set(t,i)}setIn(t,i){Gi.isEmptyPath(t)?this.contents=i:this.contents==null?this.contents=Gi.collectionFromPath(this.schema,Array.from(t),i):Ui(this.contents)&&this.contents.setIn(t,i)}setSchema(t,i={}){typeof t=="number"&&(t=String(t));let r;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Wc.Directives({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new Wc.Directives({version:t}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let n=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${n}`)}}if(i.schema instanceof Object)this.schema=i.schema;else if(r)this.schema=new Ik.Schema(Object.assign(r,i));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:i,mapAsMap:r,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=_k.toJS(this.contents,i??"",s);if(typeof a=="function")for(let{count:l,res:u}of s.anchors.values())a(u,l);return typeof o=="function"?jk.applyReviver(o,{"":c},"",c):c}toJSON(t,i){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:i})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let i=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${i}`)}return Tk.stringifyDocument(this,t)}};function Ui(e){if(He.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Rp.Document=zc});var on=P(an=>{"use strict";var nn=class extends Error{constructor(t,i,r,n){super(),this.name=t,this.code=r,this.message=n,this.pos=i}},Jc=class extends nn{constructor(t,i,r){super("YAMLParseError",t,i,r)}},Gc=class extends nn{constructor(t,i,r){super("YAMLWarning",t,i,r)}},Ok=(e,t)=>i=>{if(i.pos[0]===-1)return;i.linePos=i.pos.map(s=>t.linePos(s));let{line:r,col:n}=i.linePos[0];i.message+=` at line ${r}, column ${n}`;let a=n-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,"");if(a>=60&&o.length>80){let s=Math.min(a-39,o.length-79);o="…"+o.substring(s),a-=s-1}if(o.length>80&&(o=o.substring(0,79)+"…"),r>1&&/^ *$/.test(o.substring(0,a))){let s=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);s.length>80&&(s=s.substring(0,79)+`…
60
+ `}xp.stringifyDocument=Ak});var rn=P(Rp=>{"use strict";var _k=Vr(),Gi=va(),He=F(),Ik=zt(),Tk=Ft(),jk=Fc(),$k=Pp(),Mc=fa(),Ok=Gs(),Hk=Fr(),Wc=Js(),zc=class e{constructor(t,i,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,He.NODE_TYPE,{value:He.DOC});let n=null;typeof i=="function"||Array.isArray(i)?n=i:r===void 0&&i&&(r=i,i=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=a;let{version:o}=a;r?._directives?(this.directives=r._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new Wc.Directives({version:o}),this.setSchema(o,r),this.contents=t===void 0?null:this.createNode(t,n,r)}clone(){let t=Object.create(e.prototype,{[He.NODE_TYPE]:{value:He.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=He.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){Ui(this.contents)&&this.contents.add(t)}addIn(t,i){Ui(this.contents)&&this.contents.addIn(t,i)}createAlias(t,i){if(!t.anchor){let r=Mc.anchorNames(this);t.anchor=!i||r.has(i)?Mc.findNewAnchor(i||"a",r):i}return new _k.Alias(t.anchor)}createNode(t,i,r){let n;if(typeof i=="function")t=i.call({"":t},"",t),n=i;else if(Array.isArray(i)){let m=y=>typeof y=="number"||y instanceof String||y instanceof Number,S=i.filter(m).map(String);S.length>0&&(i=i.concat(S)),n=i}else r===void 0&&i&&(r=i,i=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:u}=r??{},{onAnchor:d,setAnchors:f,sourceObjects:p}=Mc.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:p},h=Hk.createNode(t,u,v);return s&&He.isCollection(h)&&(h.flow=!0),f(),h}createPair(t,i,r={}){let n=this.createNode(t,null,r),a=this.createNode(i,null,r);return new Ik.Pair(n,a)}delete(t){return Ui(this.contents)?this.contents.delete(t):!1}deleteIn(t){return Gi.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Ui(this.contents)?this.contents.deleteIn(t):!1}get(t,i){return He.isCollection(this.contents)?this.contents.get(t,i):void 0}getIn(t,i){return Gi.isEmptyPath(t)?!i&&He.isScalar(this.contents)?this.contents.value:this.contents:He.isCollection(this.contents)?this.contents.getIn(t,i):void 0}has(t){return He.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return Gi.isEmptyPath(t)?this.contents!==void 0:He.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,i){this.contents==null?this.contents=Gi.collectionFromPath(this.schema,[t],i):Ui(this.contents)&&this.contents.set(t,i)}setIn(t,i){Gi.isEmptyPath(t)?this.contents=i:this.contents==null?this.contents=Gi.collectionFromPath(this.schema,Array.from(t),i):Ui(this.contents)&&this.contents.setIn(t,i)}setSchema(t,i={}){typeof t=="number"&&(t=String(t));let r;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Wc.Directives({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new Wc.Directives({version:t}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let n=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${n}`)}}if(i.schema instanceof Object)this.schema=i.schema;else if(r)this.schema=new jk.Schema(Object.assign(r,i));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:i,mapAsMap:r,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=Tk.toJS(this.contents,i??"",s);if(typeof a=="function")for(let{count:l,res:u}of s.anchors.values())a(u,l);return typeof o=="function"?Ok.applyReviver(o,{"":c},"",c):c}toJSON(t,i){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:i})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let i=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${i}`)}return $k.stringifyDocument(this,t)}};function Ui(e){if(He.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Rp.Document=zc});var on=P(an=>{"use strict";var nn=class extends Error{constructor(t,i,r,n){super(),this.name=t,this.code=r,this.message=n,this.pos=i}},Jc=class extends nn{constructor(t,i,r){super("YAMLParseError",t,i,r)}},Gc=class extends nn{constructor(t,i,r){super("YAMLWarning",t,i,r)}},Dk=(e,t)=>i=>{if(i.pos[0]===-1)return;i.linePos=i.pos.map(s=>t.linePos(s));let{line:r,col:n}=i.linePos[0];i.message+=` at line ${r}, column ${n}`;let a=n-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,"");if(a>=60&&o.length>80){let s=Math.min(a-39,o.length-79);o="…"+o.substring(s),a-=s-1}if(o.length>80&&(o=o.substring(0,79)+"…"),r>1&&/^ *$/.test(o.substring(0,a))){let s=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);s.length>80&&(s=s.substring(0,79)+`…
61
61
  `),o=s+o}if(/[^ ]/.test(o)){let s=1,c=i.linePos[1];c?.line===r&&c.col>n&&(s=Math.max(1,Math.min(c.col-n,80-a)));let l=" ".repeat(a)+"^".repeat(s);i.message+=`:
62
62
 
63
63
  ${o}
64
64
  ${l}
65
- `}};an.YAMLError=nn;an.YAMLParseError=Jc;an.YAMLWarning=Gc;an.prettifyError=Ok});var sn=P(Ap=>{"use strict";function Hk(e,{flow:t,indicator:i,next:r,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d="",f="",p=!1,v=!1,h=null,m=null,S=null,y=null,k=null,N=null,E=null;for(let g of e)switch(v&&(g.type!=="space"&&g.type!=="newline"&&g.type!=="comma"&&a(g.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),h&&(l&&g.type!=="comment"&&g.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),g.type){case"space":!t&&(i!=="doc-start"||r?.type!=="flow-collection")&&g.source.includes(" ")&&(h=g),u=!0;break;case"comment":{u||a(g,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let w=g.source.substring(1)||" ";d?d+=f+w:d=w,f="",l=!1;break}case"newline":l?d?d+=g.source:(!N||i!=="seq-item-ind")&&(c=!0):f+=g.source,l=!0,p=!0,(m||S)&&(y=g),u=!0;break;case"anchor":m&&a(g,"MULTIPLE_ANCHORS","A node can have at most one anchor"),g.source.endsWith(":")&&a(g.offset+g.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),m=g,E??(E=g.offset),l=!1,u=!1,v=!0;break;case"tag":{S&&a(g,"MULTIPLE_TAGS","A node can have at most one tag"),S=g,E??(E=g.offset),l=!1,u=!1,v=!0;break}case i:(m||S)&&a(g,"BAD_PROP_ORDER",`Anchors and tags must be after the ${g.source} indicator`),N&&a(g,"UNEXPECTED_TOKEN",`Unexpected ${g.source} in ${t??"collection"}`),N=g,l=i==="seq-item-ind"||i==="explicit-key-ind",u=!1;break;case"comma":if(t){k&&a(g,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),k=g,l=!1,u=!1;break}default:a(g,"UNEXPECTED_TOKEN",`Unexpected ${g.type} token`),l=!1,u=!1}let b=e[e.length-1],x=b?b.offset+b.source.length:n;return v&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&a(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||r?.type==="block-map"||r?.type==="block-seq")&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:k,found:N,spaceBefore:c,comment:d,hasNewline:p,anchor:m,tag:S,newlineAfterProp:y,end:x,start:E??x}}Ap.resolveProps=Hk});var Xa=P(_p=>{"use strict";function Uc(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
66
- `))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let i of t.start)if(i.type==="newline")return!0;if(t.sep){for(let i of t.sep)if(i.type==="newline")return!0}if(Uc(t.key)||Uc(t.value))return!0}return!1;default:return!0}}_p.containsNewline=Uc});var Kc=P(Ip=>{"use strict";var Dk=Xa();function Bk(e,t,i){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&Dk.containsNewline(t)&&i(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Ip.flowIndentCheck=Bk});var Yc=P(jp=>{"use strict";var Tp=F();function Lk(e,t,i){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let n=typeof r=="function"?r:(a,o)=>a===o||Tp.isScalar(a)&&Tp.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,i))}jp.mapIncludes=Lk});var Lp=P(Bp=>{"use strict";var $p=zt(),Vk=Gt(),Op=sn(),Fk=Xa(),Hp=Kc(),qk=Yc(),Dp="All mapping items must start at the same column";function Mk({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??Vk.YAMLMap,s=new o(i.schema);i.atRoot&&(i.atRoot=!1);let c=r.offset,l=null;for(let u of r.items){let{start:d,key:f,sep:p,value:v}=u,h=Op.resolveProps(d,{indicator:"explicit-key-ind",next:f??p?.[0],offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0}),m=!h.found;if(m){if(f&&(f.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==r.indent&&n(c,"BAD_INDENT",Dp)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(s.comment?s.comment+=`
67
- `+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||Fk.containsNewline(f))&&n(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==r.indent&&n(c,"BAD_INDENT",Dp);i.atKey=!0;let S=h.end,y=f?e(i,f,h,n):t(i,S,d,null,h,n);i.schema.compat&&Hp.flowIndentCheck(r.indent,f,n),i.atKey=!1,qk.mapIncludes(i,s.items,y)&&n(S,"DUPLICATE_KEY","Map keys must be unique");let k=Op.resolveProps(p??[],{indicator:"map-value-ind",next:v,offset:y.range[2],onError:n,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=k.end,k.found){m&&(v?.type==="block-map"&&!k.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&h.start<k.found.offset-1024&&n(y.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let N=v?e(i,v,k,n):t(i,c,p,null,k,n);i.schema.compat&&Hp.flowIndentCheck(r.indent,v,n),c=N.range[2];let E=new $p.Pair(y,N);i.options.keepSourceTokens&&(E.srcToken=u),s.items.push(E)}else{m&&n(y.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),k.comment&&(y.comment?y.comment+=`
68
- `+k.comment:y.comment=k.comment);let N=new $p.Pair(y);i.options.keepSourceTokens&&(N.srcToken=u),s.items.push(N)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[r.offset,c,l??c],s}Bp.resolveBlockMap=Mk});var Fp=P(Vp=>{"use strict";var Wk=Ut(),zk=sn(),Jk=Kc();function Gk({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??Wk.YAMLSeq,s=new o(i.schema);i.atRoot&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let c=r.offset,l=null;for(let{start:u,value:d}of r.items){let f=zk.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||d)d?.type==="block-seq"?n(f.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(s.comment=f.comment);continue}let p=d?e(i,d,f,n):t(i,f.end,u,null,f,n);i.schema.compat&&Jk.flowIndentCheck(r.indent,d,n),c=p.range[2],s.items.push(p)}return s.range=[r.offset,c,l??c],s}Vp.resolveBlockSeq=Gk});var Ki=P(qp=>{"use strict";function Uk(e,t,i,r){let n="";if(e){let a=!1,o="";for(let s of e){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{i&&!a&&r(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";n?n+=o+u:n=u,o="";break}case"newline":n&&(o+=c),a=!0;break;default:r(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:n,offset:t}}qp.resolveEnd=Uk});var Jp=P(zp=>{"use strict";var Kk=F(),Yk=zt(),Mp=Gt(),Xk=Ut(),Qk=Ki(),Wp=sn(),Zk=Xa(),eS=Yc(),Xc="Block collections are not allowed within flow collections",Qc=e=>e&&(e.type==="block-map"||e.type==="block-seq");function tS({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=r.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Mp.YAMLMap:Xk.YAMLSeq),l=new c(i.schema);l.flow=!0;let u=i.atRoot;u&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let d=r.offset+r.start.source.length;for(let m=0;m<r.items.length;++m){let S=r.items[m],{start:y,key:k,sep:N,value:E}=S,b=Wp.resolveProps(y,{flow:s,indicator:"explicit-key-ind",next:k??N?.[0],offset:d,onError:n,parentIndent:r.indent,startOnNewline:!1});if(!b.found){if(!b.anchor&&!b.tag&&!N&&!E){m===0&&b.comma?n(b.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):m<r.items.length-1&&n(b.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),b.comment&&(l.comment?l.comment+=`
69
- `+b.comment:l.comment=b.comment),d=b.end;continue}!o&&i.options.strict&&Zk.containsNewline(k)&&n(k,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(m===0)b.comma&&n(b.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(b.comma||n(b.start,"MISSING_CHAR",`Missing , between ${s} items`),b.comment){let x="";e:for(let g of y)switch(g.type){case"comma":case"space":break;case"comment":x=g.source.substring(1);break e;default:break e}if(x){let g=l.items[l.items.length-1];Kk.isPair(g)&&(g=g.value??g.key),g.comment?g.comment+=`
65
+ `}};an.YAMLError=nn;an.YAMLParseError=Jc;an.YAMLWarning=Gc;an.prettifyError=Dk});var sn=P(Ap=>{"use strict";function Bk(e,{flow:t,indicator:i,next:r,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d="",f="",p=!1,v=!1,h=null,m=null,S=null,y=null,k=null,N=null,E=null;for(let g of e)switch(v&&(g.type!=="space"&&g.type!=="newline"&&g.type!=="comma"&&a(g.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),h&&(l&&g.type!=="comment"&&g.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),g.type){case"space":!t&&(i!=="doc-start"||r?.type!=="flow-collection")&&g.source.includes(" ")&&(h=g),u=!0;break;case"comment":{u||a(g,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let w=g.source.substring(1)||" ";d?d+=f+w:d=w,f="",l=!1;break}case"newline":l?d?d+=g.source:(!N||i!=="seq-item-ind")&&(c=!0):f+=g.source,l=!0,p=!0,(m||S)&&(y=g),u=!0;break;case"anchor":m&&a(g,"MULTIPLE_ANCHORS","A node can have at most one anchor"),g.source.endsWith(":")&&a(g.offset+g.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),m=g,E??(E=g.offset),l=!1,u=!1,v=!0;break;case"tag":{S&&a(g,"MULTIPLE_TAGS","A node can have at most one tag"),S=g,E??(E=g.offset),l=!1,u=!1,v=!0;break}case i:(m||S)&&a(g,"BAD_PROP_ORDER",`Anchors and tags must be after the ${g.source} indicator`),N&&a(g,"UNEXPECTED_TOKEN",`Unexpected ${g.source} in ${t??"collection"}`),N=g,l=i==="seq-item-ind"||i==="explicit-key-ind",u=!1;break;case"comma":if(t){k&&a(g,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),k=g,l=!1,u=!1;break}default:a(g,"UNEXPECTED_TOKEN",`Unexpected ${g.type} token`),l=!1,u=!1}let b=e[e.length-1],x=b?b.offset+b.source.length:n;return v&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&a(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||r?.type==="block-map"||r?.type==="block-seq")&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:k,found:N,spaceBefore:c,comment:d,hasNewline:p,anchor:m,tag:S,newlineAfterProp:y,end:x,start:E??x}}Ap.resolveProps=Bk});var Xa=P(_p=>{"use strict";function Uc(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
66
+ `))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let i of t.start)if(i.type==="newline")return!0;if(t.sep){for(let i of t.sep)if(i.type==="newline")return!0}if(Uc(t.key)||Uc(t.value))return!0}return!1;default:return!0}}_p.containsNewline=Uc});var Kc=P(Ip=>{"use strict";var Lk=Xa();function Vk(e,t,i){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&Lk.containsNewline(t)&&i(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Ip.flowIndentCheck=Vk});var Yc=P(jp=>{"use strict";var Tp=F();function Fk(e,t,i){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let n=typeof r=="function"?r:(a,o)=>a===o||Tp.isScalar(a)&&Tp.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,i))}jp.mapIncludes=Fk});var Lp=P(Bp=>{"use strict";var $p=zt(),qk=Gt(),Op=sn(),Mk=Xa(),Hp=Kc(),Wk=Yc(),Dp="All mapping items must start at the same column";function zk({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??qk.YAMLMap,s=new o(i.schema);i.atRoot&&(i.atRoot=!1);let c=r.offset,l=null;for(let u of r.items){let{start:d,key:f,sep:p,value:v}=u,h=Op.resolveProps(d,{indicator:"explicit-key-ind",next:f??p?.[0],offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0}),m=!h.found;if(m){if(f&&(f.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==r.indent&&n(c,"BAD_INDENT",Dp)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(s.comment?s.comment+=`
67
+ `+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||Mk.containsNewline(f))&&n(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==r.indent&&n(c,"BAD_INDENT",Dp);i.atKey=!0;let S=h.end,y=f?e(i,f,h,n):t(i,S,d,null,h,n);i.schema.compat&&Hp.flowIndentCheck(r.indent,f,n),i.atKey=!1,Wk.mapIncludes(i,s.items,y)&&n(S,"DUPLICATE_KEY","Map keys must be unique");let k=Op.resolveProps(p??[],{indicator:"map-value-ind",next:v,offset:y.range[2],onError:n,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=k.end,k.found){m&&(v?.type==="block-map"&&!k.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&h.start<k.found.offset-1024&&n(y.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let N=v?e(i,v,k,n):t(i,c,p,null,k,n);i.schema.compat&&Hp.flowIndentCheck(r.indent,v,n),c=N.range[2];let E=new $p.Pair(y,N);i.options.keepSourceTokens&&(E.srcToken=u),s.items.push(E)}else{m&&n(y.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),k.comment&&(y.comment?y.comment+=`
68
+ `+k.comment:y.comment=k.comment);let N=new $p.Pair(y);i.options.keepSourceTokens&&(N.srcToken=u),s.items.push(N)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[r.offset,c,l??c],s}Bp.resolveBlockMap=zk});var Fp=P(Vp=>{"use strict";var Jk=Ut(),Gk=sn(),Uk=Kc();function Kk({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??Jk.YAMLSeq,s=new o(i.schema);i.atRoot&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let c=r.offset,l=null;for(let{start:u,value:d}of r.items){let f=Gk.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||d)d?.type==="block-seq"?n(f.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(s.comment=f.comment);continue}let p=d?e(i,d,f,n):t(i,f.end,u,null,f,n);i.schema.compat&&Uk.flowIndentCheck(r.indent,d,n),c=p.range[2],s.items.push(p)}return s.range=[r.offset,c,l??c],s}Vp.resolveBlockSeq=Kk});var Ki=P(qp=>{"use strict";function Yk(e,t,i,r){let n="";if(e){let a=!1,o="";for(let s of e){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{i&&!a&&r(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";n?n+=o+u:n=u,o="";break}case"newline":n&&(o+=c),a=!0;break;default:r(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:n,offset:t}}qp.resolveEnd=Yk});var Jp=P(zp=>{"use strict";var Xk=F(),Qk=zt(),Mp=Gt(),Zk=Ut(),eS=Ki(),Wp=sn(),tS=Xa(),iS=Yc(),Xc="Block collections are not allowed within flow collections",Qc=e=>e&&(e.type==="block-map"||e.type==="block-seq");function rS({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=r.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Mp.YAMLMap:Zk.YAMLSeq),l=new c(i.schema);l.flow=!0;let u=i.atRoot;u&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let d=r.offset+r.start.source.length;for(let m=0;m<r.items.length;++m){let S=r.items[m],{start:y,key:k,sep:N,value:E}=S,b=Wp.resolveProps(y,{flow:s,indicator:"explicit-key-ind",next:k??N?.[0],offset:d,onError:n,parentIndent:r.indent,startOnNewline:!1});if(!b.found){if(!b.anchor&&!b.tag&&!N&&!E){m===0&&b.comma?n(b.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):m<r.items.length-1&&n(b.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),b.comment&&(l.comment?l.comment+=`
69
+ `+b.comment:l.comment=b.comment),d=b.end;continue}!o&&i.options.strict&&tS.containsNewline(k)&&n(k,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(m===0)b.comma&&n(b.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(b.comma||n(b.start,"MISSING_CHAR",`Missing , between ${s} items`),b.comment){let x="";e:for(let g of y)switch(g.type){case"comma":case"space":break;case"comment":x=g.source.substring(1);break e;default:break e}if(x){let g=l.items[l.items.length-1];Xk.isPair(g)&&(g=g.value??g.key),g.comment?g.comment+=`
70
70
  `+x:g.comment=x,b.comment=b.comment.substring(x.length+1)}}if(!o&&!N&&!b.found){let x=E?e(i,E,b,n):t(i,b.end,N,null,b,n);l.items.push(x),d=x.range[2],Qc(E)&&n(x.range,"BLOCK_IN_FLOW",Xc)}else{i.atKey=!0;let x=b.end,g=k?e(i,k,b,n):t(i,x,y,null,b,n);Qc(k)&&n(g.range,"BLOCK_IN_FLOW",Xc),i.atKey=!1;let w=Wp.resolveProps(N??[],{flow:s,indicator:"map-value-ind",next:E,offset:g.range[2],onError:n,parentIndent:r.indent,startOnNewline:!1});if(w.found){if(!o&&!b.found&&i.options.strict){if(N)for(let T of N){if(T===w.found)break;if(T.type==="newline"){n(T,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}b.start<w.found.offset-1024&&n(w.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else E&&("source"in E&&E.source?.[0]===":"?n(E,"MISSING_CHAR",`Missing space after : in ${s}`):n(w.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let C=E?e(i,E,w,n):w.found?t(i,w.end,N,null,w,n):null;C?Qc(E)&&n(C.range,"BLOCK_IN_FLOW",Xc):w.comment&&(g.comment?g.comment+=`
71
- `+w.comment:g.comment=w.comment);let $=new Yk.Pair(g,C);if(i.options.keepSourceTokens&&($.srcToken=S),o){let T=l;eS.mapIncludes(i,T.items,g)&&n(x,"DUPLICATE_KEY","Map keys must be unique"),T.items.push($)}else{let T=new Mp.YAMLMap(i.schema);T.flow=!0,T.items.push($);let pe=(C??g).range;T.range=[g.range[0],pe[1],pe[2]],l.items.push(T)}d=C?C.range[2]:w.end}}let f=o?"}":"]",[p,...v]=r.end,h=d;if(p?.source===f)h=p.offset+p.source.length;else{let m=s[0].toUpperCase()+s.substring(1),S=u?`${m} must end with a ${f}`:`${m} in block collection must be sufficiently indented and end with a ${f}`;n(d,u?"MISSING_CHAR":"BAD_INDENT",S),p&&p.source.length!==1&&v.unshift(p)}if(v.length>0){let m=Qk.resolveEnd(v,h,i.options.strict,n);m.comment&&(l.comment?l.comment+=`
72
- `+m.comment:l.comment=m.comment),l.range=[r.offset,h,m.offset]}else l.range=[r.offset,h,h];return l}zp.resolveFlowCollection=tS});var Up=P(Gp=>{"use strict";var iS=F(),rS=ne(),nS=Gt(),aS=Ut(),oS=Lp(),sS=Fp(),cS=Jp();function Zc(e,t,i,r,n,a){let o=i.type==="block-map"?oS.resolveBlockMap(e,t,i,r,a):i.type==="block-seq"?sS.resolveBlockSeq(e,t,i,r,a):cS.resolveFlowCollection(e,t,i,r,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function lS(e,t,i,r,n){let a=r.tag,o=a?t.directives.tagName(a.source,f=>n(a,"TAG_RESOLVE_FAILED",f)):null;if(i.type==="block-seq"){let{anchor:f,newlineAfterProp:p}=r,v=f&&a?f.offset>a.offset?f:a:f??a;v&&(!p||p.offset<v.offset)&&n(v,"MISSING_CHAR","Missing newline after block sequence props")}let s=i.type==="block-map"?"map":i.type==="block-seq"?"seq":i.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===nS.YAMLMap.tagName&&s==="map"||o===aS.YAMLSeq.tagName&&s==="seq")return Zc(e,t,i,n,o);let c=t.schema.tags.find(f=>f.tag===o&&f.collection===s);if(!c){let f=t.schema.knownTags[o];if(f?.collection===s)t.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?n(a,"BAD_COLLECTION_TYPE",`${f.tag} used for ${s} collection, but expects ${f.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Zc(e,t,i,n,o)}let l=Zc(e,t,i,n,o,c),u=c.resolve?.(l,f=>n(a,"TAG_RESOLVE_FAILED",f),t.options)??l,d=iS.isNode(u)?u:new rS.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}Gp.composeCollection=lS});var tl=P(Kp=>{"use strict";var el=ne();function uS(e,t,i){let r=t.offset,n=dS(t,e.options.strict,i);if(!n)return{value:"",type:null,comment:"",range:[r,r,r]};let a=n.mode===">"?el.Scalar.BLOCK_FOLDED:el.Scalar.BLOCK_LITERAL,o=t.source?fS(t.source):[],s=o.length;for(let h=o.length-1;h>=0;--h){let m=o[h][1];if(m===""||m==="\r")s=h;else break}if(s===0){let h=n.chomp==="+"&&o.length>0?`
71
+ `+w.comment:g.comment=w.comment);let $=new Qk.Pair(g,C);if(i.options.keepSourceTokens&&($.srcToken=S),o){let T=l;iS.mapIncludes(i,T.items,g)&&n(x,"DUPLICATE_KEY","Map keys must be unique"),T.items.push($)}else{let T=new Mp.YAMLMap(i.schema);T.flow=!0,T.items.push($);let pe=(C??g).range;T.range=[g.range[0],pe[1],pe[2]],l.items.push(T)}d=C?C.range[2]:w.end}}let f=o?"}":"]",[p,...v]=r.end,h=d;if(p?.source===f)h=p.offset+p.source.length;else{let m=s[0].toUpperCase()+s.substring(1),S=u?`${m} must end with a ${f}`:`${m} in block collection must be sufficiently indented and end with a ${f}`;n(d,u?"MISSING_CHAR":"BAD_INDENT",S),p&&p.source.length!==1&&v.unshift(p)}if(v.length>0){let m=eS.resolveEnd(v,h,i.options.strict,n);m.comment&&(l.comment?l.comment+=`
72
+ `+m.comment:l.comment=m.comment),l.range=[r.offset,h,m.offset]}else l.range=[r.offset,h,h];return l}zp.resolveFlowCollection=rS});var Up=P(Gp=>{"use strict";var nS=F(),aS=ne(),oS=Gt(),sS=Ut(),cS=Lp(),lS=Fp(),uS=Jp();function Zc(e,t,i,r,n,a){let o=i.type==="block-map"?cS.resolveBlockMap(e,t,i,r,a):i.type==="block-seq"?lS.resolveBlockSeq(e,t,i,r,a):uS.resolveFlowCollection(e,t,i,r,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function dS(e,t,i,r,n){let a=r.tag,o=a?t.directives.tagName(a.source,f=>n(a,"TAG_RESOLVE_FAILED",f)):null;if(i.type==="block-seq"){let{anchor:f,newlineAfterProp:p}=r,v=f&&a?f.offset>a.offset?f:a:f??a;v&&(!p||p.offset<v.offset)&&n(v,"MISSING_CHAR","Missing newline after block sequence props")}let s=i.type==="block-map"?"map":i.type==="block-seq"?"seq":i.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===oS.YAMLMap.tagName&&s==="map"||o===sS.YAMLSeq.tagName&&s==="seq")return Zc(e,t,i,n,o);let c=t.schema.tags.find(f=>f.tag===o&&f.collection===s);if(!c){let f=t.schema.knownTags[o];if(f?.collection===s)t.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?n(a,"BAD_COLLECTION_TYPE",`${f.tag} used for ${s} collection, but expects ${f.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Zc(e,t,i,n,o)}let l=Zc(e,t,i,n,o,c),u=c.resolve?.(l,f=>n(a,"TAG_RESOLVE_FAILED",f),t.options)??l,d=nS.isNode(u)?u:new aS.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}Gp.composeCollection=dS});var tl=P(Kp=>{"use strict";var el=ne();function fS(e,t,i){let r=t.offset,n=pS(t,e.options.strict,i);if(!n)return{value:"",type:null,comment:"",range:[r,r,r]};let a=n.mode===">"?el.Scalar.BLOCK_FOLDED:el.Scalar.BLOCK_LITERAL,o=t.source?hS(t.source):[],s=o.length;for(let h=o.length-1;h>=0;--h){let m=o[h][1];if(m===""||m==="\r")s=h;else break}if(s===0){let h=n.chomp==="+"&&o.length>0?`
73
73
  `.repeat(Math.max(1,o.length-1)):"",m=r+n.length;return t.source&&(m+=t.source.length),{value:h,type:a,comment:n.comment,range:[r,m,m]}}let c=t.indent+n.indent,l=t.offset+n.length,u=0;for(let h=0;h<s;++h){let[m,S]=o[h];if(S===""||S==="\r")n.indent===0&&m.length>c&&(c=m.length);else{m.length<c&&i(l+m.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(c=m.length),u=h,c===0&&!e.atRoot&&i(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=m.length+S.length+1}for(let h=o.length-1;h>=s;--h)o[h][0].length>c&&(s=h+1);let d="",f="",p=!1;for(let h=0;h<u;++h)d+=o[h][0].slice(c)+`
74
74
  `;for(let h=u;h<s;++h){let[m,S]=o[h];l+=m.length+S.length+1;let y=S[S.length-1]==="\r";if(y&&(S=S.slice(0,-1)),S&&m.length<c){let N=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;i(l-S.length-(y?2:1),"BAD_INDENT",N),m=""}a===el.Scalar.BLOCK_LITERAL?(d+=f+m.slice(c)+S,f=`
75
75
  `):m.length>c||S[0]===" "?(f===" "?f=`
@@ -84,41 +84,41 @@ ${l}
84
84
  `+o[h][0].slice(c);d[d.length-1]!==`
85
85
  `&&(d+=`
86
86
  `);break;default:d+=`
87
- `}let v=r+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[r,v,v]}}function dS({offset:e,props:t},i,r){if(t[0].type!=="block-scalar-header")return r(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",c=-1;for(let f=1;f<n.length;++f){let p=n[f];if(!s&&(p==="-"||p==="+"))s=p;else{let v=Number(p);!o&&v?o=v:c===-1&&(c=e+f)}}c!==-1&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,u="",d=n.length;for(let f=1;f<t.length;++f){let p=t[f];switch(p.type){case"space":l=!0;case"newline":d+=p.source.length;break;case"comment":i&&!l&&r(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=p.source.length,u=p.source.substring(1);break;case"error":r(p,"UNEXPECTED_TOKEN",p.message),d+=p.source.length;break;default:{let v=`Unexpected token in block scalar header: ${p.type}`;r(p,"UNEXPECTED_TOKEN",v);let h=p.source;h&&typeof h=="string"&&(d+=h.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function fS(e){let t=e.split(/\n( *)/),i=t[0],r=i.match(/^( *)/),a=[r?.[1]?[r[1],i.slice(r[1].length)]:["",i]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}Kp.resolveBlockScalar=uS});var rl=P(Xp=>{"use strict";var il=ne(),pS=Ki();function hS(e,t,i){let{offset:r,type:n,source:a,end:o}=e,s,c,l=(f,p,v)=>i(r+f,p,v);switch(n){case"scalar":s=il.Scalar.PLAIN,c=mS(a,l);break;case"single-quoted-scalar":s=il.Scalar.QUOTE_SINGLE,c=vS(a,l);break;case"double-quoted-scalar":s=il.Scalar.QUOTE_DOUBLE,c=gS(a,l);break;default:return i(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[r,r+a.length,r+a.length]}}let u=r+a.length,d=pS.resolveEnd(o,u,t,i);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function mS(e,t){let i="";switch(e[0]){case" ":i="a tab character";break;case",":i="flow indicator character ,";break;case"%":i="directive indicator character %";break;case"|":case">":{i=`block scalar indicator ${e[0]}`;break}case"@":case"`":{i=`reserved character ${e[0]}`;break}}return i&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${i}`),Yp(e)}function vS(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Yp(e.slice(1,-1)).replace(/''/g,"'")}function Yp(e){let t,i;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
87
+ `}let v=r+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[r,v,v]}}function pS({offset:e,props:t},i,r){if(t[0].type!=="block-scalar-header")return r(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",c=-1;for(let f=1;f<n.length;++f){let p=n[f];if(!s&&(p==="-"||p==="+"))s=p;else{let v=Number(p);!o&&v?o=v:c===-1&&(c=e+f)}}c!==-1&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,u="",d=n.length;for(let f=1;f<t.length;++f){let p=t[f];switch(p.type){case"space":l=!0;case"newline":d+=p.source.length;break;case"comment":i&&!l&&r(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=p.source.length,u=p.source.substring(1);break;case"error":r(p,"UNEXPECTED_TOKEN",p.message),d+=p.source.length;break;default:{let v=`Unexpected token in block scalar header: ${p.type}`;r(p,"UNEXPECTED_TOKEN",v);let h=p.source;h&&typeof h=="string"&&(d+=h.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function hS(e){let t=e.split(/\n( *)/),i=t[0],r=i.match(/^( *)/),a=[r?.[1]?[r[1],i.slice(r[1].length)]:["",i]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}Kp.resolveBlockScalar=fS});var rl=P(Xp=>{"use strict";var il=ne(),mS=Ki();function vS(e,t,i){let{offset:r,type:n,source:a,end:o}=e,s,c,l=(f,p,v)=>i(r+f,p,v);switch(n){case"scalar":s=il.Scalar.PLAIN,c=gS(a,l);break;case"single-quoted-scalar":s=il.Scalar.QUOTE_SINGLE,c=wS(a,l);break;case"double-quoted-scalar":s=il.Scalar.QUOTE_DOUBLE,c=yS(a,l);break;default:return i(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[r,r+a.length,r+a.length]}}let u=r+a.length,d=mS.resolveEnd(o,u,t,i);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function gS(e,t){let i="";switch(e[0]){case" ":i="a tab character";break;case",":i="flow indicator character ,";break;case"%":i="directive indicator character %";break;case"|":case">":{i=`block scalar indicator ${e[0]}`;break}case"@":case"`":{i=`reserved character ${e[0]}`;break}}return i&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${i}`),Yp(e)}function wS(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Yp(e.slice(1,-1)).replace(/''/g,"'")}function Yp(e){let t,i;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
88
88
  `,"sy"),i=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
89
89
  `,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,i=/[ \t]*(.*?)[ \t]*\r?\n/sy}let r=t.exec(e);if(!r)return e;let n=r[1],a=" ",o=t.lastIndex;for(i.lastIndex=o;r=i.exec(e);)r[1]===""?a===`
90
90
  `?n+=a:a=`
91
- `:(n+=a+r[1],a=" "),o=i.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,r=s.exec(e),n+a+(r?.[1]??"")}function gS(e,t){let i="";for(let r=1;r<e.length-1;++r){let n=e[r];if(!(n==="\r"&&e[r+1]===`
91
+ `:(n+=a+r[1],a=" "),o=i.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,r=s.exec(e),n+a+(r?.[1]??"")}function yS(e,t){let i="";for(let r=1;r<e.length-1;++r){let n=e[r];if(!(n==="\r"&&e[r+1]===`
92
92
  `))if(n===`
93
- `){let{fold:a,offset:o}=wS(e,r);i+=a,r=o}else if(n==="\\"){let a=e[++r],o=yS[a];if(o)i+=o;else if(a===`
93
+ `){let{fold:a,offset:o}=NS(e,r);i+=a,r=o}else if(n==="\\"){let a=e[++r],o=bS[a];if(o)i+=o;else if(a===`
94
94
  `)for(a=e[r+1];a===" "||a===" ";)a=e[++r+1];else if(a==="\r"&&e[r+1]===`
95
- `)for(a=e[++r+1];a===" "||a===" ";)a=e[++r+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;i+=NS(e,r+1,s,t),r+=s}else{let s=e.substr(r-1,2);t(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),i+=s}}else if(n===" "||n===" "){let a=r,o=e[r+1];for(;o===" "||o===" ";)o=e[++r+1];o!==`
95
+ `)for(a=e[++r+1];a===" "||a===" ";)a=e[++r+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;i+=kS(e,r+1,s,t),r+=s}else{let s=e.substr(r-1,2);t(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),i+=s}}else if(n===" "||n===" "){let a=r,o=e[r+1];for(;o===" "||o===" ";)o=e[++r+1];o!==`
96
96
  `&&!(o==="\r"&&e[r+2]===`
97
- `)&&(i+=r>a?e.slice(a,r+1):n)}else i+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),i}function wS(e,t){let i="",r=e[t+1];for(;(r===" "||r===" "||r===`
97
+ `)&&(i+=r>a?e.slice(a,r+1):n)}else i+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),i}function NS(e,t){let i="",r=e[t+1];for(;(r===" "||r===" "||r===`
98
98
  `||r==="\r")&&!(r==="\r"&&e[t+2]!==`
99
99
  `);)r===`
100
100
  `&&(i+=`
101
- `),t+=1,r=e[t+1];return i||(i=" "),{fold:i,offset:t}}var yS={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
102
- `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function NS(e,t,i,r){let n=e.substr(t,i),o=n.length===i&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,i+2);return r(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}Xp.resolveFlowScalar=hS});var eh=P(Zp=>{"use strict";var ki=F(),Qp=ne(),bS=tl(),kS=rl();function SS(e,t,i,r){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?bS.resolveBlockScalar(e,t,r):kS.resolveFlowScalar(t,e.options.strict,r),c=i?e.directives.tagName(i.source,d=>r(i,"TAG_RESOLVE_FAILED",d)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[ki.SCALAR]:c?l=ES(e.schema,n,c,i,r):t.type==="scalar"?l=CS(e,n,t,r):l=e.schema[ki.SCALAR];let u;try{let d=l.resolve(n,f=>r(i??t,"TAG_RESOLVE_FAILED",f),e.options);u=ki.isScalar(d)?d:new Qp.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);r(i??t,"TAG_RESOLVE_FAILED",f),u=new Qp.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 ES(e,t,i,r,n){if(i==="!")return e[ki.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===i)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(t))return s;let o=e.knownTags[i];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,i!=="tag:yaml.org,2002:str"),e[ki.SCALAR])}function CS({atKey:e,directives:t,schema:i},r,n,a){let o=i.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(r))||i[ki.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(r))??i[ki.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}Zp.composeScalar=SS});var ih=P(th=>{"use strict";function xS(e,t,i){if(t){i??(i=t.length);for(let r=i-1;r>=0;--r){let n=t[r];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}for(n=t[++r];n?.type==="space";)e+=n.source.length,n=t[++r];break}}return e}th.emptyScalarPosition=xS});var ah=P(al=>{"use strict";var PS=Vr(),RS=F(),AS=Up(),rh=eh(),_S=Ki(),IS=ih(),TS={composeNode:nh,composeEmptyNode:nl};function nh(e,t,i,r){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=i,l,u=!0;switch(t.type){case"alias":l=jS(e,t,r),(s||c)&&r(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=rh.composeScalar(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=AS.composeCollection(TS,e,t,i,r),s&&(l.anchor=s.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);r(t,"RESOURCE_EXHAUSTION",f)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;r(t,"UNEXPECTED_TOKEN",d),u=!1}}return l??(l=nl(e,t.offset,void 0,null,i,r)),s&&l.anchor===""&&r(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&e.options.stringKeys&&(!RS.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&r(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function nl(e,t,i,r,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:IS.emptyScalarPosition(t,i,r),indent:-1,source:""},d=rh.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 jS({options:e},{offset:t,source:i,end:r},n){let a=new PS.Alias(i.substring(1));a.source===""&&n(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(t+i.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+i.length,s=_S.resolveEnd(r,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}al.composeEmptyNode=nl;al.composeNode=nh});var ch=P(sh=>{"use strict";var $S=rn(),oh=ah(),OS=Ki(),HS=sn();function DS(e,t,{offset:i,start:r,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new $S.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=HS.resolveProps(r,{indicator:"doc-start",next:n??a?.[0],offset:i,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?oh.composeNode(l,n,u,o):oh.composeEmptyNode(l,u.end,r,null,u,o);let d=c.contents.range[2],f=OS.resolveEnd(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[i,d,f.offset],c}sh.composeDoc=DS});var sl=P(dh=>{"use strict";var BS=aa("process"),LS=Js(),VS=rn(),cn=on(),lh=F(),FS=ch(),qS=Ki();function ln(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:i}=e;return[t,t+(typeof i=="string"?i.length:1)]}function uh(e){let t="",i=!1,r=!1;for(let n=0;n<e.length;++n){let a=e[n];switch(a[0]){case"#":t+=(t===""?"":r?`
101
+ `),t+=1,r=e[t+1];return i||(i=" "),{fold:i,offset:t}}var bS={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
102
+ `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function kS(e,t,i,r){let n=e.substr(t,i),o=n.length===i&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,i+2);return r(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}Xp.resolveFlowScalar=vS});var eh=P(Zp=>{"use strict";var ki=F(),Qp=ne(),SS=tl(),ES=rl();function CS(e,t,i,r){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?SS.resolveBlockScalar(e,t,r):ES.resolveFlowScalar(t,e.options.strict,r),c=i?e.directives.tagName(i.source,d=>r(i,"TAG_RESOLVE_FAILED",d)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[ki.SCALAR]:c?l=xS(e.schema,n,c,i,r):t.type==="scalar"?l=PS(e,n,t,r):l=e.schema[ki.SCALAR];let u;try{let d=l.resolve(n,f=>r(i??t,"TAG_RESOLVE_FAILED",f),e.options);u=ki.isScalar(d)?d:new Qp.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);r(i??t,"TAG_RESOLVE_FAILED",f),u=new Qp.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 xS(e,t,i,r,n){if(i==="!")return e[ki.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===i)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(t))return s;let o=e.knownTags[i];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,i!=="tag:yaml.org,2002:str"),e[ki.SCALAR])}function PS({atKey:e,directives:t,schema:i},r,n,a){let o=i.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(r))||i[ki.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(r))??i[ki.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}Zp.composeScalar=CS});var ih=P(th=>{"use strict";function RS(e,t,i){if(t){i??(i=t.length);for(let r=i-1;r>=0;--r){let n=t[r];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}for(n=t[++r];n?.type==="space";)e+=n.source.length,n=t[++r];break}}return e}th.emptyScalarPosition=RS});var ah=P(al=>{"use strict";var AS=Vr(),_S=F(),IS=Up(),rh=eh(),TS=Ki(),jS=ih(),$S={composeNode:nh,composeEmptyNode:nl};function nh(e,t,i,r){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=i,l,u=!0;switch(t.type){case"alias":l=OS(e,t,r),(s||c)&&r(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=rh.composeScalar(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=IS.composeCollection($S,e,t,i,r),s&&(l.anchor=s.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);r(t,"RESOURCE_EXHAUSTION",f)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;r(t,"UNEXPECTED_TOKEN",d),u=!1}}return l??(l=nl(e,t.offset,void 0,null,i,r)),s&&l.anchor===""&&r(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&e.options.stringKeys&&(!_S.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&r(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function nl(e,t,i,r,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:jS.emptyScalarPosition(t,i,r),indent:-1,source:""},d=rh.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 OS({options:e},{offset:t,source:i,end:r},n){let a=new AS.Alias(i.substring(1));a.source===""&&n(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(t+i.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+i.length,s=TS.resolveEnd(r,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}al.composeEmptyNode=nl;al.composeNode=nh});var ch=P(sh=>{"use strict";var HS=rn(),oh=ah(),DS=Ki(),BS=sn();function LS(e,t,{offset:i,start:r,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new HS.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=BS.resolveProps(r,{indicator:"doc-start",next:n??a?.[0],offset:i,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?oh.composeNode(l,n,u,o):oh.composeEmptyNode(l,u.end,r,null,u,o);let d=c.contents.range[2],f=DS.resolveEnd(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[i,d,f.offset],c}sh.composeDoc=LS});var sl=P(dh=>{"use strict";var VS=aa("process"),FS=Js(),qS=rn(),cn=on(),lh=F(),MS=ch(),WS=Ki();function ln(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:i}=e;return[t,t+(typeof i=="string"?i.length:1)]}function uh(e){let t="",i=!1,r=!1;for(let n=0;n<e.length;++n){let a=e[n];switch(a[0]){case"#":t+=(t===""?"":r?`
103
103
 
104
104
  `:`
105
- `)+(a.substring(1)||" "),i=!0,r=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),i=!1;break;default:i||(r=!0),i=!1}}return{comment:t,afterEmptyLine:r}}var ol=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,r,n,a)=>{let o=ln(i);a?this.warnings.push(new cn.YAMLWarning(o,r,n)):this.errors.push(new cn.YAMLParseError(o,r,n))},this.directives=new LS.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,i){let{comment:r,afterEmptyLine:n}=uh(this.prelude);if(r){let a=t.contents;if(i)t.comment=t.comment?`${t.comment}
105
+ `)+(a.substring(1)||" "),i=!0,r=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),i=!1;break;default:i||(r=!0),i=!1}}return{comment:t,afterEmptyLine:r}}var ol=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,r,n,a)=>{let o=ln(i);a?this.warnings.push(new cn.YAMLWarning(o,r,n)):this.errors.push(new cn.YAMLParseError(o,r,n))},this.directives=new FS.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,i){let{comment:r,afterEmptyLine:n}=uh(this.prelude);if(r){let a=t.contents;if(i)t.comment=t.comment?`${t.comment}
106
106
  ${r}`:r;else if(n||t.directives.docStart||!a)t.commentBefore=r;else if(lh.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];lh.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${r}
107
107
  ${s}`:r}else{let o=a.commentBefore;a.commentBefore=o?`${r}
108
- ${o}`:r}}if(i){for(let a=0;a<this.errors.length;++a)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:uh(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,i=!1,r=-1){for(let n of t)yield*this.next(n);yield*this.end(i,r)}*next(t){switch(BS.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(i,r,n)=>{let a=ln(t);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",r,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let i=FS.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!i.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(i,!1),this.doc&&(yield this.doc),this.doc=i,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let i=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,r=new cn.YAMLParseError(ln(t),"UNEXPECTED_TOKEN",i);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){let r="Unexpected doc-end without preceding document";this.errors.push(new cn.YAMLParseError(ln(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let i=qS.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),i.comment){let r=this.doc.comment;this.doc.comment=r?`${r}
109
- ${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new cn.YAMLParseError(ln(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,i=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let r=Object.assign({_directives:this.directives},this.options),n=new VS.Document(void 0,r);this.atDirectives&&this.onError(i,"MISSING_CHAR","Missing directives-end indicator line"),n.range=[0,i,i],this.decorate(n,!1),yield n}}};dh.Composer=ol});var hh=P(Qa=>{"use strict";var MS=tl(),WS=rl(),zS=on(),fh=zr();function JS(e,t=!0,i){if(e){let r=(n,a,o)=>{let s=typeof n=="number"?n:Array.isArray(n)?n[0]:n.offset;if(i)i(s,a,o);else throw new zS.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return WS.resolveFlowScalar(e,t,r);case"block-scalar":return MS.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function GS(e,t){let{implicitKey:i=!1,indent:r,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=fh.stringifyString({type:o,value:e},{implicitKey:i,indent:r>0?" ".repeat(r):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:r,source:`
108
+ ${o}`:r}}if(i){for(let a=0;a<this.errors.length;++a)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:uh(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,i=!1,r=-1){for(let n of t)yield*this.next(n);yield*this.end(i,r)}*next(t){switch(VS.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(i,r,n)=>{let a=ln(t);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",r,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let i=MS.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!i.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(i,!1),this.doc&&(yield this.doc),this.doc=i,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let i=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,r=new cn.YAMLParseError(ln(t),"UNEXPECTED_TOKEN",i);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){let r="Unexpected doc-end without preceding document";this.errors.push(new cn.YAMLParseError(ln(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let i=WS.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),i.comment){let r=this.doc.comment;this.doc.comment=r?`${r}
109
+ ${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new cn.YAMLParseError(ln(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,i=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let r=Object.assign({_directives:this.directives},this.options),n=new qS.Document(void 0,r);this.atDirectives&&this.onError(i,"MISSING_CHAR","Missing directives-end indicator line"),n.range=[0,i,i],this.decorate(n,!1),yield n}}};dh.Composer=ol});var hh=P(Qa=>{"use strict";var zS=tl(),JS=rl(),GS=on(),fh=zr();function US(e,t=!0,i){if(e){let r=(n,a,o)=>{let s=typeof n=="number"?n:Array.isArray(n)?n[0]:n.offset;if(i)i(s,a,o);else throw new GS.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return JS.resolveFlowScalar(e,t,r);case"block-scalar":return zS.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function KS(e,t){let{implicitKey:i=!1,indent:r,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=fh.stringifyString({type:o,value:e},{implicitKey:i,indent:r>0?" ".repeat(r):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:r,source:`
110
110
  `}];switch(s[0]){case"|":case">":{let l=s.indexOf(`
111
111
  `),u=s.substring(0,l),d=s.substring(l+1)+`
112
112
  `,f=[{type:"block-scalar-header",offset:a,indent:r,source:u}];return ph(f,c)||f.push({type:"newline",offset:-1,indent:r,source:`
113
- `}),{type:"block-scalar",offset:a,indent:r,props:f,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:r,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:r,source:s,end:c};default:return{type:"scalar",offset:a,indent:r,source:s,end:c}}}function US(e,t,i={}){let{afterKey:r=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=i,s="indent"in e?e.indent:null;if(r&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=fh.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">":KS(e,c);break;case'"':cl(e,c,"double-quoted-scalar");break;case"'":cl(e,c,"single-quoted-scalar");break;default:cl(e,c,"scalar")}}function KS(e,t){let i=t.indexOf(`
113
+ `}),{type:"block-scalar",offset:a,indent:r,props:f,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:r,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:r,source:s,end:c};default:return{type:"scalar",offset:a,indent:r,source:s,end:c}}}function YS(e,t,i={}){let{afterKey:r=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=i,s="indent"in e?e.indent:null;if(r&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=fh.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">":XS(e,c);break;case'"':cl(e,c,"double-quoted-scalar");break;case"'":cl(e,c,"single-quoted-scalar");break;default:cl(e,c,"scalar")}}function XS(e,t){let i=t.indexOf(`
114
114
  `),r=t.substring(0,i),n=t.substring(i+1)+`
115
115
  `;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=r,e.source=n}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:r}];ph(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
116
116
  `});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function ph(e,t){if(t)for(let i of t)switch(i.type){case"space":case"comment":e.push(i);break;case"newline":return e.push(i),!0}return!1}function cl(e,t,i){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=i,e.source=t;break;case"block-scalar":{let r=e.props.slice(1),n=t.length;e.props[0].type==="block-scalar-header"&&(n-=e.props[0].source.length);for(let a of r)a.offset+=n;delete e.props,Object.assign(e,{type:i,source:t,end:r});break}case"block-map":case"block-seq":{let n={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
117
- `};delete e.items,Object.assign(e,{type:i,source:t,end:[n]});break}default:{let r="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:i,indent:r,source:t,end:n})}}}Qa.createScalarToken=GS;Qa.resolveAsScalar=JS;Qa.setScalarValue=US});var vh=P(mh=>{"use strict";var YS=e=>"type"in e?eo(e):Za(e);function eo(e){switch(e.type){case"block-scalar":{let t="";for(let i of e.props)t+=eo(i);return t+e.source}case"block-map":case"block-seq":{let t="";for(let i of e.items)t+=Za(i);return t}case"flow-collection":{let t=e.start.source;for(let i of e.items)t+=Za(i);for(let i of e.end)t+=i.source;return t}case"document":{let t=Za(e);if(e.end)for(let i of e.end)t+=i.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let i of e.end)t+=i.source;return t}}}function Za({start:e,key:t,sep:i,value:r}){let n="";for(let a of e)n+=a.source;if(t&&(n+=eo(t)),i)for(let a of i)n+=a.source;return r&&(n+=eo(r)),n}mh.stringify=YS});var Nh=P(yh=>{"use strict";var ll=Symbol("break visit"),XS=Symbol("skip children"),gh=Symbol("remove item");function Si(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),wh(Object.freeze([]),e,t)}Si.BREAK=ll;Si.SKIP=XS;Si.REMOVE=gh;Si.itemAtPath=(e,t)=>{let i=e;for(let[r,n]of t){let a=i?.[r];if(a&&"items"in a)i=a.items[n];else return}return i};Si.parentCollection=(e,t)=>{let i=Si.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],n=i?.[r];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function wh(e,t,i){let r=i(t,e);if(typeof r=="symbol")return r;for(let n of["key","value"]){let a=t[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=wh(Object.freeze(e.concat([[n,o]])),a.items[o],i);if(typeof s=="number")o=s-1;else{if(s===ll)return ll;s===gh&&(a.items.splice(o,1),o-=1)}}typeof r=="function"&&n==="key"&&(r=r(t,e))}}return typeof r=="function"?r(t,e):r}yh.visit=Si});var to=P(Se=>{"use strict";var ul=hh(),QS=vh(),ZS=Nh(),dl="\uFEFF",fl="",pl="",hl="",eE=e=>!!e&&"items"in e,tE=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function iE(e){switch(e){case dl:return"<BOM>";case fl:return"<DOC>";case pl:return"<FLOW_END>";case hl:return"<SCALAR>";default:return JSON.stringify(e)}}function rE(e){switch(e){case dl:return"byte-order-mark";case fl:return"doc-mode";case pl:return"flow-error-end";case hl:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
117
+ `};delete e.items,Object.assign(e,{type:i,source:t,end:[n]});break}default:{let r="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:i,indent:r,source:t,end:n})}}}Qa.createScalarToken=KS;Qa.resolveAsScalar=US;Qa.setScalarValue=YS});var vh=P(mh=>{"use strict";var QS=e=>"type"in e?eo(e):Za(e);function eo(e){switch(e.type){case"block-scalar":{let t="";for(let i of e.props)t+=eo(i);return t+e.source}case"block-map":case"block-seq":{let t="";for(let i of e.items)t+=Za(i);return t}case"flow-collection":{let t=e.start.source;for(let i of e.items)t+=Za(i);for(let i of e.end)t+=i.source;return t}case"document":{let t=Za(e);if(e.end)for(let i of e.end)t+=i.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let i of e.end)t+=i.source;return t}}}function Za({start:e,key:t,sep:i,value:r}){let n="";for(let a of e)n+=a.source;if(t&&(n+=eo(t)),i)for(let a of i)n+=a.source;return r&&(n+=eo(r)),n}mh.stringify=QS});var Nh=P(yh=>{"use strict";var ll=Symbol("break visit"),ZS=Symbol("skip children"),gh=Symbol("remove item");function Si(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),wh(Object.freeze([]),e,t)}Si.BREAK=ll;Si.SKIP=ZS;Si.REMOVE=gh;Si.itemAtPath=(e,t)=>{let i=e;for(let[r,n]of t){let a=i?.[r];if(a&&"items"in a)i=a.items[n];else return}return i};Si.parentCollection=(e,t)=>{let i=Si.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],n=i?.[r];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function wh(e,t,i){let r=i(t,e);if(typeof r=="symbol")return r;for(let n of["key","value"]){let a=t[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=wh(Object.freeze(e.concat([[n,o]])),a.items[o],i);if(typeof s=="number")o=s-1;else{if(s===ll)return ll;s===gh&&(a.items.splice(o,1),o-=1)}}typeof r=="function"&&n==="key"&&(r=r(t,e))}}return typeof r=="function"?r(t,e):r}yh.visit=Si});var to=P(Se=>{"use strict";var ul=hh(),eE=vh(),tE=Nh(),dl="\uFEFF",fl="",pl="",hl="",iE=e=>!!e&&"items"in e,rE=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function nE(e){switch(e){case dl:return"<BOM>";case fl:return"<DOC>";case pl:return"<FLOW_END>";case hl:return"<SCALAR>";default:return JSON.stringify(e)}}function aE(e){switch(e){case dl:return"byte-order-mark";case fl:return"doc-mode";case pl:return"flow-error-end";case hl:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
118
118
  `:case`\r
119
- `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}Se.createScalarToken=ul.createScalarToken;Se.resolveAsScalar=ul.resolveAsScalar;Se.setScalarValue=ul.setScalarValue;Se.stringify=QS.stringify;Se.visit=ZS.visit;Se.BOM=dl;Se.DOCUMENT=fl;Se.FLOW_END=pl;Se.SCALAR=hl;Se.isCollection=eE;Se.isScalar=tE;Se.prettyToken=iE;Se.tokenType=rE});var gl=P(kh=>{"use strict";var un=to();function Ke(e){switch(e){case void 0:case" ":case`
120
- `:case"\r":case" ":return!0;default:return!1}}var bh=new Set("0123456789ABCDEFabcdef"),nE=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),io=new Set(",[]{}"),aE=new Set(` ,[]{}
121
- \r `),ml=e=>!e||aE.has(e),vl=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,i=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!i;let r=this.next??"stream";for(;r&&(i||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let t=this.pos,i=this.buffer[t];for(;i===" "||i===" ";)i=this.buffer[++t];return!i||i==="#"||i===`
119
+ `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}Se.createScalarToken=ul.createScalarToken;Se.resolveAsScalar=ul.resolveAsScalar;Se.setScalarValue=ul.setScalarValue;Se.stringify=eE.stringify;Se.visit=tE.visit;Se.BOM=dl;Se.DOCUMENT=fl;Se.FLOW_END=pl;Se.SCALAR=hl;Se.isCollection=iE;Se.isScalar=rE;Se.prettyToken=nE;Se.tokenType=aE});var gl=P(kh=>{"use strict";var un=to();function Ke(e){switch(e){case void 0:case" ":case`
120
+ `:case"\r":case" ":return!0;default:return!1}}var bh=new Set("0123456789ABCDEFabcdef"),oE=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),io=new Set(",[]{}"),sE=new Set(` ,[]{}
121
+ \r `),ml=e=>!e||sE.has(e),vl=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,i=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!i;let r=this.next??"stream";for(;r&&(i||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let t=this.pos,i=this.buffer[t];for(;i===" "||i===" ";)i=this.buffer[++t];return!i||i==="#"||i===`
122
122
  `?!0:i==="\r"?this.buffer[t+1]===`
123
123
  `:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let i=this.buffer[t];if(this.indentNext>0){let r=0;for(;i===" ";)i=this.buffer[++r+t];if(i==="\r"){let n=this.buffer[r+t+1];if(n===`
124
124
  `||!n&&!this.atEnd)return t+r+1}return i===`
@@ -133,62 +133,62 @@ ${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.pus
133
133
  `&&a>=this.pos&&a+1+i>s)t=a;else break}while(!0);return yield un.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,i=this.pos-1,r=this.pos-1,n;for(;n=this.buffer[++r];)if(n===":"){let a=this.buffer[r+1];if(Ke(a)||t&&io.has(a))break;i=r}else if(Ke(n)){let a=this.buffer[r+1];if(n==="\r"&&(a===`
134
134
  `?(r+=1,n=`
135
135
  `,a=this.buffer[r+1]):i=r),a==="#"||t&&io.has(a))break;if(n===`
136
- `){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(t&&io.has(n))break;i=r}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield un.SCALAR,yield*this.pushToIndex(i+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,i){let r=this.buffer.slice(this.pos,t);return r?(yield r,this.pos+=r.length,r.length):(i&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(ml),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,r=this.charAt(1);if(Ke(r)||i&&io.has(r)){i?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,i=this.buffer[t];for(;!Ke(i)&&i!==">";)i=this.buffer[++t];return yield*this.pushToIndex(i===">"?t+1:t,!1)}else{let t=this.pos+1,i=this.buffer[t];for(;i;)if(nE.has(i))i=this.buffer[++t];else if(i==="%"&&bh.has(this.buffer[t+1])&&bh.has(this.buffer[t+2]))i=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
136
+ `){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(t&&io.has(n))break;i=r}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield un.SCALAR,yield*this.pushToIndex(i+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,i){let r=this.buffer.slice(this.pos,t);return r?(yield r,this.pos+=r.length,r.length):(i&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(ml),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,r=this.charAt(1);if(Ke(r)||i&&io.has(r)){i?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,i=this.buffer[t];for(;!Ke(i)&&i!==">";)i=this.buffer[++t];return yield*this.pushToIndex(i===">"?t+1:t,!1)}else{let t=this.pos+1,i=this.buffer[t];for(;i;)if(oE.has(i))i=this.buffer[++t];else if(i==="%"&&bh.has(this.buffer[t+1])&&bh.has(this.buffer[t+2]))i=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
137
137
  `?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
138
- `?yield*this.pushCount(2):0}*pushSpaces(t){let i=this.pos-1,r;do r=this.buffer[++i];while(r===" "||t&&r===" ");let n=i-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=i),n}*pushUntil(t){let i=this.pos,r=this.buffer[i];for(;!t(r);)r=this.buffer[++i];return yield*this.pushToIndex(i,!1)}};kh.Lexer=vl});var yl=P(Sh=>{"use strict";var wl=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let i=0,r=this.lineStarts.length;for(;i<r;){let a=i+r>>1;this.lineStarts[a]<t?i=a+1:r=a}if(this.lineStarts[i]===t)return{line:i+1,col:1};if(i===0)return{line:0,col:t};let n=this.lineStarts[i-1];return{line:i,col:t-n+1}}}};Sh.LineCounter=wl});var bl=P(Rh=>{"use strict";var oE=aa("process"),Eh=to(),sE=gl();function Kt(e,t){for(let i=0;i<e.length;++i)if(e[i].type===t)return!0;return!1}function Ch(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 Ph(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 ro(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 Yi(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 no(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let i=0;i<t.length;++i)e.push(t[i])}function xh(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Kt(t.start,"explicit-key-ind")&&!Kt(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Ph(t.value)?t.value.end?no(t.value.end,t.sep):t.value.end=t.sep:no(t.start,t.sep),delete t.sep)}var Nl=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 sE.Lexer,this.onNewLine=t}*parse(t,i=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(t,i))yield*this.next(r);i||(yield*this.end())}*next(t){if(this.source=t,oE.env.LOG_TOKENS&&console.log("|",Eh.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let i=Eh.tokenType(t);if(i)if(i==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=i,yield*this.step(),i){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let r=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:r,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let i=t??this.stack.pop();if(!i)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield i;else{let r=this.peek(1);switch(i.type==="block-scalar"?i.indent="indent"in r?r.indent:0:i.type==="flow-collection"&&r.type==="document"&&(i.indent=0),i.type==="flow-collection"&&xh(i),r.type){case"document":r.value=i;break;case"block-scalar":r.props.push(i);break;case"block-map":{let n=r.items[r.items.length-1];if(n.value){r.items.push({start:[],key:i,sep:[]}),this.onKeyLine=!0;return}else if(n.sep)n.value=i;else{Object.assign(n,{key:i,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case"block-seq":{let n=r.items[r.items.length-1];n.value?r.items.push({start:[],value:i}):n.value=i;break}case"flow-collection":{let n=r.items[r.items.length-1];!n||n.value?r.items.push({start:[],key:i,sep:[]}):n.sep?n.value=i:Object.assign(n,{key:i,sep:[]});return}default:yield*this.pop(),yield*this.pop(i)}if((r.type==="document"||r.type==="block-map"||r.type==="block-seq")&&(i.type==="block-map"||i.type==="block-seq")){let n=i.items[i.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&Ch(n.start)===-1&&(i.indent===0||n.start.every(a=>a.type!=="comment"||a.indent<i.indent))&&(r.type==="document"?r.end=n.start:r.items.push({start:n.start}),i.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{Ch(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let i=this.startBlockValue(t);i?this.stack.push(i):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let i=ro(this.peek(2)),r=Yi(i),n;t.end?(n=t.end,n.push(this.sourceToken),delete t.end):n=[this.sourceToken];let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:r,key:t,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let i=this.source.indexOf(`
138
+ `?yield*this.pushCount(2):0}*pushSpaces(t){let i=this.pos-1,r;do r=this.buffer[++i];while(r===" "||t&&r===" ");let n=i-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=i),n}*pushUntil(t){let i=this.pos,r=this.buffer[i];for(;!t(r);)r=this.buffer[++i];return yield*this.pushToIndex(i,!1)}};kh.Lexer=vl});var yl=P(Sh=>{"use strict";var wl=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let i=0,r=this.lineStarts.length;for(;i<r;){let a=i+r>>1;this.lineStarts[a]<t?i=a+1:r=a}if(this.lineStarts[i]===t)return{line:i+1,col:1};if(i===0)return{line:0,col:t};let n=this.lineStarts[i-1];return{line:i,col:t-n+1}}}};Sh.LineCounter=wl});var bl=P(Rh=>{"use strict";var cE=aa("process"),Eh=to(),lE=gl();function Kt(e,t){for(let i=0;i<e.length;++i)if(e[i].type===t)return!0;return!1}function Ch(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 Ph(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 ro(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 Yi(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 no(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let i=0;i<t.length;++i)e.push(t[i])}function xh(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Kt(t.start,"explicit-key-ind")&&!Kt(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Ph(t.value)?t.value.end?no(t.value.end,t.sep):t.value.end=t.sep:no(t.start,t.sep),delete t.sep)}var Nl=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 lE.Lexer,this.onNewLine=t}*parse(t,i=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(t,i))yield*this.next(r);i||(yield*this.end())}*next(t){if(this.source=t,cE.env.LOG_TOKENS&&console.log("|",Eh.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let i=Eh.tokenType(t);if(i)if(i==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=i,yield*this.step(),i){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let r=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:r,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let i=t??this.stack.pop();if(!i)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield i;else{let r=this.peek(1);switch(i.type==="block-scalar"?i.indent="indent"in r?r.indent:0:i.type==="flow-collection"&&r.type==="document"&&(i.indent=0),i.type==="flow-collection"&&xh(i),r.type){case"document":r.value=i;break;case"block-scalar":r.props.push(i);break;case"block-map":{let n=r.items[r.items.length-1];if(n.value){r.items.push({start:[],key:i,sep:[]}),this.onKeyLine=!0;return}else if(n.sep)n.value=i;else{Object.assign(n,{key:i,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case"block-seq":{let n=r.items[r.items.length-1];n.value?r.items.push({start:[],value:i}):n.value=i;break}case"flow-collection":{let n=r.items[r.items.length-1];!n||n.value?r.items.push({start:[],key:i,sep:[]}):n.sep?n.value=i:Object.assign(n,{key:i,sep:[]});return}default:yield*this.pop(),yield*this.pop(i)}if((r.type==="document"||r.type==="block-map"||r.type==="block-seq")&&(i.type==="block-map"||i.type==="block-seq")){let n=i.items[i.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&Ch(n.start)===-1&&(i.indent===0||n.start.every(a=>a.type!=="comment"||a.indent<i.indent))&&(r.type==="document"?r.end=n.start:r.items.push({start:n.start}),i.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{Ch(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let i=this.startBlockValue(t);i?this.stack.push(i):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let i=ro(this.peek(2)),r=Yi(i),n;t.end?(n=t.end,n.push(this.sourceToken),delete t.end):n=[this.sourceToken];let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:r,key:t,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let i=this.source.indexOf(`
139
139
  `)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(`
140
140
  `,i)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,i.value){let r="end"in i.value?i.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else if(i.sep)i.sep.push(this.sourceToken);else{if(this.atIndentedComment(i.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){no(n,i.start),n.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let r=!this.onKeyLine&&this.indent===t.indent,n=r&&(i.sep||i.explicitKey)&&this.type!=="seq-item-ind",a=[];if(n&&i.sep&&!i.value){let o=[];for(let s=0;s<i.sep.length;++s){let c=i.sep[s];switch(c.type){case"newline":o.push(s);break;case"space":break;case"comment":c.indent>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=i.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":n||i.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"explicit-key-ind":!i.sep&&!i.explicitKey?(i.start.push(this.sourceToken),i.explicitKey=!0):n||i.value?(a.push(this.sourceToken),t.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(i.explicitKey)if(i.sep)if(i.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Kt(i.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]});else if(Ph(i.key)&&!Kt(i.sep,"newline")){let o=Yi(i.start),s=i.key,c=i.sep;c.push(this.sourceToken),delete i.key,delete i.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?i.sep=i.sep.concat(a,this.sourceToken):i.sep.push(this.sourceToken);else if(Kt(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=Yi(i.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else i.sep?i.value||n?t.items.push({start:a,key:null,sep:[this.sourceToken]}):Kt(i.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);n||i.value?(t.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):i.sep?this.stack.push(o):(Object.assign(i,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!i.explicitKey&&i.sep&&!Kt(i.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else r&&t.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(i.value){let r="end"in i.value?i.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(i.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){no(n,i.start),n.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return;case"anchor":case"tag":if(i.value||this.indent<=t.indent)break;i.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;i.value||Kt(i.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return}if(this.indent>t.indent){let r=this.startBlockValue(t);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let i=t.items[t.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!i||i.sep?t.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return;case"map-value-ind":!i||i.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!i||i.value?t.items.push({start:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let n=this.flowScalar(this.type);!i||i.value?t.items.push({start:[],key:n,sep:[]}):i.sep?this.stack.push(n):Object.assign(i,{key:n,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===t.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let n=ro(r),a=Yi(n);xh(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let i=this.source.indexOf(`
141
141
  `)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(`
142
- `,i)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=ro(t),r=Yi(i);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let i=ro(t),r=Yi(i);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,i){return this.type!=="comment"||this.indent<=i?!1:t.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Rh.Parser=Nl});var jh=P(fn=>{"use strict";var Ah=sl(),cE=rn(),dn=on(),lE=ac(),uE=F(),dE=yl(),_h=bl();function Ih(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new dE.LineCounter||null,prettyErrors:t}}function fE(e,t={}){let{lineCounter:i,prettyErrors:r}=Ih(t),n=new _h.Parser(i?.addNewLine),a=new Ah.Composer(t),o=Array.from(a.compose(n.parse(e)));if(r&&i)for(let s of o)s.errors.forEach(dn.prettifyError(e,i)),s.warnings.forEach(dn.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Th(e,t={}){let{lineCounter:i,prettyErrors:r}=Ih(t),n=new _h.Parser(i?.addNewLine),a=new Ah.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 dn.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&i&&(o.errors.forEach(dn.prettifyError(e,i)),o.warnings.forEach(dn.prettifyError(e,i))),o}function pE(e,t,i){let r;typeof t=="function"?r=t:i===void 0&&t&&typeof t=="object"&&(i=t);let n=Th(e,i);if(!n)return null;if(n.warnings.forEach(a=>lE.warn(n.options.logLevel,a)),n.errors.length>0){if(n.options.logLevel!=="silent")throw n.errors[0];n.errors=[]}return n.toJS(Object.assign({reviver:r},i))}function hE(e,t,i){let r=null;if(typeof t=="function"||Array.isArray(t)?r=t:i===void 0&&t&&(i=t),typeof i=="string"&&(i=i.length),typeof i=="number"){let n=Math.round(i);i=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=i??t??{};if(!n)return}return uE.isDocument(e)&&!r?e.toString(i):new cE.Document(e,r,i).toString(i)}fn.parse=pE;fn.parseAllDocuments=fE;fn.parseDocument=Th;fn.stringify=hE});var Xi=P(J=>{"use strict";var mE=sl(),vE=rn(),gE=Fc(),kl=on(),wE=Vr(),Yt=F(),yE=zt(),NE=ne(),bE=Gt(),kE=Ut(),SE=to(),EE=gl(),CE=yl(),xE=bl(),ao=jh(),$h=Hr();J.Composer=mE.Composer;J.Document=vE.Document;J.Schema=gE.Schema;J.YAMLError=kl.YAMLError;J.YAMLParseError=kl.YAMLParseError;J.YAMLWarning=kl.YAMLWarning;J.Alias=wE.Alias;J.isAlias=Yt.isAlias;J.isCollection=Yt.isCollection;J.isDocument=Yt.isDocument;J.isMap=Yt.isMap;J.isNode=Yt.isNode;J.isPair=Yt.isPair;J.isScalar=Yt.isScalar;J.isSeq=Yt.isSeq;J.Pair=yE.Pair;J.Scalar=NE.Scalar;J.YAMLMap=bE.YAMLMap;J.YAMLSeq=kE.YAMLSeq;J.CST=SE;J.Lexer=EE.Lexer;J.LineCounter=CE.LineCounter;J.Parser=xE.Parser;J.parse=ao.parse;J.parseAllDocuments=ao.parseAllDocuments;J.parseDocument=ao.parseDocument;J.stringify=ao.stringify;J.visit=$h.visit;J.visitAsync=$h.visitAsync});import{promises as Eu}from"fs";import Vv from"path";var Fs={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:"验证预期"}},Xy={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:"结论"}},Qy={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:"结论"}},Wd=new Map,qs=new Map;for(let e of Object.keys(Fs)){for(let[t,i]of Object.entries(Fs[e]))Wd.set(i.toLocaleLowerCase("en-US"),t);for(let[t,i]of Object.entries(Xy[e]))qs.set(i.toLocaleLowerCase("en-US"),t);for(let[t,i]of Object.entries(Qy[e]))qs.set(i.toLocaleLowerCase("en-US"),t)}function Zy(e,t){return Fs[e][t]}function oa(e){return Wd.get(e.trim().toLocaleLowerCase("en-US"))??null}function zd(e){return qs.get(e.trim().toLocaleLowerCase("en-US"))??null}function sa(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(i=>`# ${Zy(e,i)}
142
+ `,i)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=ro(t),r=Yi(i);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let i=ro(t),r=Yi(i);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,i){return this.type!=="comment"||this.indent<=i?!1:t.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Rh.Parser=Nl});var jh=P(fn=>{"use strict";var Ah=sl(),uE=rn(),dn=on(),dE=ac(),fE=F(),pE=yl(),_h=bl();function Ih(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new pE.LineCounter||null,prettyErrors:t}}function hE(e,t={}){let{lineCounter:i,prettyErrors:r}=Ih(t),n=new _h.Parser(i?.addNewLine),a=new Ah.Composer(t),o=Array.from(a.compose(n.parse(e)));if(r&&i)for(let s of o)s.errors.forEach(dn.prettifyError(e,i)),s.warnings.forEach(dn.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Th(e,t={}){let{lineCounter:i,prettyErrors:r}=Ih(t),n=new _h.Parser(i?.addNewLine),a=new Ah.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 dn.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&i&&(o.errors.forEach(dn.prettifyError(e,i)),o.warnings.forEach(dn.prettifyError(e,i))),o}function mE(e,t,i){let r;typeof t=="function"?r=t:i===void 0&&t&&typeof t=="object"&&(i=t);let n=Th(e,i);if(!n)return null;if(n.warnings.forEach(a=>dE.warn(n.options.logLevel,a)),n.errors.length>0){if(n.options.logLevel!=="silent")throw n.errors[0];n.errors=[]}return n.toJS(Object.assign({reviver:r},i))}function vE(e,t,i){let r=null;if(typeof t=="function"||Array.isArray(t)?r=t:i===void 0&&t&&(i=t),typeof i=="string"&&(i=i.length),typeof i=="number"){let n=Math.round(i);i=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=i??t??{};if(!n)return}return fE.isDocument(e)&&!r?e.toString(i):new uE.Document(e,r,i).toString(i)}fn.parse=mE;fn.parseAllDocuments=hE;fn.parseDocument=Th;fn.stringify=vE});var Xi=P(J=>{"use strict";var gE=sl(),wE=rn(),yE=Fc(),kl=on(),NE=Vr(),Yt=F(),bE=zt(),kE=ne(),SE=Gt(),EE=Ut(),CE=to(),xE=gl(),PE=yl(),RE=bl(),ao=jh(),$h=Hr();J.Composer=gE.Composer;J.Document=wE.Document;J.Schema=yE.Schema;J.YAMLError=kl.YAMLError;J.YAMLParseError=kl.YAMLParseError;J.YAMLWarning=kl.YAMLWarning;J.Alias=NE.Alias;J.isAlias=Yt.isAlias;J.isCollection=Yt.isCollection;J.isDocument=Yt.isDocument;J.isMap=Yt.isMap;J.isNode=Yt.isNode;J.isPair=Yt.isPair;J.isScalar=Yt.isScalar;J.isSeq=Yt.isSeq;J.Pair=bE.Pair;J.Scalar=kE.Scalar;J.YAMLMap=SE.YAMLMap;J.YAMLSeq=EE.YAMLSeq;J.CST=CE;J.Lexer=xE.Lexer;J.LineCounter=PE.LineCounter;J.Parser=RE.Parser;J.parse=ao.parse;J.parseAllDocuments=ao.parseAllDocuments;J.parseDocument=ao.parseDocument;J.stringify=ao.stringify;J.visit=$h.visit;J.visitAsync=$h.visitAsync});import{promises as Eu}from"fs";import Vv from"path";var Fs={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:"验证预期"}},Zy={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:"结论"}},eN={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:"结论"}},Wd=new Map,qs=new Map;for(let e of Object.keys(Fs)){for(let[t,i]of Object.entries(Fs[e]))Wd.set(i.toLocaleLowerCase("en-US"),t);for(let[t,i]of Object.entries(Zy[e]))qs.set(i.toLocaleLowerCase("en-US"),t);for(let[t,i]of Object.entries(eN[e]))qs.set(i.toLocaleLowerCase("en-US"),t)}function tN(e,t){return Fs[e][t]}function oa(e){return Wd.get(e.trim().toLocaleLowerCase("en-US"))??null}function zd(e){return qs.get(e.trim().toLocaleLowerCase("en-US"))??null}function sa(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(i=>`# ${tN(e,i)}
143
143
  `).join(`
144
- `)}var bu=Or(Xi(),1);import{promises as jv}from"fs";import si from"path";import{execFileSync as PE}from"child_process";import pn from"path";function Qi(e,t){return PE("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function RE(e,t){let i=pn.normalize(e),r=pn.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function Ee(e){try{let t=pn.resolve(Qi(e,["rev-parse","--show-toplevel"])),r=Qi(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=r?pn.resolve(r.slice(9)):t,a=null;try{a=Qi(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!RE(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function Oh(e){try{Qi(e,["rev-parse","--is-inside-work-tree"]);let t=Qi(e,["worktree","list","--porcelain"]).split(/\r?\n/u),i=[],r=null;for(let n of t)n.startsWith("worktree ")?(r&&i.push(r),r={root:pn.resolve(n.slice(9)),branch:null,detached:!1}):r&&n.startsWith("branch refs/heads/")?r.branch=n.slice(18):r&&n==="detached"&&(r.detached=!0);return r&&i.push(r),i}catch{return[]}}function Zi(e){return Oh(e).map(t=>t.root)}function Ei(e,t){try{let i=Qi(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(i)?i:null}catch{return null}}import{createHash as TE}from"node:crypto";import{promises as Ye}from"node:fs";import De from"node:path";import{TextDecoder as jE}from"node:util";import Sl from"path";var AE=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),_E=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function IE(e){return e.toLowerCase().startsWith(".env")}function ft(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>IE(r))?"environment-file":i.some(r=>_E.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>AE.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function El(e,t){let i=ft(t);if(i)return i;let r=Sl.resolve(e.projectRoot,...t.split("/")),n=Sl.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||r===Sl.resolve(e.configFile)?"native-runtime":null}function Xt(e){return e!==0&&e!==0n&&e!=="0"}function _e(e,t){return Xt(e.dev)&&Xt(t.dev)&&Xt(e.ino)&&Xt(t.ino)}function q(e,t){let i=Xt(e.dev)&&Xt(t.dev);if(i&&e.dev!==t.dev)return!1;let r=Xt(e.ino)&&Xt(t.ino);return r&&e.ino!==t.ino?!1:i&&r?!0:e.birthtime===t.birthtime}var hn=1024*1024;function Cl(e,t){let i=De.relative(e,t);return i===""||!De.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${De.sep}`)}function $E(e){let t=De.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||De.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let i=e.toLowerCase(),r=ft(e);if(r||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${r??"native-runtime"}): ${e}`);return e}function OE(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function HE(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function oo(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return _e(i,r)?q(i,r):q(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Hh(e){let t=await Ye.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Ye.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function DE(e,t){let i=De.resolve(e),r=De.resolve(t);if(!Cl(i,r))throw new Error("Native artifact path is outside its root");let n=[await Hh(i)],a=i;for(let o of De.relative(i,r).split(De.sep).filter(Boolean)){a=De.join(a,o);let s=await Hh(a);if(!Cl(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function Dh(e){for(let t of e){let i=await Ye.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!HE(t,i)||await Ye.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function re(e){let t=$E(e.ref),i=e.maxBytes===null?null:OE(e.maxBytes??hn),r=De.resolve(e.root,...t.split("/")),n=await DE(e.root,De.dirname(r));await e.hooks?.afterParentChainCaptured?.();let a=await Ye.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(i!==null&&a.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);let o=await Ye.realpath(r);if(!Cl(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Ye.open(r,"r");try{let[c,l,u]=await Promise.all([s.stat(),Ye.lstat(r),Ye.realpath(r)]);if(await Dh(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!oo(a,c)||!oo(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,p=Buffer.allocUnsafe(i===null?64*1024:Math.min(64*1024,i+1));for(;;){let k=i===null?p.length:i+1-f,N=await s.read(p,0,Math.min(p.length,k),null);if(N.bytesRead===0)break;if(f+=N.bytesRead,i!==null&&f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,N.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([s.stat(),Ye.lstat(r),Ye.realpath(r)]);if(await Dh(n),!h.isFile()||h.isSymbolicLink()||m!==o||!oo(c,v)||!oo(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let S=Buffer.concat(d,f),y;try{y=new jE("utf-8",{fatal:!0}).decode(S)}catch(k){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:k})}return{ref:t,size:f,hash:e.includeHash===!1?null:TE("sha256").update(S).digest("hex"),text:y}}finally{await s.close()}}import{randomUUID as BE}from"crypto";import{promises as le}from"fs";import Xe from"path";function so(e,t){let i=Xe.relative(e,t);return i===""||!Xe.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Xe.sep}`)}function LE(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function co(e,t){return q({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function VE(e,t){return co(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Bh(e){let t=await le.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await le.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function er(e){for(let t of e){let i=await le.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!LE(t,i)||await le.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function FE(e,t,i){let[r,n]=await Promise.all([le.lstat(e),le.realpath(e),i?er(i):Promise.resolve()]);if(!r.isFile()||r.isSymbolicLink()||!co(r,t)||i&&!so(i[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return r}async function qE(e,t){let i=Xe.resolve(e),r=Xe.resolve(t);if(!so(i,r))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await Bh(i)],a=Xe.relative(i,r).split(Xe.sep).filter(Boolean),o=i;for(let s of a){await er(n),o=Xe.join(o,s);try{await le.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Bh(o);if(!so(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await er(n),n}async function ME(e){let t;try{t=await le.open(e,"r"),await t.sync()}catch(i){let r=i.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(r??""))throw i}finally{await t?.close()}}async function WE(e,t,i={}){let r=Xe.dirname(e),n=i.containedRoot?await qE(i.containedRoot,r):null;n||await le.mkdir(r,{recursive:!0});let a=Xe.join(r,`.${Xe.basename(e)}.${BE()}.tmp`),o,s,c;try{if(await i.beforeTemporaryOpen?.(),o=await le.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([le.lstat(a),le.realpath(a)]);if(await er(n),!l.isFile()||l.isSymbolicLink()||!co(s,l)||!so(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(),!co(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await i.afterTemporaryClose?.(),!c)throw new Error("Native atomic write temporary file was not written");if(c=await FE(a,c,n),await i.beforeCommit?.(),n){await er(n);let l=await le.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!VE(l,c))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await le.link(a,e),await le.unlink(a)):await le.rename(a,e),await ME(r)}catch(l){if(await o?.close(),!n)await le.rm(a,{force:!0});else try{await er(n),await le.rm(a,{force:!0})}catch{}throw l}}async function Et(e,t,i={}){await WE(e,t,i)}async function Qe(e,t,i={}){await Et(e,JSON.stringify(t,null,2)+`
145
- `,i)}var Pl=Or(Xi(),1);import Qt from"path";var mn=64*1024,uo=1024,fo=64,Lh=1024,Vh=64,Rl=5,lo={learning:!0,retrieval:!0},Mh={provider:"local"},zE=12e4,Fh=6e5,JE=[".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/**"],GE=["**/.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"],UE=[...JE,...GE].sort((e,t)=>e.localeCompare(t,"en"));var Ce={include:["**/*"],exclude:[...UE],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function KE(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||Qt.posix.isAbsolute(i)||Qt.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be a project-relative path`);if(i===".")return[];let r=i.replaceAll("\\","/").split("/");if(r.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(r.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return r}function Ci(e){let t=KE(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Wh(e,t="docs"){let i=e??t;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function po(e,t,i=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim().replaceAll("\\","/");if(r.length===0||Qt.posix.isAbsolute(r)||Qt.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be relative to its declared path base`);let n=r.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(r))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function Ct(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function zh(e,t,i){let r=e??t;if(r!=="en"&&r!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return r}function ho(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>uo)throw new Error(`${t} exceeds ${uo} characters`);let i=0;for(let r=0;r<e.length;r+=1)e[r]==="?"?i+=1:e[r]==="*"&&(i+=1,e[r+1]==="*"&&(r+=1));if(i>fo)throw new Error(`${t} contains more than ${fo} wildcard tokens`);return e}function qh(e,t,i){if(e===void 0)return[...i];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(r=>ho(r,t)))].sort((r,n)=>r.localeCompare(n,"en"))}function xl(e,t,i){let r=e??t;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${i} must be a positive integer`);return r}function YE(e){if(e===void 0)return{...Ce,include:[...Ce.include],exclude:[...Ce.exclude]};let t=Ct(e,"native.snapshot");return{include:qh(t.include,"native.snapshot.include",Ce.include),exclude:qh(t.exclude,"native.snapshot.exclude",Ce.exclude),max_files:xl(t.max_files,Ce.max_files,"native.snapshot.max_files"),max_total_bytes:xl(t.max_total_bytes,Ce.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:xl(t.max_duration_ms,Ce.max_duration_ms,"native.snapshot.max_duration_ms")}}function XE(e){if(e===void 0)return;let t=Ct(e,"native.pending_root_move"),i=t.id,r=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof i!="string"||!/^[a-f0-9-]{8,}$/u.test(i))throw new Error("native.pending_root_move.id is invalid");if(typeof r!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=Ct(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:i,fromArtifactRoot:Ci(r),toArtifactRoot:Ci(n),stage:a,...o?{cleanup:o}:{}}}function QE(e){if(e===void 0)return;let t=Ct(e,"native.finish");if(t.pull_request===void 0)return{};let i=Ct(t.pull_request,"native.finish.pull_request");if(i.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(i.command)||i.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(i.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let r=i.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(Qt.posix.isAbsolute(r[0])||Qt.win32.isAbsolute(r[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=i.timeout_ms??zE;if(!Number.isSafeInteger(n)||n<1||n>Fh)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Fh}`);return{pull_request:{provider:"repository-command",command:r,timeout_ms:n}}}function ZE(e,t={}){let i=Ct(e,"native"),r=i.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof r!="string")throw new Error("native.artifact_root must be a string");let n=i.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=i.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=i.max_verify_failures??Rl;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=XE(i.pending_root_move),c=QE(i.finish);return{artifact_root:Ci(r),language:zh(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:YE(i.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function eC(e){let t=Ct(e,"classic"),i=t.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let r=t.review_mode??"standard";if(r!=="off"&&r!=="standard"&&r!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:Wh(t.artifact_layout),language:zh(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function tC(e){let i=Ct(e,"hook").allow_paths??[];if(!Array.isArray(i))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(i.map((r,n)=>po(r,`hook.allow_paths[${n}]`)))]}}function iC(e){if(e===void 0)return{...lo};let t=Ct(e,"memory"),i=t.learning??lo.learning,r=t.retrieval??lo.retrieval;if(typeof i!="boolean")throw new Error("memory.learning must be true or false");if(typeof r!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:i,retrieval:r}}function Al(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function rC(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||i.includes("\\")||i.includes("\0")||Qt.posix.isAbsolute(i)||Qt.win32.isAbsolute(i)||i.startsWith("~")||i.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!i.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(i.length>Lh)throw new Error(`${t} exceeds ${Lh} characters`);let r=0;for(let n=0;n<i.length;n+=1)i[n]==="?"?r+=1:i[n]==="*"&&(r+=1,i[n+1]==="*"&&(n+=1));if(r>Vh)throw new Error(`${t} contains more than ${Vh} wildcard tokens`);return i}function nC(e){let i=Al(e,"knowledge.local").include??[];if(!Array.isArray(i))throw new Error("knowledge.local.include must be an array");return{include:[...new Set(i.map((r,n)=>rC(r,`knowledge.local.include[${n}]`)))]}}function aC(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let i=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),r=i==="localhost"||i==="127.0.0.1"||i==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&r))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function oC(e){let t=Al(e,"knowledge.remote"),i=aC(t.endpoint),r=t.token_env;if(r!==void 0&&(typeof r!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(r)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:i,...r===void 0?{}:{token_env:r},...n===void 0?{}:{scope:n},timeout_ms:a}}function sC(e){if(e===void 0)return{...Mh};let t=Al(e,"knowledge"),i=t.provider??"local";if(i!=="local"&&i!=="remote")throw new Error("knowledge.provider must be local or remote");let r=t.local===void 0?void 0:nC(t.local);if(i==="local")return{provider:i,...r?{local:r}:{}};let n=t.remote===void 0?void 0:oC(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:i,...r?{local:r}:{},remote:n}}function cC(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function lC(e,t,i,r,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let u=e.workflows??[e.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(f=>f!=="native"&&f!=="classic"))throw new Error("workflows must contain native and/or classic");let d=[...new Set(u)];if(!d.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(d.includes("native")&&!n)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:d,ambient_resume:o,...t?{hook:t}:{},memory:i,knowledge:r,...n?{native:n}:{},...a?{classic:a}:{}}}function vn(e,t={}){let i=(0,Pl.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${i.errors[0].message}`);let r=i.toJS();if(r==null)return{value:{},config:null,ambient_resume:!0};if(typeof r!="object"||Array.isArray(r))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=r,a=cC(n.ambient_resume),o=n.hook===void 0?void 0:tC(n.hook),s=iC(n.memory),c=sC(n.knowledge),l=n.native===void 0?void 0:ZE(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:eC(n.classic),d=lC(n,o,s,c,l,u,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...u?{classic:u}:{}}}function mo(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...lo},knowledge:{...Mh},native:{artifact_root:Ci(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:Rl,snapshot:{...Ce,include:[...Ce.include],exclude:[...Ce.exclude]}}}}import{createHash as dC}from"crypto";import{promises as wo}from"fs";import Zt from"path";import{constants as vo,promises as xi}from"fs";var Ze=class extends Error{reason;constructor(t,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=t}};function _l(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Jh(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function gn(e){return{dev:e.dev,ino:e.ino,birthtime:_l(e)}}function go(e,t){let i=gn(e),r=gn(t);return _e(i,r)?q(i,r):q(i,r)&&_l(e)===_l(t)&&Jh(e)===Jh(t)&&e.size===t.size}async function Pi(e,t,i={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let r=i.label??"file",n=i.bigint===!0,a=await xi.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Ze("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Ze("too-large",`${r} exceeds ${t} bytes`);let o=await xi.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:gn(a)});let s=process.platform==="win32"?vo.O_RDONLY:vo.O_RDONLY|vo.O_NOFOLLOW|vo.O_NONBLOCK,c;try{c=await xi.open(e,s)}catch(l){throw l.code==="ELOOP"?new Ze("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),xi.lstat(e,{bigint:n}),xi.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!go(a,l)||!go(a,u))throw new Ze("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:gn(l)}),await i.hooks?.afterOpen?.();let f=[],p=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let y=t+1-p,{bytesRead:k}=await c.read(v,0,Math.min(v.length,y),null);if(k===0)break;if(p+=k,p>t)throw new Ze("too-large",`${r} exceeds ${t} bytes`);f.push(Buffer.from(v.subarray(0,k)))}await i.hooks?.beforeFinalCheck?.();let[h,m,S]=await Promise.all([c.stat({bigint:n}),xi.lstat(e,{bigint:n}),xi.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||S!==o||!go(a,h)||!go(a,m))throw new Ze("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:S,identity:gn(h)}),{bytes:Buffer.concat(f,p),stat:h,realPath:S}}finally{await c.close()}}function uC(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Il(e,t){let i=Zt.relative(e,t);return i===""||!Zt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Zt.sep}`)}async function Gh(e,t){let i=Zt.resolve(e),r=await wo.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return wo.realpath(i)}async function Uh(e,t,i,r){let n=e;for(let a=0;a<i.length;a++){n=Zt.join(n,i[a]);let o;try{o=await wo.lstat(n)}catch(u){if(uC(u))return{exists:!1,kind:"missing"};throw u}let s=Zt.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${r.label} crosses a symbolic link or junction at ${s}`);let c=a===i.length-1;if(!c&&!o.isDirectory())throw new Error(`${r.label} ancestor ${s} must be a real directory`);if(c&&(r.expected==="file"&&!o.isFile()||r.expected==="directory"&&!o.isDirectory()||r.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${r.label} must be a real ${r.expected}`);let l=await wo.realpath(n);if(!Il(t,l))throw new Error(`${r.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function tr(e,t,i){let r=po(t,i.label),n=Zt.resolve(e),a=await Gh(n,i.label),o=r.split("/"),s=Zt.resolve(n,...o);if(!Il(n,s))throw new Error(`${i.label} must stay inside the project root`);let c=await Uh(n,a,o,i);return{projectRoot:n,target:s,relative:r,exists:c.exists,kind:c.kind}}async function ei(e,t,i,r){let n=await tr(e,t,{label:r.label,expected:"file"});if(!n.exists){let o=new Error(`${r.label} does not exist`);throw o.code="ENOENT",o}let a=await Gh(n.projectRoot,r.label);return Pi(n.target,i,{...r,verify:async(o,s)=>{if(!Il(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await Uh(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var wn=".comet/config.yaml";function fC(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function yo(e,t={}){return(await No(e,t)).document}async function pC(e){try{return(await ei(e,wn,mn,{label:wn})).bytes}catch(t){if(fC(t))return null;throw t}}function hC(e){return e?{exists:!0,sha256:dC("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function No(e,t={}){let i=await pC(e);return{document:i?vn(i.toString("utf8"),t):null,identity:hC(i)}}async function Tl(e){return(await yo(e))?.config??null}var f0=16*1024;import{existsSync as Yh,promises as ti}from"fs";import W from"path";import yC from"os";var bo=".comet/config.yaml",NC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function Ol(e){try{return await ti.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function bC(e){try{let t=await ti.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function rr(e,t){let i=W.relative(e,t);return i===""||!W.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${W.sep}`)}async function ir(e){let t=[],i=e;for(;!await Ol(i);){let n=W.dirname(i);if(n===i)break;t.push(W.basename(i)),i=n}let r=await ti.realpath(i);return W.resolve(r,...t.reverse())}async function Hl(e){try{return(await ti.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function ko(e){let t=W.resolve(e);try{(await ti.stat(t)).isDirectory()||(t=W.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let i=t,r=W.resolve(yC.homedir());for(;;){if(!(t===r&&i!==r)){let o=W.join(t,...bo.split("/")),s=t===i||await bC(o);if(await Ol(o)&&s)return t}if(await Ol(W.join(t,".git")))return t;let a=W.dirname(t);if(a===t)return i;t=a}}function So(e){return Ci(e)}async function kC(e,t){let i=So(t),r=W.resolve(e,...i.split("/")),n=await ti.realpath(e),a=await ir(r);if(!rr(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function Ri(e,t){let i=So(t),r=await kC(e,i),n=W.join(r,"comet");if(await Hl(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([ir(r),ir(n)]);if(!rr(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=W.resolve(e),c=W.join(s,".comet","runtime","native");if(await Hl(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([ti.realpath(s),ir(c)]);if(!rr(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:W.join(e,...bo.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:W.join(n,"specs"),changesDir:W.join(n,"changes"),archiveDir:W.join(n,"archive"),runtimeDir:c,changesRuntimeDir:W.join(c,"changes"),locksDir:W.join(c,"locks"),transactionsDir:W.join(c,"transactions")}}function Qh(e){if(!NC.test(e))throw new Error(`Invalid Native change name: ${e}`)}function ii(e,t){Qh(t);let i=W.join(e.changesRuntimeDir,t);if(!V(e.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function Zh(e,t){Qh(t);let i=W.join(e.changesDir,t,"runtime");if(!V(e.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function U(e,t){let i=ii(e,t);if(Yh(i))return i;let r=Zh(e,t);return Yh(r)?r:i}async function Xh(e){try{let t=await ti.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function Dl(e,t){let i=ii(e,t),r=Zh(e,t),[n,a]=await Promise.all([Xh(i),Xh(r)]);return n==="invalid"?{status:"invalid",layout:"project-local",path:i,message:"Native Runtime path must be a real directory"}:a==="invalid"?{status:"invalid",layout:"legacy",path:r,message:"Legacy Native Runtime path must be a real directory"}:n==="directory"&&a==="directory"?{status:"invalid",layout:"project-local",path:i,message:"Both project-local and legacy Native Runtime directories exist"}:n==="directory"?{status:"available",layout:"project-local",path:i}:a==="directory"?{status:"available",layout:"legacy",path:r}:{status:"missing",layout:"missing",path:i}}function ri(e,t){if(!t.startsWith("runtime/")||W.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let i=W.resolve(e,...t.slice(8).split("/"));if(!V(e,i))throw new Error(`Native Runtime ref escaped: ${t}`);return i}function ue(e,t){let i=W.resolve(t);if(V(e.runtimeDir,i))return e.runtimeDir;if(V(e.nativeRoot,i))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function V(e,t){return rr(W.resolve(e),W.resolve(t))}async function z(e,t){let i=W.resolve(e),r=W.resolve(t);if(!rr(i,r))throw new Error(`Path is outside the Native root: ${t}`);if(await Hl(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([ir(i),ir(r)]);if(!rr(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return r}var Bl=Ce;var Eo=ho;function EC(e="docs",t="en"){return mo(e,t)}async function Ie(e){let t=(await yo(e))?.config??null;return t?.native?t:null}async function Co(e){let t=await Ie(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function em(e){let t=await ko(e.startPath),i=await Ie(t);if(!i&&e.allowMissingConfig===!1)throw new Error(`${bo} was not found`);if(i?.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let r=e.explicitArtifactRoot?So(e.explicitArtifactRoot):void 0;if(i&&r&&r!==i.native.artifact_root)throw new Error(`Configured Native artifact root is ${i.native.artifact_root}; refusing conflicting root ${r}`);let n=i??EC(r??"docs"),a=await Ri(t,n.native.artifact_root);return{config:n,paths:a,configured:i!==null}}import{promises as iP}from"fs";import rP from"path";import{AsyncLocalStorage as CC}from"async_hooks";import{randomUUID as rm}from"crypto";import{promises as Be}from"fs";import nm from"os";import ye from"path";var tm=16*1024,am=".coordinator",xC=5e3,im=new CC,xo=new Map;function PC(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function RC(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let i=e;if(typeof i.id!="string"||i.id.length===0||typeof i.pid!="number"||!Number.isSafeInteger(i.pid)||i.pid<1||typeof i.hostname!="string"||i.hostname.length===0||typeof i.createdAt!="string"||i.createdAt.length===0||typeof i.operation!="string"||i.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return i}function om(e){return{device:e.dev.toString(),inode:e.ino.toString(),size:e.size.toString(),birthtimeNs:e.birthtimeNs.toString(),ctimeNs:e.ctimeNs.toString(),mtimeNs:e.mtimeNs.toString()}}function Po(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},r={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return _e(i,r)?q(i,r):q(i,r)&&e.size===t.size}function Ll(e,t){return Po(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function pt(e){let t,i;try{let r=await Pi(e,tm,{bigint:!0,label:"Native lock"});t=r.bytes,i=r.stat}catch(r){if(r.code==="ENOENT")return null;throw r instanceof Ze?r.reason==="too-large"?new Error(`Native lock metadata exceeds ${tm} bytes: ${e}`,{cause:r}):r.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:r}):new Error(`Native lock changed while reading: ${e}`,{cause:r}):r}return{file:e,owner:RC(JSON.parse(t.toString("utf8")),e),identity:om(i)}}async function AC(e){return(await pt(e))?.owner??null}function sm(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==nm.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=OC(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function _C(e,t){try{await Be.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await Be.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function Vl(e,t){let i=await pt(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Ll(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await Be.mkdir(t,{recursive:!0});let r=ye.join(t,`${ye.basename(e.file)}.${e.owner.id}.${rm()}.removed`);try{await Be.rename(e.file,r)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await pt(r);if(!n||n.owner.id!==e.owner.id||!Po(n.identity,e.identity))throw await _C(r,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await Be.rm(r,{force:!0}),"removed"}function cm(e){return{id:rm(),pid:process.pid,hostname:nm.hostname(),createdAt:new Date().toISOString(),operation:e}}async function lm(e,t){let i;try{i=await Be.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await AC(e);throw new Error(`Native lock is already held: ${e}${o?` by pid ${o.pid} for ${o.operation}`:""}`,{cause:a})}throw a}let r;try{await i.writeFile(JSON.stringify(t,null,2)+`
146
- `,"utf8"),await i.sync(),r=om(await i.stat({bigint:!0}))}finally{await i.close()}let n=await pt(e);if(!r||!n||n.owner.id!==t.id||!Po(n.identity,r))throw new Error(`Native lock changed after write: ${e}`);return n.identity}async function IC(e,t){let i=await z(e.runtimeDir,e.locksDir);await Be.mkdir(i,{recursive:!0});let r=await z(e.runtimeDir,ye.join(i,am));await Be.mkdir(r,{recursive:!0});let n=cm(t),a=ye.join(r,`.${n.id}.tmp`),o=ye.join(r,`${n.id}.claim`);try{let s=await lm(a,n);await Be.rename(a,o);let c=await pt(o);if(!c||!Po(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:i,owner:n,identity:c.identity}}finally{await Be.rm(a,{force:!0})}}async function TC(e){let t=ye.dirname(e.file),i=!1,r=ye.basename(e.file);for(let n of await Be.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=ye.join(t,n.name);if(ye.resolve(a)!==ye.resolve(e.file))try{let o=await pt(a),s=sm(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Vl(o,t);continue}n.name<r&&(i=!0)}catch{n.name<r&&(i=!0)}}return i}async function um(e){let t=await pt(e.file);if(t){if(t.owner.id!==e.owner.id||!Ll(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await Vl(t,ye.dirname(e.file))}}async function jC(e,t){let i=Date.now()+xC;for(;;){let r=await IC(e,t);if(!await TC(r))return r;if(await um(r),Date.now()>=i)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function $C(e){let t=xo.get(e)??Promise.resolve(),i,r=new Promise(a=>{i=a}),n=t.then(()=>r);return xo.set(e,n),await t,()=>{i(),xo.get(e)===n&&xo.delete(e)}}async function dm(e,t,i){let r=ye.resolve(e.locksDir),n=im.getStore();if(n?.has(r))return i();let a=await $C(r);try{let o=await jC(e,t),s=new Map(n??[]);return s.set(r,o),await im.run(s,async()=>{try{return await i()}finally{await um(o)}})}finally{a()}}async function Ro(e,t,i){return dm(e,`acquire ${t}`,async()=>{let r=await z(e.runtimeDir,e.locksDir);await Be.mkdir(r,{recursive:!0});let n=await z(e.runtimeDir,ye.join(r,PC(t))),a=cm(i),o=await lm(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:r,owner:a,identity:o}})}async function Ao(e){await pt(e.file)&&await dm({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${ye.basename(e.file)}`,async()=>{let t=await pt(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Ll(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=ye.join(e.locksDir,am);await Vl(t,i)})}function OC(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function fm(e){return sm(await pt(e))}import _x from"node:path";import pm from"node:path";import{createHash as HC}from"crypto";function et(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function DC(e,t){t.has(e)&&et("cyclic structures are not supported"),t.add(e);try{let i=Object.keys(e);for(let r=0;r<e.length;r+=1)Object.prototype.hasOwnProperty.call(e,r)||et("sparse arrays are not supported");return(i.length!==e.length||i.some((r,n)=>r!==String(n)))&&et("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&et("symbol properties are not supported"),`[${e.map(r=>Fl(r,t)).join(",")}]`}finally{t.delete(e)}}function BC(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&et("only plain objects are supported"),t.has(e)&&et("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&et("symbol properties are not supported"),t.add(e);try{let r=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=r[o];return(!s||!("value"in s))&&et("accessor properties are not supported"),`${JSON.stringify(o)}:${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)||et("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?DC(e,t):BC(e,t);case"bigint":case"function":case"symbol":case"undefined":return et(`${typeof e} values are not supported`)}return et("unsupported value type")}function Nn(e){return Fl(e,new Set)}function H(e,t){if(e.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(e))throw new TypeError("Canonical hash tag must not contain a line break");return HC("sha256").update(`${e}
147
- ${Nn(t)}`).digest("hex")}var LC="comet.native.acceptance.v1",VC=/^acceptance-[a-f0-9]{64}$/u,FC=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),qC=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,MC=/^[a-f0-9]{64}$/u,WC=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function zC(e,t){return e<t?-1:e>t?1:0}var xt=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),bn=Object.freeze({maxCriteria:1024}),hm="<!-- comet-native:acceptance-evidence:start -->",mm="<!-- comet-native:acceptance-evidence:end -->";function vm(e,t){if(Buffer.byteLength(e,"utf8")<=t)return{value:e,truncated:!1};let i="",r=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(r+a>t)break;i+=n,r+=a}return{value:i,truncated:!0}}function gm(e,t){let i=t.toString(36),r=H("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${i}.${r}`}function JC(e){if(!MC.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=WC.exec(e.cursor);if(!t)throw new Error("Native acceptance cursor is invalid");if(t[1]!==e.acceptanceHash)throw new Error("Native acceptance cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native acceptance cursor offset is invalid");if(t[3]!==H("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:i}))throw new Error("Native acceptance cursor integrity check failed");return i}function GC(e,t){let i=vm(e.text,xt.maxTextBytes),r=e.context.slice(0,xt.maxContextItems).map(n=>vm(n,xt.maxContextItemBytes));return{id:e.id,kind:e.kind,source:e.source,context:r.map(n=>n.value),text:i.value,contextTruncated:e.context.length>r.length||r.some(n=>n.truncated),textTruncated:i.truncated,verificationStatus:t}}function ym(e){let t=JC({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),i=[],r=[...new Set(e.failedCheckIds??[])].sort(zC),n=r.slice(0,xt.maxFailedCheckIds),a=e.criteria.slice(t,t+xt.maxItems);for(let c of a){let l=[...i,GC(c,e.verificationStatuses?.get(c.id)??"unverified")],u=t+l.length,d={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:l,failedAcceptanceIds:l.filter(f=>f.verificationStatus==="failed").map(f=>f.id),missingAcceptanceIds:l.filter(f=>f.verificationStatus==="missing").map(f=>f.id),failedCheckIds:n,failedCheckIdsTruncated:r.length>n.length,nextCursor:u<e.criteria.length?gm(e.acceptanceHash,u):null,limits:{...xt}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>xt.maxSerializedBytes){if(i.length===0)throw new Error("Native acceptance criterion exceeds the page serialization budget");break}i.push(l.at(-1))}if(e.criteria.length>0&&i.length===0)throw new Error("Native acceptance page could not project its next criterion");let o=t+i.length,s={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:i,failedAcceptanceIds:i.filter(c=>c.verificationStatus==="failed").map(c=>c.id),missingAcceptanceIds:i.filter(c=>c.verificationStatus==="missing").map(c=>c.id),failedCheckIds:n,failedCheckIdsTruncated:r.length>n.length,nextCursor:o<e.criteria.length?gm(e.acceptanceHash,o):null,limits:{...xt}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>xt.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function Ml(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 ql(e,t){let i=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!i)return t;let r=i[1][0];return t===null?{marker:r,length:i[1].length}:r===t.marker&&i[1].length>=t.length&&i[2].trim().length===0?null:t}function wm(e){return e.includes("-->")||e.includes("--!>")}function*nr(e){let t=null,i=!1,r=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
144
+ `)}var bu=Or(Xi(),1);import{promises as jv}from"fs";import si from"path";import{execFileSync as AE}from"child_process";import pn from"path";function Qi(e,t){return AE("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function _E(e,t){let i=pn.normalize(e),r=pn.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function Ee(e){try{let t=pn.resolve(Qi(e,["rev-parse","--show-toplevel"])),r=Qi(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=r?pn.resolve(r.slice(9)):t,a=null;try{a=Qi(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!_E(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function Oh(e){try{Qi(e,["rev-parse","--is-inside-work-tree"]);let t=Qi(e,["worktree","list","--porcelain"]).split(/\r?\n/u),i=[],r=null;for(let n of t)n.startsWith("worktree ")?(r&&i.push(r),r={root:pn.resolve(n.slice(9)),branch:null,detached:!1}):r&&n.startsWith("branch refs/heads/")?r.branch=n.slice(18):r&&n==="detached"&&(r.detached=!0);return r&&i.push(r),i}catch{return[]}}function Zi(e){return Oh(e).map(t=>t.root)}function Ei(e,t){try{let i=Qi(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(i)?i:null}catch{return null}}import{createHash as $E}from"node:crypto";import{promises as Ye}from"node:fs";import De from"node:path";import{TextDecoder as OE}from"node:util";import Sl from"path";var IE=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),TE=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function jE(e){return e.toLowerCase().startsWith(".env")}function ft(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>jE(r))?"environment-file":i.some(r=>TE.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>IE.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function El(e,t){let i=ft(t);if(i)return i;let r=Sl.resolve(e.projectRoot,...t.split("/")),n=Sl.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||r===Sl.resolve(e.configFile)?"native-runtime":null}function Xt(e){return e!==0&&e!==0n&&e!=="0"}function _e(e,t){return Xt(e.dev)&&Xt(t.dev)&&Xt(e.ino)&&Xt(t.ino)}function q(e,t){let i=Xt(e.dev)&&Xt(t.dev);if(i&&e.dev!==t.dev)return!1;let r=Xt(e.ino)&&Xt(t.ino);return r&&e.ino!==t.ino?!1:i&&r?!0:e.birthtime===t.birthtime}var hn=1024*1024;function Cl(e,t){let i=De.relative(e,t);return i===""||!De.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${De.sep}`)}function HE(e){let t=De.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||De.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let i=e.toLowerCase(),r=ft(e);if(r||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${r??"native-runtime"}): ${e}`);return e}function DE(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function BE(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function oo(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return _e(i,r)?q(i,r):q(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Hh(e){let t=await Ye.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Ye.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function LE(e,t){let i=De.resolve(e),r=De.resolve(t);if(!Cl(i,r))throw new Error("Native artifact path is outside its root");let n=[await Hh(i)],a=i;for(let o of De.relative(i,r).split(De.sep).filter(Boolean)){a=De.join(a,o);let s=await Hh(a);if(!Cl(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function Dh(e){for(let t of e){let i=await Ye.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!BE(t,i)||await Ye.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function re(e){let t=HE(e.ref),i=e.maxBytes===null?null:DE(e.maxBytes??hn),r=De.resolve(e.root,...t.split("/")),n=await LE(e.root,De.dirname(r));await e.hooks?.afterParentChainCaptured?.();let a=await Ye.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(i!==null&&a.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);let o=await Ye.realpath(r);if(!Cl(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Ye.open(r,"r");try{let[c,l,u]=await Promise.all([s.stat(),Ye.lstat(r),Ye.realpath(r)]);if(await Dh(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!oo(a,c)||!oo(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,p=Buffer.allocUnsafe(i===null?64*1024:Math.min(64*1024,i+1));for(;;){let k=i===null?p.length:i+1-f,N=await s.read(p,0,Math.min(p.length,k),null);if(N.bytesRead===0)break;if(f+=N.bytesRead,i!==null&&f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,N.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([s.stat(),Ye.lstat(r),Ye.realpath(r)]);if(await Dh(n),!h.isFile()||h.isSymbolicLink()||m!==o||!oo(c,v)||!oo(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let S=Buffer.concat(d,f),y;try{y=new OE("utf-8",{fatal:!0}).decode(S)}catch(k){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:k})}return{ref:t,size:f,hash:e.includeHash===!1?null:$E("sha256").update(S).digest("hex"),text:y}}finally{await s.close()}}import{randomUUID as VE}from"crypto";import{promises as le}from"fs";import Xe from"path";function so(e,t){let i=Xe.relative(e,t);return i===""||!Xe.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Xe.sep}`)}function FE(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function co(e,t){return q({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function qE(e,t){return co(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Bh(e){let t=await le.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await le.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function er(e){for(let t of e){let i=await le.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!FE(t,i)||await le.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function ME(e,t,i){let[r,n]=await Promise.all([le.lstat(e),le.realpath(e),i?er(i):Promise.resolve()]);if(!r.isFile()||r.isSymbolicLink()||!co(r,t)||i&&!so(i[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return r}async function WE(e,t){let i=Xe.resolve(e),r=Xe.resolve(t);if(!so(i,r))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await Bh(i)],a=Xe.relative(i,r).split(Xe.sep).filter(Boolean),o=i;for(let s of a){await er(n),o=Xe.join(o,s);try{await le.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Bh(o);if(!so(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await er(n),n}async function zE(e){let t;try{t=await le.open(e,"r"),await t.sync()}catch(i){let r=i.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(r??""))throw i}finally{await t?.close()}}async function JE(e,t,i={}){let r=Xe.dirname(e),n=i.containedRoot?await WE(i.containedRoot,r):null;n||await le.mkdir(r,{recursive:!0});let a=Xe.join(r,`.${Xe.basename(e)}.${VE()}.tmp`),o,s,c;try{if(await i.beforeTemporaryOpen?.(),o=await le.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([le.lstat(a),le.realpath(a)]);if(await er(n),!l.isFile()||l.isSymbolicLink()||!co(s,l)||!so(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(),!co(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await i.afterTemporaryClose?.(),!c)throw new Error("Native atomic write temporary file was not written");if(c=await ME(a,c,n),await i.beforeCommit?.(),n){await er(n);let l=await le.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!qE(l,c))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await le.link(a,e),await le.unlink(a)):await le.rename(a,e),await zE(r)}catch(l){if(await o?.close(),!n)await le.rm(a,{force:!0});else try{await er(n),await le.rm(a,{force:!0})}catch{}throw l}}async function Et(e,t,i={}){await JE(e,t,i)}async function Qe(e,t,i={}){await Et(e,JSON.stringify(t,null,2)+`
145
+ `,i)}var Pl=Or(Xi(),1);import Qt from"path";var mn=64*1024,uo=1024,fo=64,Lh=1024,Vh=64,Rl=5,lo={learning:!0,retrieval:!0},Mh={provider:"local"},GE=12e4,Fh=6e5,UE=[".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/**"],KE=["**/.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"],YE=[...UE,...KE].sort((e,t)=>e.localeCompare(t,"en"));var Ce={include:["**/*"],exclude:[...YE],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function XE(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||Qt.posix.isAbsolute(i)||Qt.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be a project-relative path`);if(i===".")return[];let r=i.replaceAll("\\","/").split("/");if(r.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(r.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return r}function Ci(e){let t=XE(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Wh(e,t="docs"){let i=e??t;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function po(e,t,i=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim().replaceAll("\\","/");if(r.length===0||Qt.posix.isAbsolute(r)||Qt.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be relative to its declared path base`);let n=r.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(r))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function Ct(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function zh(e,t,i){let r=e??t;if(r!=="en"&&r!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return r}function ho(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>uo)throw new Error(`${t} exceeds ${uo} characters`);let i=0;for(let r=0;r<e.length;r+=1)e[r]==="?"?i+=1:e[r]==="*"&&(i+=1,e[r+1]==="*"&&(r+=1));if(i>fo)throw new Error(`${t} contains more than ${fo} wildcard tokens`);return e}function qh(e,t,i){if(e===void 0)return[...i];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(r=>ho(r,t)))].sort((r,n)=>r.localeCompare(n,"en"))}function xl(e,t,i){let r=e??t;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${i} must be a positive integer`);return r}function QE(e){if(e===void 0)return{...Ce,include:[...Ce.include],exclude:[...Ce.exclude]};let t=Ct(e,"native.snapshot");return{include:qh(t.include,"native.snapshot.include",Ce.include),exclude:qh(t.exclude,"native.snapshot.exclude",Ce.exclude),max_files:xl(t.max_files,Ce.max_files,"native.snapshot.max_files"),max_total_bytes:xl(t.max_total_bytes,Ce.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:xl(t.max_duration_ms,Ce.max_duration_ms,"native.snapshot.max_duration_ms")}}function ZE(e){if(e===void 0)return;let t=Ct(e,"native.pending_root_move"),i=t.id,r=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof i!="string"||!/^[a-f0-9-]{8,}$/u.test(i))throw new Error("native.pending_root_move.id is invalid");if(typeof r!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=Ct(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:i,fromArtifactRoot:Ci(r),toArtifactRoot:Ci(n),stage:a,...o?{cleanup:o}:{}}}function eC(e){if(e===void 0)return;let t=Ct(e,"native.finish");if(t.pull_request===void 0)return{};let i=Ct(t.pull_request,"native.finish.pull_request");if(i.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(i.command)||i.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(i.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let r=i.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(Qt.posix.isAbsolute(r[0])||Qt.win32.isAbsolute(r[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=i.timeout_ms??GE;if(!Number.isSafeInteger(n)||n<1||n>Fh)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Fh}`);return{pull_request:{provider:"repository-command",command:r,timeout_ms:n}}}function tC(e,t={}){let i=Ct(e,"native"),r=i.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof r!="string")throw new Error("native.artifact_root must be a string");let n=i.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=i.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=i.max_verify_failures??Rl;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=ZE(i.pending_root_move),c=eC(i.finish);return{artifact_root:Ci(r),language:zh(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:QE(i.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function iC(e){let t=Ct(e,"classic"),i=t.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let r=t.review_mode??"standard";if(r!=="off"&&r!=="standard"&&r!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:Wh(t.artifact_layout),language:zh(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function rC(e){let i=Ct(e,"hook").allow_paths??[];if(!Array.isArray(i))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(i.map((r,n)=>po(r,`hook.allow_paths[${n}]`)))]}}function nC(e){if(e===void 0)return{...lo};let t=Ct(e,"memory"),i=t.learning??lo.learning,r=t.retrieval??lo.retrieval;if(typeof i!="boolean")throw new Error("memory.learning must be true or false");if(typeof r!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:i,retrieval:r}}function Al(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function aC(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||i.includes("\\")||i.includes("\0")||Qt.posix.isAbsolute(i)||Qt.win32.isAbsolute(i)||i.startsWith("~")||i.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!i.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(i.length>Lh)throw new Error(`${t} exceeds ${Lh} characters`);let r=0;for(let n=0;n<i.length;n+=1)i[n]==="?"?r+=1:i[n]==="*"&&(r+=1,i[n+1]==="*"&&(n+=1));if(r>Vh)throw new Error(`${t} contains more than ${Vh} wildcard tokens`);return i}function oC(e){let i=Al(e,"knowledge.local").include??[];if(!Array.isArray(i))throw new Error("knowledge.local.include must be an array");return{include:[...new Set(i.map((r,n)=>aC(r,`knowledge.local.include[${n}]`)))]}}function sC(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let i=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),r=i==="localhost"||i==="127.0.0.1"||i==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&r))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function cC(e){let t=Al(e,"knowledge.remote"),i=sC(t.endpoint),r=t.token_env;if(r!==void 0&&(typeof r!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(r)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:i,...r===void 0?{}:{token_env:r},...n===void 0?{}:{scope:n},timeout_ms:a}}function lC(e){if(e===void 0)return{...Mh};let t=Al(e,"knowledge"),i=t.provider??"local";if(i!=="local"&&i!=="remote")throw new Error("knowledge.provider must be local or remote");let r=t.local===void 0?void 0:oC(t.local);if(i==="local")return{provider:i,...r?{local:r}:{}};let n=t.remote===void 0?void 0:cC(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:i,...r?{local:r}:{},remote:n}}function uC(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function dC(e,t,i,r,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let u=e.workflows??[e.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(f=>f!=="native"&&f!=="classic"))throw new Error("workflows must contain native and/or classic");let d=[...new Set(u)];if(!d.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(d.includes("native")&&!n)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:d,ambient_resume:o,...t?{hook:t}:{},memory:i,knowledge:r,...n?{native:n}:{},...a?{classic:a}:{}}}function vn(e,t={}){let i=(0,Pl.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${i.errors[0].message}`);let r=i.toJS();if(r==null)return{value:{},config:null,ambient_resume:!0};if(typeof r!="object"||Array.isArray(r))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=r,a=uC(n.ambient_resume),o=n.hook===void 0?void 0:rC(n.hook),s=nC(n.memory),c=lC(n.knowledge),l=n.native===void 0?void 0:tC(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:iC(n.classic),d=dC(n,o,s,c,l,u,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...u?{classic:u}:{}}}function mo(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...lo},knowledge:{...Mh},native:{artifact_root:Ci(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:Rl,snapshot:{...Ce,include:[...Ce.include],exclude:[...Ce.exclude]}}}}import{createHash as pC}from"crypto";import{promises as wo}from"fs";import Zt from"path";import{constants as vo,promises as xi}from"fs";var Ze=class extends Error{reason;constructor(t,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=t}};function _l(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Jh(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function gn(e){return{dev:e.dev,ino:e.ino,birthtime:_l(e)}}function go(e,t){let i=gn(e),r=gn(t);return _e(i,r)?q(i,r):q(i,r)&&_l(e)===_l(t)&&Jh(e)===Jh(t)&&e.size===t.size}async function Pi(e,t,i={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let r=i.label??"file",n=i.bigint===!0,a=await xi.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Ze("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Ze("too-large",`${r} exceeds ${t} bytes`);let o=await xi.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:gn(a)});let s=process.platform==="win32"?vo.O_RDONLY:vo.O_RDONLY|vo.O_NOFOLLOW|vo.O_NONBLOCK,c;try{c=await xi.open(e,s)}catch(l){throw l.code==="ELOOP"?new Ze("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),xi.lstat(e,{bigint:n}),xi.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!go(a,l)||!go(a,u))throw new Ze("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:gn(l)}),await i.hooks?.afterOpen?.();let f=[],p=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let y=t+1-p,{bytesRead:k}=await c.read(v,0,Math.min(v.length,y),null);if(k===0)break;if(p+=k,p>t)throw new Ze("too-large",`${r} exceeds ${t} bytes`);f.push(Buffer.from(v.subarray(0,k)))}await i.hooks?.beforeFinalCheck?.();let[h,m,S]=await Promise.all([c.stat({bigint:n}),xi.lstat(e,{bigint:n}),xi.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||S!==o||!go(a,h)||!go(a,m))throw new Ze("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:S,identity:gn(h)}),{bytes:Buffer.concat(f,p),stat:h,realPath:S}}finally{await c.close()}}function fC(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Il(e,t){let i=Zt.relative(e,t);return i===""||!Zt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Zt.sep}`)}async function Gh(e,t){let i=Zt.resolve(e),r=await wo.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return wo.realpath(i)}async function Uh(e,t,i,r){let n=e;for(let a=0;a<i.length;a++){n=Zt.join(n,i[a]);let o;try{o=await wo.lstat(n)}catch(u){if(fC(u))return{exists:!1,kind:"missing"};throw u}let s=Zt.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${r.label} crosses a symbolic link or junction at ${s}`);let c=a===i.length-1;if(!c&&!o.isDirectory())throw new Error(`${r.label} ancestor ${s} must be a real directory`);if(c&&(r.expected==="file"&&!o.isFile()||r.expected==="directory"&&!o.isDirectory()||r.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${r.label} must be a real ${r.expected}`);let l=await wo.realpath(n);if(!Il(t,l))throw new Error(`${r.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function tr(e,t,i){let r=po(t,i.label),n=Zt.resolve(e),a=await Gh(n,i.label),o=r.split("/"),s=Zt.resolve(n,...o);if(!Il(n,s))throw new Error(`${i.label} must stay inside the project root`);let c=await Uh(n,a,o,i);return{projectRoot:n,target:s,relative:r,exists:c.exists,kind:c.kind}}async function ei(e,t,i,r){let n=await tr(e,t,{label:r.label,expected:"file"});if(!n.exists){let o=new Error(`${r.label} does not exist`);throw o.code="ENOENT",o}let a=await Gh(n.projectRoot,r.label);return Pi(n.target,i,{...r,verify:async(o,s)=>{if(!Il(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await Uh(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var wn=".comet/config.yaml";function hC(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function yo(e,t={}){return(await No(e,t)).document}async function mC(e){try{return(await ei(e,wn,mn,{label:wn})).bytes}catch(t){if(hC(t))return null;throw t}}function vC(e){return e?{exists:!0,sha256:pC("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function No(e,t={}){let i=await mC(e);return{document:i?vn(i.toString("utf8"),t):null,identity:vC(i)}}async function Tl(e){return(await yo(e))?.config??null}var p0=16*1024;import{existsSync as Yh,promises as ti}from"fs";import W from"path";import bC from"os";var bo=".comet/config.yaml",kC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function Ol(e){try{return await ti.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function SC(e){try{let t=await ti.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function rr(e,t){let i=W.relative(e,t);return i===""||!W.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${W.sep}`)}async function ir(e){let t=[],i=e;for(;!await Ol(i);){let n=W.dirname(i);if(n===i)break;t.push(W.basename(i)),i=n}let r=await ti.realpath(i);return W.resolve(r,...t.reverse())}async function Hl(e){try{return(await ti.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function ko(e){let t=W.resolve(e);try{(await ti.stat(t)).isDirectory()||(t=W.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let i=t,r=W.resolve(bC.homedir());for(;;){if(!(t===r&&i!==r)){let o=W.join(t,...bo.split("/")),s=t===i||await SC(o);if(await Ol(o)&&s)return t}if(await Ol(W.join(t,".git")))return t;let a=W.dirname(t);if(a===t)return i;t=a}}function So(e){return Ci(e)}async function EC(e,t){let i=So(t),r=W.resolve(e,...i.split("/")),n=await ti.realpath(e),a=await ir(r);if(!rr(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function Ri(e,t){let i=So(t),r=await EC(e,i),n=W.join(r,"comet");if(await Hl(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([ir(r),ir(n)]);if(!rr(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=W.resolve(e),c=W.join(s,".comet","runtime","native");if(await Hl(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([ti.realpath(s),ir(c)]);if(!rr(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:W.join(e,...bo.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:W.join(n,"specs"),changesDir:W.join(n,"changes"),archiveDir:W.join(n,"archive"),runtimeDir:c,changesRuntimeDir:W.join(c,"changes"),locksDir:W.join(c,"locks"),transactionsDir:W.join(c,"transactions")}}function Qh(e){if(!kC.test(e))throw new Error(`Invalid Native change name: ${e}`)}function ii(e,t){Qh(t);let i=W.join(e.changesRuntimeDir,t);if(!V(e.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function Zh(e,t){Qh(t);let i=W.join(e.changesDir,t,"runtime");if(!V(e.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function U(e,t){let i=ii(e,t);if(Yh(i))return i;let r=Zh(e,t);return Yh(r)?r:i}async function Xh(e){try{let t=await ti.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function Dl(e,t){let i=ii(e,t),r=Zh(e,t),[n,a]=await Promise.all([Xh(i),Xh(r)]);return n==="invalid"?{status:"invalid",layout:"project-local",path:i,message:"Native Runtime path must be a real directory"}:a==="invalid"?{status:"invalid",layout:"legacy",path:r,message:"Legacy Native Runtime path must be a real directory"}:n==="directory"&&a==="directory"?{status:"invalid",layout:"project-local",path:i,message:"Both project-local and legacy Native Runtime directories exist"}:n==="directory"?{status:"available",layout:"project-local",path:i}:a==="directory"?{status:"available",layout:"legacy",path:r}:{status:"missing",layout:"missing",path:i}}function ri(e,t){if(!t.startsWith("runtime/")||W.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let i=W.resolve(e,...t.slice(8).split("/"));if(!V(e,i))throw new Error(`Native Runtime ref escaped: ${t}`);return i}function ue(e,t){let i=W.resolve(t);if(V(e.runtimeDir,i))return e.runtimeDir;if(V(e.nativeRoot,i))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function V(e,t){return rr(W.resolve(e),W.resolve(t))}async function z(e,t){let i=W.resolve(e),r=W.resolve(t);if(!rr(i,r))throw new Error(`Path is outside the Native root: ${t}`);if(await Hl(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([ir(i),ir(r)]);if(!rr(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return r}var Bl=Ce;var Eo=ho;function xC(e="docs",t="en"){return mo(e,t)}async function Ie(e){let t=(await yo(e))?.config??null;return t?.native?t:null}async function Co(e){let t=await Ie(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function em(e){let t=await ko(e.startPath),i=await Ie(t);if(!i&&e.allowMissingConfig===!1)throw new Error(`${bo} was not found`);if(i?.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let r=e.explicitArtifactRoot?So(e.explicitArtifactRoot):void 0;if(i&&r&&r!==i.native.artifact_root)throw new Error(`Configured Native artifact root is ${i.native.artifact_root}; refusing conflicting root ${r}`);let n=i??xC(r??"docs"),a=await Ri(t,n.native.artifact_root);return{config:n,paths:a,configured:i!==null}}import{promises as nP}from"fs";import aP from"path";import{AsyncLocalStorage as PC}from"async_hooks";import{randomUUID as rm}from"crypto";import{promises as Be}from"fs";import nm from"os";import ye from"path";var tm=16*1024,am=".coordinator",RC=5e3,im=new PC,xo=new Map;function AC(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function _C(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let i=e;if(typeof i.id!="string"||i.id.length===0||typeof i.pid!="number"||!Number.isSafeInteger(i.pid)||i.pid<1||typeof i.hostname!="string"||i.hostname.length===0||typeof i.createdAt!="string"||i.createdAt.length===0||typeof i.operation!="string"||i.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return i}function om(e){return{device:e.dev.toString(),inode:e.ino.toString(),size:e.size.toString(),birthtimeNs:e.birthtimeNs.toString(),ctimeNs:e.ctimeNs.toString(),mtimeNs:e.mtimeNs.toString()}}function Po(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},r={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return _e(i,r)?q(i,r):q(i,r)&&e.size===t.size}function Ll(e,t){return Po(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function pt(e){let t,i;try{let r=await Pi(e,tm,{bigint:!0,label:"Native lock"});t=r.bytes,i=r.stat}catch(r){if(r.code==="ENOENT")return null;throw r instanceof Ze?r.reason==="too-large"?new Error(`Native lock metadata exceeds ${tm} bytes: ${e}`,{cause:r}):r.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:r}):new Error(`Native lock changed while reading: ${e}`,{cause:r}):r}return{file:e,owner:_C(JSON.parse(t.toString("utf8")),e),identity:om(i)}}async function IC(e){return(await pt(e))?.owner??null}function sm(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==nm.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=DC(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function TC(e,t){try{await Be.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await Be.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function Vl(e,t){let i=await pt(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Ll(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await Be.mkdir(t,{recursive:!0});let r=ye.join(t,`${ye.basename(e.file)}.${e.owner.id}.${rm()}.removed`);try{await Be.rename(e.file,r)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await pt(r);if(!n||n.owner.id!==e.owner.id||!Po(n.identity,e.identity))throw await TC(r,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await Be.rm(r,{force:!0}),"removed"}function cm(e){return{id:rm(),pid:process.pid,hostname:nm.hostname(),createdAt:new Date().toISOString(),operation:e}}async function lm(e,t){let i;try{i=await Be.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await IC(e);throw new Error(`Native lock is already held: ${e}${o?` by pid ${o.pid} for ${o.operation}`:""}`,{cause:a})}throw a}let r;try{await i.writeFile(JSON.stringify(t,null,2)+`
146
+ `,"utf8"),await i.sync(),r=om(await i.stat({bigint:!0}))}finally{await i.close()}let n=await pt(e);if(!r||!n||n.owner.id!==t.id||!Po(n.identity,r))throw new Error(`Native lock changed after write: ${e}`);return n.identity}async function jC(e,t){let i=await z(e.runtimeDir,e.locksDir);await Be.mkdir(i,{recursive:!0});let r=await z(e.runtimeDir,ye.join(i,am));await Be.mkdir(r,{recursive:!0});let n=cm(t),a=ye.join(r,`.${n.id}.tmp`),o=ye.join(r,`${n.id}.claim`);try{let s=await lm(a,n);await Be.rename(a,o);let c=await pt(o);if(!c||!Po(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:i,owner:n,identity:c.identity}}finally{await Be.rm(a,{force:!0})}}async function $C(e){let t=ye.dirname(e.file),i=!1,r=ye.basename(e.file);for(let n of await Be.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=ye.join(t,n.name);if(ye.resolve(a)!==ye.resolve(e.file))try{let o=await pt(a),s=sm(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Vl(o,t);continue}n.name<r&&(i=!0)}catch{n.name<r&&(i=!0)}}return i}async function um(e){let t=await pt(e.file);if(t){if(t.owner.id!==e.owner.id||!Ll(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await Vl(t,ye.dirname(e.file))}}async function OC(e,t){let i=Date.now()+RC;for(;;){let r=await jC(e,t);if(!await $C(r))return r;if(await um(r),Date.now()>=i)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function HC(e){let t=xo.get(e)??Promise.resolve(),i,r=new Promise(a=>{i=a}),n=t.then(()=>r);return xo.set(e,n),await t,()=>{i(),xo.get(e)===n&&xo.delete(e)}}async function dm(e,t,i){let r=ye.resolve(e.locksDir),n=im.getStore();if(n?.has(r))return i();let a=await HC(r);try{let o=await OC(e,t),s=new Map(n??[]);return s.set(r,o),await im.run(s,async()=>{try{return await i()}finally{await um(o)}})}finally{a()}}async function Ro(e,t,i){return dm(e,`acquire ${t}`,async()=>{let r=await z(e.runtimeDir,e.locksDir);await Be.mkdir(r,{recursive:!0});let n=await z(e.runtimeDir,ye.join(r,AC(t))),a=cm(i),o=await lm(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:r,owner:a,identity:o}})}async function Ao(e){await pt(e.file)&&await dm({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${ye.basename(e.file)}`,async()=>{let t=await pt(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Ll(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=ye.join(e.locksDir,am);await Vl(t,i)})}function DC(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function fm(e){return sm(await pt(e))}import Tx from"node:path";import pm from"node:path";import{createHash as BC}from"crypto";function et(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function LC(e,t){t.has(e)&&et("cyclic structures are not supported"),t.add(e);try{let i=Object.keys(e);for(let r=0;r<e.length;r+=1)Object.prototype.hasOwnProperty.call(e,r)||et("sparse arrays are not supported");return(i.length!==e.length||i.some((r,n)=>r!==String(n)))&&et("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&et("symbol properties are not supported"),`[${e.map(r=>Fl(r,t)).join(",")}]`}finally{t.delete(e)}}function VC(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&et("only plain objects are supported"),t.has(e)&&et("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&et("symbol properties are not supported"),t.add(e);try{let r=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=r[o];return(!s||!("value"in s))&&et("accessor properties are not supported"),`${JSON.stringify(o)}:${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)||et("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?LC(e,t):VC(e,t);case"bigint":case"function":case"symbol":case"undefined":return et(`${typeof e} values are not supported`)}return et("unsupported value type")}function Nn(e){return Fl(e,new Set)}function H(e,t){if(e.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(e))throw new TypeError("Canonical hash tag must not contain a line break");return BC("sha256").update(`${e}
147
+ ${Nn(t)}`).digest("hex")}var FC="comet.native.acceptance.v1",qC=/^acceptance-[a-f0-9]{64}$/u,MC=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),WC=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,zC=/^[a-f0-9]{64}$/u,JC=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function GC(e,t){return e<t?-1:e>t?1:0}var xt=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),bn=Object.freeze({maxCriteria:1024}),hm="<!-- comet-native:acceptance-evidence:start -->",mm="<!-- comet-native:acceptance-evidence:end -->";function vm(e,t){if(Buffer.byteLength(e,"utf8")<=t)return{value:e,truncated:!1};let i="",r=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(r+a>t)break;i+=n,r+=a}return{value:i,truncated:!0}}function gm(e,t){let i=t.toString(36),r=H("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${i}.${r}`}function UC(e){if(!zC.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=JC.exec(e.cursor);if(!t)throw new Error("Native acceptance cursor is invalid");if(t[1]!==e.acceptanceHash)throw new Error("Native acceptance cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native acceptance cursor offset is invalid");if(t[3]!==H("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:i}))throw new Error("Native acceptance cursor integrity check failed");return i}function KC(e,t){let i=vm(e.text,xt.maxTextBytes),r=e.context.slice(0,xt.maxContextItems).map(n=>vm(n,xt.maxContextItemBytes));return{id:e.id,kind:e.kind,source:e.source,context:r.map(n=>n.value),text:i.value,contextTruncated:e.context.length>r.length||r.some(n=>n.truncated),textTruncated:i.truncated,verificationStatus:t}}function ym(e){let t=UC({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),i=[],r=[...new Set(e.failedCheckIds??[])].sort(GC),n=r.slice(0,xt.maxFailedCheckIds),a=e.criteria.slice(t,t+xt.maxItems);for(let c of a){let l=[...i,KC(c,e.verificationStatuses?.get(c.id)??"unverified")],u=t+l.length,d={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:l,failedAcceptanceIds:l.filter(f=>f.verificationStatus==="failed").map(f=>f.id),missingAcceptanceIds:l.filter(f=>f.verificationStatus==="missing").map(f=>f.id),failedCheckIds:n,failedCheckIdsTruncated:r.length>n.length,nextCursor:u<e.criteria.length?gm(e.acceptanceHash,u):null,limits:{...xt}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>xt.maxSerializedBytes){if(i.length===0)throw new Error("Native acceptance criterion exceeds the page serialization budget");break}i.push(l.at(-1))}if(e.criteria.length>0&&i.length===0)throw new Error("Native acceptance page could not project its next criterion");let o=t+i.length,s={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:i,failedAcceptanceIds:i.filter(c=>c.verificationStatus==="failed").map(c=>c.id),missingAcceptanceIds:i.filter(c=>c.verificationStatus==="missing").map(c=>c.id),failedCheckIds:n,failedCheckIdsTruncated:r.length>n.length,nextCursor:o<e.criteria.length?gm(e.acceptanceHash,o):null,limits:{...xt}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>xt.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function Ml(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 ql(e,t){let i=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!i)return t;let r=i[1][0];return t===null?{marker:r,length:i[1].length}:r===t.marker&&i[1].length>=t.length&&i[2].trim().length===0?null:t}function wm(e){return e.includes("-->")||e.includes("--!>")}function*nr(e){let t=null,i=!1,r=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
148
148
  `),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
149
- `,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!i&&r===null,index:s},s+=1,t!==null)t=ql(l,t);else if(i)wm(l)&&(i=!1);else if(r!==null)new RegExp(`</${r}\\s*>`,"iu").test(l)&&(r=null);else{let d=ql(l,null);if(d!==null)t=d;else{let f=l.trimStart();if(f.startsWith("<!--")&&!wm(f))i=!0;else{let p=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(f);p&&n.has(p[1].toLowerCase())&&!f.startsWith("</")&&!f.endsWith("/>")&&!new RegExp(`</${p[1]}\\s*>`,"iu").test(f)&&(r=p[1])}}}if(c===-1)break;o=c+1}}function UC(e){return[...nr(e)].map(({line:t,body:i})=>({line:t,body:i}))}function _o(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function KC(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function Wl(e,t,i,r=[],n="content-hash"){let a=_o(i),o=t.replaceAll("\\","/").trim(),s=r.map(_o);if(a.length===0)throw new Error(`${e} acceptance criterion must not be empty`);if(o.length===0)throw new Error(`${e} acceptance criterion source must not be empty`);return{id:n==="content-hash"?`acceptance-${H(LC,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function zl(e,t,i="content-hash"){let r=new Set;for(let n of e){let a=i==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(r.has(a))throw new Error(`${t} contains duplicate acceptance criteria`);r.add(a)}return e}function YC(e){let t=null,i=null,r=0,n=0;for(let{line:a,body:o,index:s}of nr(e)){n=s+1;let c=o?Ml(a):null;c?.level===1&&(oa(c.text)==="acceptanceExamples"?(r+=1,r===1&&(t=s+1)):t!==null&&i===null&&(i=s))}if(r===0||t===null)return null;if(r!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:i??n}}function Jl(e,t="brief.md",i=bn.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native brief acceptance budget is invalid");let n=YC(e);if(n===null)return[];let a=null;for(let{line:l,body:u,index:d}of nr(e)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(f===null)continue;let p=f[1].length;a=a===null?p:Math.min(a,p)}let o=[],s=null,c=()=>{if(s!==null){if(o.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);o.push(s)}};for(let{line:l,body:u,index:d}of nr(e)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;f&&f[1].length===a?(c(),s=[f[2]]):s!==null&&s.push(l)}return c(),zl(o.map(l=>Wl("brief-example",t,l.join(`
149
+ `,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!i&&r===null,index:s},s+=1,t!==null)t=ql(l,t);else if(i)wm(l)&&(i=!1);else if(r!==null)new RegExp(`</${r}\\s*>`,"iu").test(l)&&(r=null);else{let d=ql(l,null);if(d!==null)t=d;else{let f=l.trimStart();if(f.startsWith("<!--")&&!wm(f))i=!0;else{let p=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(f);p&&n.has(p[1].toLowerCase())&&!f.startsWith("</")&&!f.endsWith("/>")&&!new RegExp(`</${p[1]}\\s*>`,"iu").test(f)&&(r=p[1])}}}if(c===-1)break;o=c+1}}function YC(e){return[...nr(e)].map(({line:t,body:i})=>({line:t,body:i}))}function _o(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function XC(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function Wl(e,t,i,r=[],n="content-hash"){let a=_o(i),o=t.replaceAll("\\","/").trim(),s=r.map(_o);if(a.length===0)throw new Error(`${e} acceptance criterion must not be empty`);if(o.length===0)throw new Error(`${e} acceptance criterion source must not be empty`);return{id:n==="content-hash"?`acceptance-${H(FC,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function zl(e,t,i="content-hash"){let r=new Set;for(let n of e){let a=i==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(r.has(a))throw new Error(`${t} contains duplicate acceptance criteria`);r.add(a)}return e}function QC(e){let t=null,i=null,r=0,n=0;for(let{line:a,body:o,index:s}of nr(e)){n=s+1;let c=o?Ml(a):null;c?.level===1&&(oa(c.text)==="acceptanceExamples"?(r+=1,r===1&&(t=s+1)):t!==null&&i===null&&(i=s))}if(r===0||t===null)return null;if(r!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:i??n}}function Jl(e,t="brief.md",i=bn.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native brief acceptance budget is invalid");let n=QC(e);if(n===null)return[];let a=null;for(let{line:l,body:u,index:d}of nr(e)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(f===null)continue;let p=f[1].length;a=a===null?p:Math.min(a,p)}let o=[],s=null,c=()=>{if(s!==null){if(o.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);o.push(s)}};for(let{line:l,body:u,index:d}of nr(e)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;f&&f[1].length===a?(c(),s=[f[2]]):s!==null&&s.push(l)}return c(),zl(o.map(l=>Wl("brief-example",t,l.join(`
150
150
  `),[],r)),"Brief",r)}function Gl(e,t="spec.md",i=bn.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=()=>{if(o!==null){if(n.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);n.push(Wl("spec-scenario",t,[o.title,...o.body].join(`
151
- `),o.context,r)),o=null}};for(let{line:c,body:l}of nr(e)){let u=l?Ml(c):null,d=u?/^Scenario\s*:\s*(.*)$/iu.exec(u.text):null;if(d){for(s();a.at(-1)&&a.at(-1).level>=u.level;)a.pop();let f=_o(d[1]);if(f.length===0)throw new Error("Scenario title must not be empty");o={level:u.level,title:f,body:[],context:a.map(p=>p.text)}}else if(u){for(o!==null&&u.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=u.level;)a.pop();a.push(u)}else o!==null&&l&&o.body.push(c)}return s(),zl(n,"Specification",r)}function Nm(e,t="spec.md",i=bn.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=null,c=()=>{if(s!==null){if(n.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);n.push(Wl("spec-must",t,s.parts.join(" "),s.context,r)),s=null}},l=()=>a.some(u=>/^(?:non-?goals?|非目标)$/iu.test(u.text.trim()));for(let{line:u,body:d}of nr(e)){let f=d?Ml(u):null;if(f){for(c(),o!==null&&f.level<=o&&(o=null);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f),/^Scenario\s*:/iu.test(f.text)&&(o=f.level);continue}let p=u.trim();if(!d||o!==null||l()){c();continue}if(p.length===0||ql(u,null)!==null||p.startsWith("<!--")||p==="-->"||p==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(p)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(p)||/^(?:[-*_]\s*){3,}$/u.test(p)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(p)){c();continue}let v=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(u);if(v){c(),s={parts:[v[1]],context:a.map(h=>h.text)};continue}if(/^\|.*\|$/u.test(p)){c(),s={parts:[p],context:a.map(h=>h.text)},c();continue}s===null?s={parts:[p],context:a.map(h=>h.text)}:s.parts.push(p)}return c(),zl(n,"Specification mandatory requirements",r)}function XC(e,t){let i=e.trim().replaceAll("\\","/");if(i.length===0||KC(i)||pm.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~|[A-Za-z][A-Za-z0-9+.-]*:)/u.test(i)||i.split("/").includes(".."))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);let r=pm.posix.normalize(i);if(r==="."||r===".."||r.startsWith("../"))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);if(r.split("/").some(n=>n.toLowerCase()===".git"||n.toLowerCase().startsWith(".env")))throw new Error(`Acceptance evidence ${t} references sensitive content`);if(!qC.test(r))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return r}function QC(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`Acceptance evidence entry ${t} must be an object`);let i=e,r=Object.keys(i).filter(n=>!FC.has(n));if(r.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${r.join(", ")}`);return i}function bm(e){if(!Array.isArray(e))throw new Error("Native acceptance evidence block must be a JSON array");let t=new Set;return e.map((i,r)=>{let n=QC(i,r),a=n.acceptance_id;if(typeof a!="string"||!VC.test(a))throw new Error(`Acceptance evidence entry ${r} has an invalid acceptance_id`);if(t.has(a))throw new Error(`Native acceptance evidence has duplicate acceptance_id: ${a}`);if(t.add(a),!Array.isArray(n.evidence_refs))throw new Error(`Acceptance evidence ${a} requires an evidence_refs array`);let o=n.evidence_refs.map(l=>{if(typeof l!="string"||l.trim().length===0)throw new Error(`Acceptance evidence ${a} has a non-empty string requirement`);return XC(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 km(e){let t=UC(e);if(t.some(({line:l,body:u})=>!u&&(l===hm||l===mm)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let r=t.flatMap(({line:l,body:u},d)=>u&&l===hm?[d]:[]),n=t.flatMap(({line:l,body:u},d)=>u&&l===mm?[d]:[]);if(r.length!==1||n.length!==1)throw new Error("Verification must contain exactly one Native acceptance evidence block");if(r[0]>=n[0])throw new Error("Native acceptance evidence markers are out of order");let a=t.slice(r[0]+1,n[0]).map(({line:l})=>l).join(`
152
- `).trim();if(a.length===0)throw new Error("Native acceptance evidence block is empty");let o;try{o=JSON.parse(a)}catch(l){throw new Error(`Native acceptance evidence block is invalid JSON: ${l.message}`,{cause:l})}let s=bm(o),c=ZC(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function ZC(e){let t=bm([...e]).map(i=>({...i,evidence_refs:[...i.evidence_refs].sort()})).sort((i,r)=>i.acceptance_id.localeCompare(r.acceptance_id));return JSON.stringify(t,null,2)}var Kl=Or(Xi(),1);import{promises as tx}from"node:fs";var kn="comet.native.v4",Io="comet.native.local-execution.v4";var Sm=["multi-session","single-session"];var ix=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,rx=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,nx=/^A[1-9][0-9]*$/u,ax=/^[a-f0-9]{64}$/u,ox=new Set(["schema","name","language","phase","status","state_version","brief","shape_confirmation_hash","children_contract_hash","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]);function Ne(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function be(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function de(e,t,i){if(typeof e!="string"||!i?.empty&&e.length===0)throw new Error(`${t} must be ${i?.empty?"a string":"a non-empty string"}`);return e}function Ul(e,t){return e===null?null:de(e,t)}function Cm(e,t){let i=de(e,t);if(!ax.test(i))throw new Error(`${t} must be a SHA-256 hash`);return i}function ar(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function ie(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function sx(e,t){return e===null?null:ie(e,t,Number.MIN_SAFE_INTEGER)}function ae(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function ht(e,t,i){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,n)=>i(r,n))}function To(e,t){return ht(e,t,(i,r)=>de(i,`${t}[${r}]`))}function Ai(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function or(e,t){let i=de(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO date or timestamp`);return i}function Yl(e,t,i=!1){let r=de(e,t);if(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").includes("..")||!i&&(r==="."||r.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return r}function Le(e,t){let i=Ne(e,t);return be(i,new Set(["text","truncated"]),t),{text:de(i.text,`${t}.text`,{empty:!0}),truncated:ar(i.truncated,`${t}.truncated`)}}function cx(e,t){let i=`Native spec_changes[${t}]`,r=Ne(e,i);be(r,new Set(["capability","operation","source"]),i);let n=de(r.capability,`${i}.capability`);if(!rx.test(n))throw new Error(`${i}.capability is invalid`);let a=ae(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:Yl(r.source,`${i}.source`);if(a==="remove"&&o!==null)throw new Error(`${i} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${i} ${a} requires a source`);return{capability:n,operation:a,source:o}}function lx(e){let t="Native workspace",i=Ne(e,t);be(i,new Set(["isolation","change_branch","target_branch","finish"]),t);let r=ae(i.isolation,["current","branch","worktree"],`${t}.isolation`),n=Ul(i.change_branch,`${t}.change_branch`),a=Ul(i.target_branch,`${t}.target_branch`),o=i.finish===null?null:ae(i.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(r==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(r==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(r!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:r,change_branch:n,target_branch:a,finish:o}}function ux(e){let t="Native loop",i=Ne(e,t);be(i,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let r=To(i.previous_unresolved_ids,`${t}.previous_unresolved_ids`);Ai(r,`${t}.previous_unresolved_ids`);let n=i.stop_reason===void 0?void 0:ae(i.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:ae(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:ie(i.goal_cycle,`${t}.goal_cycle`,1),iteration:ie(i.iteration,`${t}.iteration`),attempt:ie(i.attempt,`${t}.attempt`),retry_epoch:ie(i.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:ie(i.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:ie(i.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:ie(i.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:r,next_action:Ul(i.next_action,`${t}.next_action`)}}function dx(e,t){let i=`Native acceptance[${t}]`,r=Ne(e,i);be(r,new Set(["id","source","text","result","reason"]),i);let n=de(r.id,`${i}.id`);if(!nx.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:Yl(r.source,`${i}.source`),text:de(r.text,`${i}.text`),result:ae(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:Le(r.reason,`${i}.reason`)}}function fx(e,t){let i=`Native builder_handoff.checks[${t}]`,r=Ne(e,i);return be(r,new Set(["name","result","note"]),i),{name:Le(r.name,`${i}.name`),result:ae(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:Le(r.note,`${i}.note`)}}function px(e){let t="Native builder_handoff",i=Ne(e,t);be(i,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let r=To(i.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);Ai(r,`${t}.addressed_acceptance_ids`);let n=i.review===null||i.review===void 0?null:Ne(i.review,`${t}.review`);return n&&be(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:de(i.candidate_id,`${t}.candidate_id`),identity_provider:de(i.identity_provider,`${t}.identity_provider`),builder_execution_ref:de(i.builder_execution_ref,`${t}.builder_execution_ref`),iteration:ie(i.iteration,`${t}.iteration`,1),summary:Le(i.summary,`${t}.summary`),addressed_acceptance_ids:r,checks:ht(i.checks,`${t}.checks`,fx),checks_truncated:ar(i.checks_truncated,`${t}.checks_truncated`),known_limits:ht(i.known_limits,`${t}.known_limits`,(a,o)=>Le(a,`${t}.known_limits[${o}]`)),known_limits_truncated:ar(i.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:ae(n.status,["passed"],`${t}.review.status`),summary:Le(n.summary,`${t}.review.summary`),reviewer_execution_ref:de(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:or(i.submitted_at,`${t}.submitted_at`)}}function hx(e,t){let i=`Native blockers[${t}]`,r=Ne(e,i);be(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=To(r.acceptance_ids,`${i}.acceptance_ids`);return Ai(n,`${i}.acceptance_ids`),{owner:ae(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:Le(r.reason,`${i}.reason`),acceptance_ids:n,resolution_action:ae(r.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${i}.resolution_action`)}}function mx(e,t){let i=`Native verification.checks[${t}]`,r=Ne(e,i);return be(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:de(r.id,`${i}.id`),name:Le(r.name,`${i}.name`),argv_display:ht(r.argv_display,`${i}.argv_display`,(n,a)=>Le(n,`${i}.argv_display[${a}]`)),argv_truncated:ar(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:Yl(r.cwd_ref,`${i}.cwd_ref`,!0),status:ae(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:sx(r.exit_code,`${i}.exit_code`),duration_ms:ie(r.duration_ms,`${i}.duration_ms`)}}function vx(e){let t="Native verification",i=Ne(e,t);be(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let r=ht(i.checks,`${t}.checks`,mx);Ai(r.map(a=>a.id),`${t}.checks IDs`);let n=de(i.identity_provider,`${t}.identity_provider`);return{candidate_id:de(i.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:de(i.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:ie(i.iteration,`${t}.iteration`,1),attempt:ie(i.attempt,`${t}.attempt`,1),assurance:i.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":ae(i.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:ae(i.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:r,summary:Le(i.summary,`${t}.summary`),risks:ht(i.risks,`${t}.risks`,(a,o)=>Le(a,`${t}.risks[${o}]`)),risks_truncated:ar(i.risks_truncated,`${t}.risks_truncated`),completed_at:or(i.completed_at,`${t}.completed_at`)}}function gx(e,t){let i=`Native history[${t}]`,r=Ne(e,i);be(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=To(r.unresolved_ids,`${i}.unresolved_ids`);return Ai(n,`${i}.unresolved_ids`),{goal_cycle:ie(r.goal_cycle,`${i}.goal_cycle`,1),iteration:ie(r.iteration,`${i}.iteration`),attempt:ie(r.attempt,`${i}.attempt`),outcome:ae(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:Le(r.summary,`${i}.summary`),completed_at:or(r.completed_at,`${i}.completed_at`)}}function wx(e){let t="Native history_overflow.outcome_counts",i=Ne(e,t),r=["pass","fail","blocked","execution-error","recovery"];return be(i,new Set(r),t),{pass:ie(i.pass,`${t}.pass`),fail:ie(i.fail,`${t}.fail`),blocked:ie(i.blocked,`${t}.blocked`),"execution-error":ie(i["execution-error"],`${t}.execution-error`),recovery:ie(i.recovery,`${t}.recovery`)}}function yx(e){let t="Native history_overflow",i=Ne(e,t);be(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let r=ie(i.dropped_entries,`${t}.dropped_entries`),n=i.first_dropped_at===null?null:or(i.first_dropped_at,`${t}.first_dropped_at`),a=i.last_dropped_at===null?null:or(i.last_dropped_at,`${t}.last_dropped_at`);if(r===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(r>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=wx(i.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==r)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:r,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function Nx(e){let t=new Set(e.acceptance.map(i=>i.id));for(let i of e.loop.previous_unresolved_ids)if(!t.has(i))throw new Error(`Native loop references unknown acceptance ID ${i}`);for(let i of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(i))throw new Error(`Native builder handoff references unknown ID ${i}`);for(let i of e.blockers)for(let r of i.acceptance_ids)if(!t.has(r))throw new Error(`Native blocker references unknown ID ${r}`);if(e.builder_handoff){if(!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let r=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!r&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function bx(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let i=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(i!==null&&e.loop.stage!==i)throw new Error(`Native status ${e.status} requires loop stage ${i}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(r=>r.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(r=>r.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function Sn(e){let t=Ne(e,"Native portable state");if(be(t,ox,"Native portable state"),t.schema!==kn)throw new Error(`Native portable state schema must be ${kn}`);let i=de(t.name,"Native state name");if(!ix.test(i))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let r=ht(t.spec_changes,"Native spec_changes",cx);Ai(r.map(s=>s.capability),"Native spec change capabilities");let n=ht(t.acceptance,"Native acceptance",dx);Ai(n.map(s=>s.id),"Native acceptance IDs");let a=ht(t.history,"Native history",gx);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:kn,name:i,language:ae(t.language,["en","zh-CN"],"Native state language"),phase:ae(t.phase,["shape","build","verify","archive"],"Native state phase"),status:ae(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:ie(t.state_version,"Native state_version",1),brief:"brief.md",...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:Cm(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:Cm(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:ae(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:r,workspace:lx(t.workspace),loop:ux(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:px(t.builder_handoff),blockers:ht(t.blockers,"Native blockers",hx),verification:t.verification===null?null:vx(t.verification),history:a,history_overflow:yx(t.history_overflow),verification_result:ae(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:ae(t.verification_report,["verification.md"],"Native verification_report"),archived:ar(t.archived,"Native archived"),created_at:or(t.created_at,"Native created_at")};return Nx(o),bx(o),o}function kx(e,t){let i=(0,Kl.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`${t} is invalid YAML: ${i.errors[0].message}`);return i.toJS({mapAsMap:!1})}async function En(e){let t=await tx.readFile(e,"utf8");return Sn(kx(t,"Native portable state"))}var Pt="comet.native.v3",Rt="comet.native.v2",At="comet.native.v1",sr="comet.native.transition.v3",cr="comet.native.transition.v2",Cn="comet.native.transition.v1";var xm="comet.native.portable-migration.v1",Sx=new Set(["schema","id","change","fromSchema","status","createdAt"]),Ex=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Cx=/^[a-z0-9][a-z0-9-]{7,127}$/u,xx=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),Px=new Set([At,Rt,Pt]);function Rx(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ax(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function Rm(e){let t=Rx(e,"Native portable migration transaction"),i=Object.keys(t).filter(r=>!Sx.has(r));if(i.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${i.join(", ")}`);if(t.schema!==xm)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!Cx.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!Ex.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!Px.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!xx.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:xm,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:Ax(t.createdAt,"Native portable migration transaction createdAt")}}var Am="comet.native.archive-transaction.v4",_m="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",Ix=new RegExp(`^portable-archive-(${_m})\\.json$`,"u"),Tx=new RegExp(`^portable-migration-(${_m})\\.json$`,"u"),jx=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,$x=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Ox=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),Hx=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),Dx=new Set(["capability","operation","source","content"]),Im=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Tm(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function jm(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(Object.keys(e).length!==t.size)throw new Error(`${i} fields are invalid`)}function Bx(e,t){let i=`Native portable Archive spec_changes[${t}]`,r=Tm(e,i);if(jm(r,Dx,i),typeof r.capability!="string"||!Im.test(r.capability))throw new Error(`${i}.capability is invalid`);if(!["create","modify","remove"].includes(String(r.operation)))throw new Error(`${i}.operation is invalid`);let n=r.operation;if(n==="remove"){if(r.source!==null||r.content!==null)throw new Error(`${i} remove requires source and content null`);return{capability:r.capability,operation:n,source:null,content:null}}if(typeof r.source!="string"||r.source.length===0||r.source.includes("\\")||r.source.startsWith("/")||/^[A-Za-z]:/u.test(r.source)||r.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${i}.${n} source is invalid`);if(typeof r.content!="string")throw new Error(`${i}.${n} content is invalid`);return{capability:r.capability,operation:n,source:r.source,content:r.content}}function Lx(e){let t=Tm(e,"Native portable Archive transaction");if(jm(t,Hx,"Native portable Archive transaction"),t.schema!==Am)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!jx.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Im.test(t.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(t.start_state_version)||Number(t.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof t.archive_ref!="string"||!$x.test(t.archive_ref)||!t.archive_ref.endsWith(`-${t.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof t.status!="string"||!Ox.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let i=t.spec_changes.map(Bx);if(new Set(i.map(({capability:n})=>n)).size!==i.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>i.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let r=new Date(t.created_at);if(Number.isNaN(r.valueOf())||r.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:Am,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:i,created_at:t.created_at}}function Xl(e){let t=Ix.exec(e);if(t)return{kind:"archive",change:t[1]};let i=Tx.exec(e);return i?{kind:"migration",change:i[1]}:null}async function $m(e,t){let i=Xl(t);if(!i)return null;let r=await re({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(r.text),a=_x.join(e.transactionsDir,t);if(i.kind==="archive"){let s=Lx(n);if(s.change!==i.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:i.change,file:a,journal:s}}let o=Rm(n);if(o.change!==i.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:i.change,file:a,journal:o}}function Om(e){return e.kind==="archive"||e.journal.status!=="committed"}import It from"path";import{TextDecoder as Jx}from"util";import{createHash as Vx}from"node:crypto";import{constants as jo,promises as Te}from"node:fs";import tt from"node:path";import{TextDecoder as Fx}from"node:util";function Oo(e,t){let i=tt.relative(e,t);return i===""||!tt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${tt.sep}`)}function Hm(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function qx(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Mx(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function $o(e,t){return q({...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 Ql(e,t){let i=await Te.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await Te.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function Dm(e,t,i){let r=tt.resolve(e),n=tt.resolve(t);if(!Oo(r,n))throw new Error(`${i} is outside its managed root`);let a=[await Ql(r,i)],o=r;for(let s of tt.relative(r,n).split(tt.sep).filter(Boolean)){await _t(a,i),o=tt.join(o,s);let c=await Ql(o,i);if(!Oo(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await _t(a,i),a}async function _t(e,t){for(let i of e){let r=await Te.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!qx(i,r)||await Te.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function Wx(e,t,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${i} exceeds ${t} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function mt(e){let t=Hm(e.maxBytes),i=tt.resolve(e.file),r=await Dm(e.root,tt.dirname(i),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>Ql(tt.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await _t(r,e.label);let a=await Te.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=Mx(a),s=await Te.realpath(i);if(!Oo(r[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>Oo(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?jo.O_RDONLY:jo.O_RDONLY|jo.O_NOFOLLOW|jo.O_NONBLOCK,l=await Te.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([Te.lstat(i),Te.realpath(i)]);if(await _t(r,e.label),await _t(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!$o(o,u)||!$o(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await Wx(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([l.stat(),Te.lstat(i),Te.realpath(i)]);if(await _t(r,e.label),await _t(n,e.label),!h.isFile()||h.isSymbolicLink()||m!==s||!$o(o,v)||!$o(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:Vx("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function Bm(e){let t=await mt(e),i;try{i=new Fx("utf-8",{fatal:!0}).decode(t.bytes)}catch(r){throw new Error(`${e.label} is not valid UTF-8`,{cause:r})}return{...t,text:i}}async function xn(e){let t=await Dm(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await Te.readdir(e.directory,{withFileTypes:!0});else{let r=Hm(e.maxEntries);i=[];let n=await Te.opendir(e.directory);try{for await(let a of n)if(i.push(a),i.length>r)throw new Error(`${e.label} exceeds ${r} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await _t(t,e.label),{entries:i,verify:()=>_t(t,e.label)}}var Gx=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),Ux=new Set(["id","type","source","target","staged","backup"]),Kx=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),Yx=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var Fm=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var Xx=256*1024,_H=1024*1024,IH=16*1024;var TH=64*1024*1024;var Qx=new Jx("utf-8",{fatal:!0});function Do(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Bo(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function qm(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Zl(e,t){if(typeof e!="string"||e.length===0||It.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Ho(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function Lm(e,t){if(Zl(e,t),e.includes("\\")||e!==It.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function Zx(e,t){let i=Do(e,`transaction operations[${t}]`);if(Bo(i,Ux,`transaction operations[${t}]`),typeof i.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.id))throw new Error(`transaction operations[${t}].id is invalid`);if(i.type!=="write"&&i.type!=="remove"&&i.type!=="move")throw new Error(`transaction operation ${i.id} has an invalid type`);Zl(i.target,`transaction operation ${i.id} target`);for(let r of["source","staged","backup"])i[r]!==void 0&&Zl(i[r],`transaction operation ${i.id} ${r}`);if(i.type==="write"){if(i.staged===void 0||i.source!==void 0)throw new Error(`write operation ${i.id} requires staged and forbids source`)}else if(i.type==="remove"){if(i.source!==void 0||i.staged!==void 0)throw new Error(`remove operation ${i.id} forbids source and staged`)}else if(i.source===void 0||i.staged!==void 0||i.backup!==void 0)throw new Error(`move operation ${i.id} requires source and forbids staged and backup`);return i}function Mm(e){let t=Do(e,"Native Archive transaction journal");if(Bo(t,Kx,"Native Archive transaction journal"),t.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native Archive transaction id is invalid");if(t.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof t.status!="string"||!Fm.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!qm(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Ho(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let i=t.operations.map((s,c)=>{let l=Do(s,`Archive transaction operations[${c}]`);if(Bo(l,Yx,`Archive transaction operations[${c}]`),typeof l.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(l.id))throw new Error(`Archive transaction operations[${c}].id is invalid`);if(l.type!=="write"&&l.type!=="remove"&&l.type!=="move")throw new Error(`Archive transaction operation ${l.id} has an invalid type`);Lm(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&Lm(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&Ho(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(Ho(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);Ho(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),r=i.map(s=>s.id);if(new Set(r).size!==r.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=i.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||i.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of i.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:i}}function eP(e){let t=Do(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Mm(t);if(Bo(t,Gx,"Native transaction journal"),t.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native transaction id is invalid");if(t.kind!=="archive"&&t.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof t.status!="string"||!Fm.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!It.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!It.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!qm(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let i=t.operations.map(Zx),r=i.map(n=>n.id);if(new Set(r).size!==r.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:i}}function tP(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return It.join(e.transactionsDir,t)}function Wm(e,t){let i=tP(e,t);return{directory:i,journal:It.join(i,"transaction.json"),events:It.join(i,"events.jsonl"),staged:It.join(i,"staged"),backups:It.join(i,"backups")}}async function eu(e,t){let i=Wm(e,t);return await Promise.all(Object.values(i).map(r=>z(e.runtimeDir,r))),i}async function tu(e,t,i={}){let r=await eu(e,t),n=await mt({root:e.runtimeDir,file:r.journal,maxBytes:Xx,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(Qx.decode(n.bytes)),o=eP(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function nP(e,t,i){let r;try{r=await iP.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await tu(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of r)if(Xl(n.name))try{let a=await $m(e,n.name);if(!a||i?.kind===a.kind&&i.change===a.change)continue;if(Om(a))return!0}catch{return!0}return!1}async function aP(e,t){let i=Date.now()+5e3,r=rP.join(e.locksDir,"root-move.lock");for(;;)try{return await Ro(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await fm(r);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=i)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function it(e,t,i,r){let n=await aP(e,t);try{if(await Co(e.projectRoot),await nP(e,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await Ao(n)}}import{createHash as Mo}from"crypto";import{spawn as ev}from"node:child_process";import{promises as X}from"fs";import D from"path";import{createHash as zm}from"crypto";import{createReadStream as oP}from"fs";async function iu(e){let t=zm("sha256");for await(let i of oP(e))t.update(i);return t.digest("hex")}function K(e){return zm("sha256").update(e).digest("hex")}var Lo={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},cu=1e3,sP=8*1024*1024,cP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,lP=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),uP=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),dP=new Set(["schema","include","exclude","hash"]),fP=new Set(["provider","gitSelection","physicalSelection","projection"]),pP=new Set(["provider","selection"]),hP=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),mP=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),vP=new Set(["schema","status","before","after"]),gP=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),wP=new Set(["path","hash","size","type","gitObjectId"]),yP=new Set(["path","size","type","reason"]),NP=new Set(["ref","hash","count"]),bP=new Set(["change-created","legacy-migration","explicit"]),kP=new Set(["file","directory","other"]),SP=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"]),Wo=/^[a-f0-9]{64}$/u,tv=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,EP=new Set(["EACCES","EPERM"]),mr=64*1024,ou=64*1024,CP=6e4,xP=1e3,PP=2,lu={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},RP={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function iv(e){let t=e.deadlineMs??CP;if(!Number.isSafeInteger(t)||t<1)throw new Error("Native snapshot execution budget must be a positive integer");return{deadlineAt:Date.now()+t,gitProcess:e.gitProcess??{command:"git"}}}function rt(e){return Math.max(0,e.deadlineAt-Date.now())}function j(e){return rt(e)>=1}function ru(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 pr(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function AP(e){let t={...RP,...e};if(!Number.isSafeInteger(t.maxNodes)||t.maxNodes<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxPathBytes)||t.maxPathBytes<1||t.maxPathBytes>t.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return t}async function _P(e,t){if(t.terminateTree){await t.terminateTree(e);return}let i=e.pid;if(i===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let r=process.env.SystemRoot??process.env.WINDIR,n=r&&D.win32.isAbsolute(r)?D.win32.resolve(r):"C:\\Windows",a=D.win32.join(n,"System32","taskkill.exe");if(!D.win32.isAbsolute(a))throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git taskkill path is not trusted"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"});let o=()=>new Promise(s=>{let c=!1,l=null,u=null,d=(f,p=!1)=>{c||(c=!0,u&&clearTimeout(u),p&&l?.kill("SIGKILL"),s(f))};try{l=ev(a,["/pid",String(i),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>d(!1)),l.once("close",f=>d(f===0)),u=setTimeout(()=>d(!1,!0),xP),u.unref()}catch{d(!1)}});for(let s=0;s<PP;s+=1)if(await o()){e.kill("SIGKILL");return}throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git process-tree termination could not be confirmed on Windows"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"})}try{process.kill(-i,"SIGKILL")}catch(r){if(r.code!=="ESRCH")throw r}e.kill("SIGKILL")}function uu(e,t,i,r){let n=rt(e);if(n<1)throw ru();let a=e.gitProcess,o=ev(a.command,[...a.argsPrefix??[],"-C",t,...i],{cwd:t,stdio:[r?"pipe":"ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"}),s=null,c=!1,l=null;o.once("error",p=>{s=p});let u=new Promise(p=>{o.once("close",p)}),d=setTimeout(()=>{c=!0,l=_P(o,a).then(()=>({error:null}),p=>({error:p}))},n);d.unref();let f=u.then(async p=>{if(clearTimeout(d),c){let v=await l;throw v?.error?ru(v.error):ru()}return{code:p,spawnError:s}});return{child:o,completion:f}}function rv(e){let t={...lu,...e};if(!Number.isSafeInteger(t.maxRecords)||t.maxRecords<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxRecordBytes)||t.maxRecordBytes<1||t.maxRecordBytes>t.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return t}async function Vo(e,t,i,r=ou){let{child:n,completion:a}=uu(e,t,i,!1),o=[],s=[],c=0,l=0,u=!1;n.stdout.on("data",p=>{let v=Math.max(0,r-l);v>0&&o.push(Buffer.from(p).subarray(0,v)),l+=p.byteLength,l>r&&(u=!0)}),n.stderr.on("data",p=>{if(c>=mr)return;let v=mr-c,h=Buffer.from(p).subarray(0,v);s.push(h),c+=h.byteLength});let{code:d,spawnError:f}=await a;if(d===0&&f===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${i.join(" ")} failed${f?`: ${f.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function nu(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function Rn(e,t,i,r){if(r.outputChunkBytes!==void 0&&(!Number.isSafeInteger(r.outputChunkBytes)||r.outputChunkBytes<1))throw new Error("Native Git output chunk size must be a positive integer");return new Promise((n,a)=>{let{child:o,completion:s}=uu(e,t,i,r.stdin!==void 0),c=[],l=Mo("sha256"),u=[],d=0,f=0,p=0,v=0,h=Buffer.alloc(0),m=!1,S=!1,y=!1,k=N=>{let E=0;for(;E<N.byteLength;){let b=N.indexOf(0,E),x=b<0?N.byteLength:b,g=N.subarray(E,x);if(!m&&g.byteLength>0&&(h.byteLength+g.byteLength>r.maxRecordBytes?(h=Buffer.alloc(0),m=!0,S=!0):h=Buffer.concat([h,g])),b<0)break;v+=1,h.byteLength===0&&!m&&(y=!0);let w=h.byteLength+1;!m&&v<=r.maxRecords&&p+w<=r.maxBytes?(c.push(h),p+=w):S=!0,h=Buffer.alloc(0),m=!1,E=b+1}};o.stdout.on("data",N=>{l.update(N),f+=N.byteLength,f>r.maxBytes&&(S=!0);let E=r.outputChunkBytes;if(E===void 0){k(N);return}for(let b=0;b<N.byteLength;b+=E)k(N.subarray(b,Math.min(N.byteLength,b+E)))}),o.stderr.on("data",N=>{if(d>=mr)return;let E=mr-d,b=Buffer.from(N).subarray(0,E);u.push(b),d+=b.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:N,spawnError:E})=>{let b=r.acceptedExitCodes??[0];if(N!==null&&b.includes(N)&&E===null&&!y&&h.byteLength===0&&!m){n({records:c,digest:l.digest("hex"),overflow:S,recordCount:v,stdoutBytes:f});return}a(new Error(`git ${i.join(" ")} failed${E?`: ${E.message}`:y||h.byteLength>0||m?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),r.stdin&&o.stdin?.end(r.stdin)})}function Fo(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 IP(e,t,i){if(i.length===0)return new Set;let r=await Rn(e,t,["check-ignore","--no-index","-z","--stdin"],{...lu,maxRecords:Math.max(1,i.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${i.join("\0")}\0`,"utf8")});if(r.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(r.records.map(n=>{let a=Fo(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function TP(e,t,i){let{child:r,completion:n}=uu(e,t,i,!1),a=[],o=0,s=!1;r.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),r.stderr.on("data",u=>{if(o>=mr)return;let d=mr-o,f=Buffer.from(u).subarray(0,d);a.push(f),o+=f.byteLength});let{code:c,spawnError:l}=await n;if(c===0&&l===null)return s;throw new Error(`git ${i.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function hr(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||D.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||D.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function jP(e,t){return e.map(i=>{let r=hr(i);if(r===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return r})}async function $P(e){let t=D.resolve(e);for(;;){try{return await X.lstat(D.join(t,".git")),!0}catch(r){if(r.code!=="ENOENT")throw r}let i=D.dirname(t);if(i===t)return!1;t=i}}async function nv(e,t,i,r={}){let n=D.resolve(t.projectRoot),a=D.join(n,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,a].map(f=>{let p=D.relative(n,D.resolve(f)).replaceAll("\\","/"),v=hr(p);if(v===null)throw new Error("Native Git snapshot exclusion escaped the project root");return v}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`])],c={...i,...r.outputChunkBytes===void 0?{}:{outputChunkBytes:r.outputChunkBytes}},l=await Rn(e,n,["ls-files","--stage","-z",...s],c);await r.afterStageBefore?.();let u=await Rn(e,n,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await r.afterCombined?.();let d=await Rn(e,n,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function av(e){return{stageBefore:nu(e.stagedBefore),combined:nu(e.combined),stageAfter:nu(e.stagedAfter)}}async function ov(e,t,i=lu,r={}){let n=D.resolve(t.projectRoot);if(!await $P(n))return null;let a;try{a=await Vo(e,n,["rev-parse","--is-inside-work-tree"])}catch(y){throw pr(y)?y:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:y})}if(a.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let o;try{o=await nv(e,t,i,r)}catch(y){throw pr(y)?y:new Error("Native Git snapshot provider failed after repository detection",{cause:y})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,u=new Set,d=new Map,f=new Set,p=y=>{for(let k of y){let N=Fo(k),E=N.indexOf(" ");if(E<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let b=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(N.slice(0,E))?.groups;if(!b)throw new Error("Native Git snapshot provider returned a malformed staged header");let x=hr(N.slice(E+1));if(x===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(x),b.stage==="0"&&d.set(x,b.objectId),b.mode==="160000"&&b.stage==="0"&&f.add(x)}};p(s.records),p(l.records);let v=c.records.map(Fo),h=jP(v,"combined"),m=new Set(h.filter(y=>!u.has(y))),S=new Set(h.filter((y,k)=>!u.has(y)&&v[k].endsWith("/")));for(let y of f)S.delete(y);return{tracked:u,trackedObjectIds:d,untracked:m,gitlinks:f,nestedRepositories:S,omissions:[],overflow:null,evidence:null,initialFence:av(o)}}function oi(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function Jm(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function OP(e,t){return!oi(e.stageBefore,e.stageAfter)||!oi(e.stageAfter,t.stageBefore)||!oi(e.combined,t.combined)||!oi(t.stageBefore,t.stageAfter)}async function sv(e,t,i,r,n){let a;try{a=await nv(e,t,i,{...n===void 0?{}:{outputChunkBytes:n}})}catch(u){throw pr(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=r.initialFence,s=av(a),c=Jm(o)||Jm(s),l=OP(o,s);c&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),l&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),r.evidence=c||l?{schema:"comet.native.git-selection.v1",status:c&&l?"overflow-and-changed":c?"overflow":"changed",...o,finalStageBefore:s.stageBefore,finalCombined:s.combined,finalStageAfter:s.stageAfter}:null,(o.combined.overflow||s.combined.overflow)&&(r.overflow={count:Math.max(1,o.combined.recordCount-o.combined.storedRecordCount,s.combined.recordCount-s.combined.storedRecordCount),hash:K(`comet.native.git-selection-overflow.v2
153
- ${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var HP=(1n<<256n)-1n;function DP(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function Gm(e){let t=D.resolve(e.paths.projectRoot),i=D.resolve(e.paths.nativeRoot),r=D.resolve(e.paths.runtimeDir),n=D.resolve(e.paths.configFile),a=D.join(t,".comet","current-change.json"),o=[],s=[],c=Buffer.alloc(32),l=0n,u=0,d=0,f=0,p=!1,v=!1,h=!1,m=()=>rt(e.execution)>=1?!0:(p=!0,h=!0,!1),S=N=>{let E=Buffer.from(`${N.type}\0${N.path}`,"utf8"),b=Mo("sha256").update("comet.native.physical-selection-record.v1\0").update(E).digest();for(let x=0;x<c.length;x+=1)c[x]^=b[x];if(l=l+BigInt(`0x${b.toString("hex")}`)&HP,d+=1,f+=E.byteLength,Buffer.byteLength(N.path,"utf8")>e.limits.maxPathBytes||f>e.limits.maxBytes){p=!0,h=!0;return}o.push(N)},y=async N=>{if(h||!m())return;let E;try{E=await X.opendir(N)}catch(C){if(!m())return;if(!se(C)&&!oe(C)||N===t&&se(C))throw C;v||=oe(C),p||=se(C),h=!0;return}if(!m()){try{await E.close()}catch(C){if(C.code!=="ERR_DIR_CLOSED")throw C}return}let b=!1,x;try{for(;!h&&m();){let C;try{C=await E.read()}catch(G){if(!m())break;if(!se(G)&&!oe(G)||N===t&&se(G))throw G;v||=oe(G),p||=se(G),h=!0;break}if(!m()||C===null)break;if(u+=1,u>e.limits.maxNodes){p=!0,h=!0;break}let $=D.join(N,C.name),T=LP(t,$);if($===n||$===a||nt(i,$)||nt(r,$)||e.denylist.some(G=>nt(G,$))||ft(T)!==null)continue;if(!m())break;let pe;try{pe=await X.lstat($)}catch(G){if(!m())break;if(!se(G)&&!oe(G))throw G;if(v=!0,S({path:T,type:"other"}),s.push({path:T,size:null,type:"file",reason:se(G)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(T),h||!m())break;continue}if(!m())break;let Q=DP(pe);if(Q==="directory"){if(MP(e.policy,T))continue;if(!m())break;let G;try{G=await X.realpath($)}catch(lt){if(!m())break;if(!se(lt)&&!oe(lt))throw lt;if(v=!0,S({path:T,type:Q}),s.push({path:T,size:null,type:"directory",reason:se(lt)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(T),h||!m())break;continue}if(!m())break;if(!V(e.physicalProjectRoot,G)||nt(e.physicalNativeRoot,G))continue;if(S({path:T,type:Q}),await e.hooks?.afterNode?.(T),!m()||(await y($),h))break;continue}if(S({path:T,type:Q}),await e.hooks?.afterNode?.(T),!m()||h)break}}catch(C){b=!0,x=C}let g;try{await E.close()}catch(C){g=C}let w=m();if(b)throw x;if(w&&g!==void 0&&g.code!=="ERR_DIR_CLOSED")throw g};await y(t),m(),p?(o.length=0,d=0,f=0):(o.sort((N,E)=>N.path.localeCompare(E.path,"en")),s.sort((N,E)=>N.path.localeCompare(E.path,"en")));let k=p?K(`comet.native.physical-selection-incomplete.v1
151
+ `),o.context,r)),o=null}};for(let{line:c,body:l}of nr(e)){let u=l?Ml(c):null,d=u?/^Scenario\s*:\s*(.*)$/iu.exec(u.text):null;if(d){for(s();a.at(-1)&&a.at(-1).level>=u.level;)a.pop();let f=_o(d[1]);if(f.length===0)throw new Error("Scenario title must not be empty");o={level:u.level,title:f,body:[],context:a.map(p=>p.text)}}else if(u){for(o!==null&&u.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=u.level;)a.pop();a.push(u)}else o!==null&&l&&o.body.push(c)}return s(),zl(n,"Specification",r)}function Nm(e,t="spec.md",i=bn.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=null,c=()=>{if(s!==null){if(n.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);n.push(Wl("spec-must",t,s.parts.join(" "),s.context,r)),s=null}},l=()=>a.some(u=>/^(?:non-?goals?|非目标)$/iu.test(u.text.trim()));for(let{line:u,body:d}of nr(e)){let f=d?Ml(u):null;if(f){for(c(),o!==null&&f.level<=o&&(o=null);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f),/^Scenario\s*:/iu.test(f.text)&&(o=f.level);continue}let p=u.trim();if(!d||o!==null||l()){c();continue}if(p.length===0||ql(u,null)!==null||p.startsWith("<!--")||p==="-->"||p==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(p)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(p)||/^(?:[-*_]\s*){3,}$/u.test(p)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(p)){c();continue}let v=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(u);if(v){c(),s={parts:[v[1]],context:a.map(h=>h.text)};continue}if(/^\|.*\|$/u.test(p)){c(),s={parts:[p],context:a.map(h=>h.text)},c();continue}s===null?s={parts:[p],context:a.map(h=>h.text)}:s.parts.push(p)}return c(),zl(n,"Specification mandatory requirements",r)}function ZC(e,t){let i=e.trim().replaceAll("\\","/");if(i.length===0||XC(i)||pm.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~|[A-Za-z][A-Za-z0-9+.-]*:)/u.test(i)||i.split("/").includes(".."))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);let r=pm.posix.normalize(i);if(r==="."||r===".."||r.startsWith("../"))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);if(r.split("/").some(n=>n.toLowerCase()===".git"||n.toLowerCase().startsWith(".env")))throw new Error(`Acceptance evidence ${t} references sensitive content`);if(!WC.test(r))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return r}function ex(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`Acceptance evidence entry ${t} must be an object`);let i=e,r=Object.keys(i).filter(n=>!MC.has(n));if(r.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${r.join(", ")}`);return i}function bm(e){if(!Array.isArray(e))throw new Error("Native acceptance evidence block must be a JSON array");let t=new Set;return e.map((i,r)=>{let n=ex(i,r),a=n.acceptance_id;if(typeof a!="string"||!qC.test(a))throw new Error(`Acceptance evidence entry ${r} has an invalid acceptance_id`);if(t.has(a))throw new Error(`Native acceptance evidence has duplicate acceptance_id: ${a}`);if(t.add(a),!Array.isArray(n.evidence_refs))throw new Error(`Acceptance evidence ${a} requires an evidence_refs array`);let o=n.evidence_refs.map(l=>{if(typeof l!="string"||l.trim().length===0)throw new Error(`Acceptance evidence ${a} has a non-empty string requirement`);return ZC(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 km(e){let t=YC(e);if(t.some(({line:l,body:u})=>!u&&(l===hm||l===mm)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let r=t.flatMap(({line:l,body:u},d)=>u&&l===hm?[d]:[]),n=t.flatMap(({line:l,body:u},d)=>u&&l===mm?[d]:[]);if(r.length!==1||n.length!==1)throw new Error("Verification must contain exactly one Native acceptance evidence block");if(r[0]>=n[0])throw new Error("Native acceptance evidence markers are out of order");let a=t.slice(r[0]+1,n[0]).map(({line:l})=>l).join(`
152
+ `).trim();if(a.length===0)throw new Error("Native acceptance evidence block is empty");let o;try{o=JSON.parse(a)}catch(l){throw new Error(`Native acceptance evidence block is invalid JSON: ${l.message}`,{cause:l})}let s=bm(o),c=tx(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function tx(e){let t=bm([...e]).map(i=>({...i,evidence_refs:[...i.evidence_refs].sort()})).sort((i,r)=>i.acceptance_id.localeCompare(r.acceptance_id));return JSON.stringify(t,null,2)}var Kl=Or(Xi(),1);import{promises as rx}from"node:fs";var kn="comet.native.v4",Io="comet.native.local-execution.v4";var Sm=["multi-session","single-session"];var nx=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ax=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ox=/^A[1-9][0-9]*$/u,sx=/^[a-f0-9]{64}$/u,cx=new Set(["schema","name","language","phase","status","state_version","brief","shape_confirmation_hash","children_contract_hash","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]);function Ne(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function be(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function de(e,t,i){if(typeof e!="string"||!i?.empty&&e.length===0)throw new Error(`${t} must be ${i?.empty?"a string":"a non-empty string"}`);return e}function Ul(e,t){return e===null?null:de(e,t)}function Cm(e,t){let i=de(e,t);if(!sx.test(i))throw new Error(`${t} must be a SHA-256 hash`);return i}function ar(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function ie(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function lx(e,t){return e===null?null:ie(e,t,Number.MIN_SAFE_INTEGER)}function ae(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function ht(e,t,i){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,n)=>i(r,n))}function To(e,t){return ht(e,t,(i,r)=>de(i,`${t}[${r}]`))}function Ai(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function or(e,t){let i=de(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO date or timestamp`);return i}function Yl(e,t,i=!1){let r=de(e,t);if(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").includes("..")||!i&&(r==="."||r.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return r}function Le(e,t){let i=Ne(e,t);return be(i,new Set(["text","truncated"]),t),{text:de(i.text,`${t}.text`,{empty:!0}),truncated:ar(i.truncated,`${t}.truncated`)}}function ux(e,t){let i=`Native spec_changes[${t}]`,r=Ne(e,i);be(r,new Set(["capability","operation","source"]),i);let n=de(r.capability,`${i}.capability`);if(!ax.test(n))throw new Error(`${i}.capability is invalid`);let a=ae(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:Yl(r.source,`${i}.source`);if(a==="remove"&&o!==null)throw new Error(`${i} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${i} ${a} requires a source`);return{capability:n,operation:a,source:o}}function dx(e){let t="Native workspace",i=Ne(e,t);be(i,new Set(["isolation","change_branch","target_branch","finish"]),t);let r=ae(i.isolation,["current","branch","worktree"],`${t}.isolation`),n=Ul(i.change_branch,`${t}.change_branch`),a=Ul(i.target_branch,`${t}.target_branch`),o=i.finish===null?null:ae(i.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(r==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(r==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(r!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:r,change_branch:n,target_branch:a,finish:o}}function fx(e){let t="Native loop",i=Ne(e,t);be(i,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let r=To(i.previous_unresolved_ids,`${t}.previous_unresolved_ids`);Ai(r,`${t}.previous_unresolved_ids`);let n=i.stop_reason===void 0?void 0:ae(i.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:ae(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:ie(i.goal_cycle,`${t}.goal_cycle`,1),iteration:ie(i.iteration,`${t}.iteration`),attempt:ie(i.attempt,`${t}.attempt`),retry_epoch:ie(i.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:ie(i.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:ie(i.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:ie(i.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:r,next_action:Ul(i.next_action,`${t}.next_action`)}}function px(e,t){let i=`Native acceptance[${t}]`,r=Ne(e,i);be(r,new Set(["id","source","text","result","reason"]),i);let n=de(r.id,`${i}.id`);if(!ox.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:Yl(r.source,`${i}.source`),text:de(r.text,`${i}.text`),result:ae(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:Le(r.reason,`${i}.reason`)}}function hx(e,t){let i=`Native builder_handoff.checks[${t}]`,r=Ne(e,i);return be(r,new Set(["name","result","note"]),i),{name:Le(r.name,`${i}.name`),result:ae(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:Le(r.note,`${i}.note`)}}function mx(e){let t="Native builder_handoff",i=Ne(e,t);be(i,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let r=To(i.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);Ai(r,`${t}.addressed_acceptance_ids`);let n=i.review===null||i.review===void 0?null:Ne(i.review,`${t}.review`);return n&&be(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:de(i.candidate_id,`${t}.candidate_id`),identity_provider:de(i.identity_provider,`${t}.identity_provider`),builder_execution_ref:de(i.builder_execution_ref,`${t}.builder_execution_ref`),iteration:ie(i.iteration,`${t}.iteration`,1),summary:Le(i.summary,`${t}.summary`),addressed_acceptance_ids:r,checks:ht(i.checks,`${t}.checks`,hx),checks_truncated:ar(i.checks_truncated,`${t}.checks_truncated`),known_limits:ht(i.known_limits,`${t}.known_limits`,(a,o)=>Le(a,`${t}.known_limits[${o}]`)),known_limits_truncated:ar(i.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:ae(n.status,["passed"],`${t}.review.status`),summary:Le(n.summary,`${t}.review.summary`),reviewer_execution_ref:de(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:or(i.submitted_at,`${t}.submitted_at`)}}function vx(e,t){let i=`Native blockers[${t}]`,r=Ne(e,i);be(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=To(r.acceptance_ids,`${i}.acceptance_ids`);return Ai(n,`${i}.acceptance_ids`),{owner:ae(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:Le(r.reason,`${i}.reason`),acceptance_ids:n,resolution_action:ae(r.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${i}.resolution_action`)}}function gx(e,t){let i=`Native verification.checks[${t}]`,r=Ne(e,i);return be(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:de(r.id,`${i}.id`),name:Le(r.name,`${i}.name`),argv_display:ht(r.argv_display,`${i}.argv_display`,(n,a)=>Le(n,`${i}.argv_display[${a}]`)),argv_truncated:ar(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:Yl(r.cwd_ref,`${i}.cwd_ref`,!0),status:ae(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:lx(r.exit_code,`${i}.exit_code`),duration_ms:ie(r.duration_ms,`${i}.duration_ms`)}}function wx(e){let t="Native verification",i=Ne(e,t);be(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let r=ht(i.checks,`${t}.checks`,gx);Ai(r.map(a=>a.id),`${t}.checks IDs`);let n=de(i.identity_provider,`${t}.identity_provider`);return{candidate_id:de(i.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:de(i.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:ie(i.iteration,`${t}.iteration`,1),attempt:ie(i.attempt,`${t}.attempt`,1),assurance:i.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":ae(i.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:ae(i.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:r,summary:Le(i.summary,`${t}.summary`),risks:ht(i.risks,`${t}.risks`,(a,o)=>Le(a,`${t}.risks[${o}]`)),risks_truncated:ar(i.risks_truncated,`${t}.risks_truncated`),completed_at:or(i.completed_at,`${t}.completed_at`)}}function yx(e,t){let i=`Native history[${t}]`,r=Ne(e,i);be(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=To(r.unresolved_ids,`${i}.unresolved_ids`);return Ai(n,`${i}.unresolved_ids`),{goal_cycle:ie(r.goal_cycle,`${i}.goal_cycle`,1),iteration:ie(r.iteration,`${i}.iteration`),attempt:ie(r.attempt,`${i}.attempt`),outcome:ae(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:Le(r.summary,`${i}.summary`),completed_at:or(r.completed_at,`${i}.completed_at`)}}function Nx(e){let t="Native history_overflow.outcome_counts",i=Ne(e,t),r=["pass","fail","blocked","execution-error","recovery"];return be(i,new Set(r),t),{pass:ie(i.pass,`${t}.pass`),fail:ie(i.fail,`${t}.fail`),blocked:ie(i.blocked,`${t}.blocked`),"execution-error":ie(i["execution-error"],`${t}.execution-error`),recovery:ie(i.recovery,`${t}.recovery`)}}function bx(e){let t="Native history_overflow",i=Ne(e,t);be(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let r=ie(i.dropped_entries,`${t}.dropped_entries`),n=i.first_dropped_at===null?null:or(i.first_dropped_at,`${t}.first_dropped_at`),a=i.last_dropped_at===null?null:or(i.last_dropped_at,`${t}.last_dropped_at`);if(r===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(r>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=Nx(i.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==r)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:r,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function kx(e){let t=new Set(e.acceptance.map(i=>i.id));for(let i of e.loop.previous_unresolved_ids)if(!t.has(i))throw new Error(`Native loop references unknown acceptance ID ${i}`);for(let i of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(i))throw new Error(`Native builder handoff references unknown ID ${i}`);for(let i of e.blockers)for(let r of i.acceptance_ids)if(!t.has(r))throw new Error(`Native blocker references unknown ID ${r}`);if(e.builder_handoff){if(!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let r=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!r&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function Sx(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let i=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(i!==null&&e.loop.stage!==i)throw new Error(`Native status ${e.status} requires loop stage ${i}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(r=>r.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(r=>r.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function Sn(e){let t=Ne(e,"Native portable state");if(be(t,cx,"Native portable state"),t.schema!==kn)throw new Error(`Native portable state schema must be ${kn}`);let i=de(t.name,"Native state name");if(!nx.test(i))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let r=ht(t.spec_changes,"Native spec_changes",ux);Ai(r.map(s=>s.capability),"Native spec change capabilities");let n=ht(t.acceptance,"Native acceptance",px);Ai(n.map(s=>s.id),"Native acceptance IDs");let a=ht(t.history,"Native history",yx);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:kn,name:i,language:ae(t.language,["en","zh-CN"],"Native state language"),phase:ae(t.phase,["shape","build","verify","archive"],"Native state phase"),status:ae(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:ie(t.state_version,"Native state_version",1),brief:"brief.md",...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:Cm(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:Cm(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:ae(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:r,workspace:dx(t.workspace),loop:fx(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:mx(t.builder_handoff),blockers:ht(t.blockers,"Native blockers",vx),verification:t.verification===null?null:wx(t.verification),history:a,history_overflow:bx(t.history_overflow),verification_result:ae(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:ae(t.verification_report,["verification.md"],"Native verification_report"),archived:ar(t.archived,"Native archived"),created_at:or(t.created_at,"Native created_at")};return kx(o),Sx(o),o}function Ex(e,t){let i=(0,Kl.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`${t} is invalid YAML: ${i.errors[0].message}`);return i.toJS({mapAsMap:!1})}async function En(e){let t=await rx.readFile(e,"utf8");return Sn(Ex(t,"Native portable state"))}var Pt="comet.native.v3",Rt="comet.native.v2",At="comet.native.v1",sr="comet.native.transition.v3",cr="comet.native.transition.v2",Cn="comet.native.transition.v1";var xm="comet.native.portable-migration.v1",Cx=new Set(["schema","id","change","fromSchema","status","createdAt"]),xx=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Px=/^[a-z0-9][a-z0-9-]{7,127}$/u,Rx=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),Ax=new Set([At,Rt,Pt]);function _x(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ix(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function Rm(e){let t=_x(e,"Native portable migration transaction"),i=Object.keys(t).filter(r=>!Cx.has(r));if(i.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${i.join(", ")}`);if(t.schema!==xm)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!Px.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!xx.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!Ax.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!Rx.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:xm,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:Ix(t.createdAt,"Native portable migration transaction createdAt")}}var Am="comet.native.archive-transaction.v4",_m="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",jx=new RegExp(`^portable-archive-(${_m})\\.json$`,"u"),$x=new RegExp(`^portable-migration-(${_m})\\.json$`,"u"),Ox=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Hx=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Dx=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),Bx=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),Lx=new Set(["capability","operation","source","content"]),Im=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Tm(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function jm(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(Object.keys(e).length!==t.size)throw new Error(`${i} fields are invalid`)}function Vx(e,t){let i=`Native portable Archive spec_changes[${t}]`,r=Tm(e,i);if(jm(r,Lx,i),typeof r.capability!="string"||!Im.test(r.capability))throw new Error(`${i}.capability is invalid`);if(!["create","modify","remove"].includes(String(r.operation)))throw new Error(`${i}.operation is invalid`);let n=r.operation;if(n==="remove"){if(r.source!==null||r.content!==null)throw new Error(`${i} remove requires source and content null`);return{capability:r.capability,operation:n,source:null,content:null}}if(typeof r.source!="string"||r.source.length===0||r.source.includes("\\")||r.source.startsWith("/")||/^[A-Za-z]:/u.test(r.source)||r.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${i}.${n} source is invalid`);if(typeof r.content!="string")throw new Error(`${i}.${n} content is invalid`);return{capability:r.capability,operation:n,source:r.source,content:r.content}}function Fx(e){let t=Tm(e,"Native portable Archive transaction");if(jm(t,Bx,"Native portable Archive transaction"),t.schema!==Am)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!Ox.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Im.test(t.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(t.start_state_version)||Number(t.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof t.archive_ref!="string"||!Hx.test(t.archive_ref)||!t.archive_ref.endsWith(`-${t.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof t.status!="string"||!Dx.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let i=t.spec_changes.map(Vx);if(new Set(i.map(({capability:n})=>n)).size!==i.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>i.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let r=new Date(t.created_at);if(Number.isNaN(r.valueOf())||r.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:Am,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:i,created_at:t.created_at}}function Xl(e){let t=jx.exec(e);if(t)return{kind:"archive",change:t[1]};let i=$x.exec(e);return i?{kind:"migration",change:i[1]}:null}async function $m(e,t){let i=Xl(t);if(!i)return null;let r=await re({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(r.text),a=Tx.join(e.transactionsDir,t);if(i.kind==="archive"){let s=Fx(n);if(s.change!==i.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:i.change,file:a,journal:s}}let o=Rm(n);if(o.change!==i.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:i.change,file:a,journal:o}}function Om(e){return e.kind==="archive"||e.journal.status!=="committed"}import It from"path";import{TextDecoder as Ux}from"util";import{createHash as qx}from"node:crypto";import{constants as jo,promises as Te}from"node:fs";import tt from"node:path";import{TextDecoder as Mx}from"node:util";function Oo(e,t){let i=tt.relative(e,t);return i===""||!tt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${tt.sep}`)}function Hm(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function Wx(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function zx(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function $o(e,t){return q({...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 Ql(e,t){let i=await Te.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await Te.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function Dm(e,t,i){let r=tt.resolve(e),n=tt.resolve(t);if(!Oo(r,n))throw new Error(`${i} is outside its managed root`);let a=[await Ql(r,i)],o=r;for(let s of tt.relative(r,n).split(tt.sep).filter(Boolean)){await _t(a,i),o=tt.join(o,s);let c=await Ql(o,i);if(!Oo(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await _t(a,i),a}async function _t(e,t){for(let i of e){let r=await Te.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!Wx(i,r)||await Te.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function Jx(e,t,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${i} exceeds ${t} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function mt(e){let t=Hm(e.maxBytes),i=tt.resolve(e.file),r=await Dm(e.root,tt.dirname(i),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>Ql(tt.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await _t(r,e.label);let a=await Te.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=zx(a),s=await Te.realpath(i);if(!Oo(r[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>Oo(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?jo.O_RDONLY:jo.O_RDONLY|jo.O_NOFOLLOW|jo.O_NONBLOCK,l=await Te.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([Te.lstat(i),Te.realpath(i)]);if(await _t(r,e.label),await _t(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!$o(o,u)||!$o(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await Jx(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([l.stat(),Te.lstat(i),Te.realpath(i)]);if(await _t(r,e.label),await _t(n,e.label),!h.isFile()||h.isSymbolicLink()||m!==s||!$o(o,v)||!$o(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:qx("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function Bm(e){let t=await mt(e),i;try{i=new Mx("utf-8",{fatal:!0}).decode(t.bytes)}catch(r){throw new Error(`${e.label} is not valid UTF-8`,{cause:r})}return{...t,text:i}}async function xn(e){let t=await Dm(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await Te.readdir(e.directory,{withFileTypes:!0});else{let r=Hm(e.maxEntries);i=[];let n=await Te.opendir(e.directory);try{for await(let a of n)if(i.push(a),i.length>r)throw new Error(`${e.label} exceeds ${r} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await _t(t,e.label),{entries:i,verify:()=>_t(t,e.label)}}var Kx=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),Yx=new Set(["id","type","source","target","staged","backup"]),Xx=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),Qx=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var Fm=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var Zx=256*1024,IH=1024*1024,TH=16*1024;var jH=64*1024*1024;var eP=new Ux("utf-8",{fatal:!0});function Do(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Bo(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function qm(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Zl(e,t){if(typeof e!="string"||e.length===0||It.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Ho(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function Lm(e,t){if(Zl(e,t),e.includes("\\")||e!==It.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function tP(e,t){let i=Do(e,`transaction operations[${t}]`);if(Bo(i,Yx,`transaction operations[${t}]`),typeof i.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.id))throw new Error(`transaction operations[${t}].id is invalid`);if(i.type!=="write"&&i.type!=="remove"&&i.type!=="move")throw new Error(`transaction operation ${i.id} has an invalid type`);Zl(i.target,`transaction operation ${i.id} target`);for(let r of["source","staged","backup"])i[r]!==void 0&&Zl(i[r],`transaction operation ${i.id} ${r}`);if(i.type==="write"){if(i.staged===void 0||i.source!==void 0)throw new Error(`write operation ${i.id} requires staged and forbids source`)}else if(i.type==="remove"){if(i.source!==void 0||i.staged!==void 0)throw new Error(`remove operation ${i.id} forbids source and staged`)}else if(i.source===void 0||i.staged!==void 0||i.backup!==void 0)throw new Error(`move operation ${i.id} requires source and forbids staged and backup`);return i}function Mm(e){let t=Do(e,"Native Archive transaction journal");if(Bo(t,Xx,"Native Archive transaction journal"),t.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native Archive transaction id is invalid");if(t.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof t.status!="string"||!Fm.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!qm(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Ho(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let i=t.operations.map((s,c)=>{let l=Do(s,`Archive transaction operations[${c}]`);if(Bo(l,Qx,`Archive transaction operations[${c}]`),typeof l.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(l.id))throw new Error(`Archive transaction operations[${c}].id is invalid`);if(l.type!=="write"&&l.type!=="remove"&&l.type!=="move")throw new Error(`Archive transaction operation ${l.id} has an invalid type`);Lm(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&Lm(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&Ho(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(Ho(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);Ho(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),r=i.map(s=>s.id);if(new Set(r).size!==r.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=i.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||i.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of i.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:i}}function iP(e){let t=Do(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Mm(t);if(Bo(t,Kx,"Native transaction journal"),t.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native transaction id is invalid");if(t.kind!=="archive"&&t.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof t.status!="string"||!Fm.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!It.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!It.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!qm(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let i=t.operations.map(tP),r=i.map(n=>n.id);if(new Set(r).size!==r.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:i}}function rP(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return It.join(e.transactionsDir,t)}function Wm(e,t){let i=rP(e,t);return{directory:i,journal:It.join(i,"transaction.json"),events:It.join(i,"events.jsonl"),staged:It.join(i,"staged"),backups:It.join(i,"backups")}}async function eu(e,t){let i=Wm(e,t);return await Promise.all(Object.values(i).map(r=>z(e.runtimeDir,r))),i}async function tu(e,t,i={}){let r=await eu(e,t),n=await mt({root:e.runtimeDir,file:r.journal,maxBytes:Zx,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(eP.decode(n.bytes)),o=iP(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function oP(e,t,i){let r;try{r=await nP.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await tu(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of r)if(Xl(n.name))try{let a=await $m(e,n.name);if(!a||i?.kind===a.kind&&i.change===a.change)continue;if(Om(a))return!0}catch{return!0}return!1}async function sP(e,t){let i=Date.now()+5e3,r=aP.join(e.locksDir,"root-move.lock");for(;;)try{return await Ro(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await fm(r);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=i)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function it(e,t,i,r){let n=await sP(e,t);try{if(await Co(e.projectRoot),await oP(e,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await Ao(n)}}import{createHash as Mo}from"crypto";import{spawn as ev}from"node:child_process";import{promises as X}from"fs";import D from"path";import{createHash as zm}from"crypto";import{createReadStream as cP}from"fs";async function iu(e){let t=zm("sha256");for await(let i of cP(e))t.update(i);return t.digest("hex")}function K(e){return zm("sha256").update(e).digest("hex")}var Lo={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},cu=1e3,lP=8*1024*1024,uP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,dP=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),fP=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),pP=new Set(["schema","include","exclude","hash"]),hP=new Set(["provider","gitSelection","physicalSelection","projection"]),mP=new Set(["provider","selection"]),vP=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),gP=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),wP=new Set(["schema","status","before","after"]),yP=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),NP=new Set(["path","hash","size","type","gitObjectId"]),bP=new Set(["path","size","type","reason"]),kP=new Set(["ref","hash","count"]),SP=new Set(["change-created","legacy-migration","explicit"]),EP=new Set(["file","directory","other"]),CP=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"]),Wo=/^[a-f0-9]{64}$/u,tv=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,xP=new Set(["EACCES","EPERM"]),mr=64*1024,ou=64*1024,PP=6e4,RP=1e3,AP=2,lu={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},_P={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function iv(e){let t=e.deadlineMs??PP;if(!Number.isSafeInteger(t)||t<1)throw new Error("Native snapshot execution budget must be a positive integer");return{deadlineAt:Date.now()+t,gitProcess:e.gitProcess??{command:"git"}}}function rt(e){return Math.max(0,e.deadlineAt-Date.now())}function j(e){return rt(e)>=1}function ru(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 pr(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function IP(e){let t={..._P,...e};if(!Number.isSafeInteger(t.maxNodes)||t.maxNodes<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxPathBytes)||t.maxPathBytes<1||t.maxPathBytes>t.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return t}async function TP(e,t){if(t.terminateTree){await t.terminateTree(e);return}let i=e.pid;if(i===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let r=process.env.SystemRoot??process.env.WINDIR,n=r&&D.win32.isAbsolute(r)?D.win32.resolve(r):"C:\\Windows",a=D.win32.join(n,"System32","taskkill.exe");if(!D.win32.isAbsolute(a))throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git taskkill path is not trusted"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"});let o=()=>new Promise(s=>{let c=!1,l=null,u=null,d=(f,p=!1)=>{c||(c=!0,u&&clearTimeout(u),p&&l?.kill("SIGKILL"),s(f))};try{l=ev(a,["/pid",String(i),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>d(!1)),l.once("close",f=>d(f===0)),u=setTimeout(()=>d(!1,!0),RP),u.unref()}catch{d(!1)}});for(let s=0;s<AP;s+=1)if(await o()){e.kill("SIGKILL");return}throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git process-tree termination could not be confirmed on Windows"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"})}try{process.kill(-i,"SIGKILL")}catch(r){if(r.code!=="ESRCH")throw r}e.kill("SIGKILL")}function uu(e,t,i,r){let n=rt(e);if(n<1)throw ru();let a=e.gitProcess,o=ev(a.command,[...a.argsPrefix??[],"-C",t,...i],{cwd:t,stdio:[r?"pipe":"ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"}),s=null,c=!1,l=null;o.once("error",p=>{s=p});let u=new Promise(p=>{o.once("close",p)}),d=setTimeout(()=>{c=!0,l=TP(o,a).then(()=>({error:null}),p=>({error:p}))},n);d.unref();let f=u.then(async p=>{if(clearTimeout(d),c){let v=await l;throw v?.error?ru(v.error):ru()}return{code:p,spawnError:s}});return{child:o,completion:f}}function rv(e){let t={...lu,...e};if(!Number.isSafeInteger(t.maxRecords)||t.maxRecords<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxRecordBytes)||t.maxRecordBytes<1||t.maxRecordBytes>t.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return t}async function Vo(e,t,i,r=ou){let{child:n,completion:a}=uu(e,t,i,!1),o=[],s=[],c=0,l=0,u=!1;n.stdout.on("data",p=>{let v=Math.max(0,r-l);v>0&&o.push(Buffer.from(p).subarray(0,v)),l+=p.byteLength,l>r&&(u=!0)}),n.stderr.on("data",p=>{if(c>=mr)return;let v=mr-c,h=Buffer.from(p).subarray(0,v);s.push(h),c+=h.byteLength});let{code:d,spawnError:f}=await a;if(d===0&&f===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${i.join(" ")} failed${f?`: ${f.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function nu(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function Rn(e,t,i,r){if(r.outputChunkBytes!==void 0&&(!Number.isSafeInteger(r.outputChunkBytes)||r.outputChunkBytes<1))throw new Error("Native Git output chunk size must be a positive integer");return new Promise((n,a)=>{let{child:o,completion:s}=uu(e,t,i,r.stdin!==void 0),c=[],l=Mo("sha256"),u=[],d=0,f=0,p=0,v=0,h=Buffer.alloc(0),m=!1,S=!1,y=!1,k=N=>{let E=0;for(;E<N.byteLength;){let b=N.indexOf(0,E),x=b<0?N.byteLength:b,g=N.subarray(E,x);if(!m&&g.byteLength>0&&(h.byteLength+g.byteLength>r.maxRecordBytes?(h=Buffer.alloc(0),m=!0,S=!0):h=Buffer.concat([h,g])),b<0)break;v+=1,h.byteLength===0&&!m&&(y=!0);let w=h.byteLength+1;!m&&v<=r.maxRecords&&p+w<=r.maxBytes?(c.push(h),p+=w):S=!0,h=Buffer.alloc(0),m=!1,E=b+1}};o.stdout.on("data",N=>{l.update(N),f+=N.byteLength,f>r.maxBytes&&(S=!0);let E=r.outputChunkBytes;if(E===void 0){k(N);return}for(let b=0;b<N.byteLength;b+=E)k(N.subarray(b,Math.min(N.byteLength,b+E)))}),o.stderr.on("data",N=>{if(d>=mr)return;let E=mr-d,b=Buffer.from(N).subarray(0,E);u.push(b),d+=b.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:N,spawnError:E})=>{let b=r.acceptedExitCodes??[0];if(N!==null&&b.includes(N)&&E===null&&!y&&h.byteLength===0&&!m){n({records:c,digest:l.digest("hex"),overflow:S,recordCount:v,stdoutBytes:f});return}a(new Error(`git ${i.join(" ")} failed${E?`: ${E.message}`:y||h.byteLength>0||m?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),r.stdin&&o.stdin?.end(r.stdin)})}function Fo(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 jP(e,t,i){if(i.length===0)return new Set;let r=await Rn(e,t,["check-ignore","--no-index","-z","--stdin"],{...lu,maxRecords:Math.max(1,i.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${i.join("\0")}\0`,"utf8")});if(r.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(r.records.map(n=>{let a=Fo(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function $P(e,t,i){let{child:r,completion:n}=uu(e,t,i,!1),a=[],o=0,s=!1;r.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),r.stderr.on("data",u=>{if(o>=mr)return;let d=mr-o,f=Buffer.from(u).subarray(0,d);a.push(f),o+=f.byteLength});let{code:c,spawnError:l}=await n;if(c===0&&l===null)return s;throw new Error(`git ${i.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function hr(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||D.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||D.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function OP(e,t){return e.map(i=>{let r=hr(i);if(r===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return r})}async function HP(e){let t=D.resolve(e);for(;;){try{return await X.lstat(D.join(t,".git")),!0}catch(r){if(r.code!=="ENOENT")throw r}let i=D.dirname(t);if(i===t)return!1;t=i}}async function nv(e,t,i,r={}){let n=D.resolve(t.projectRoot),a=D.join(n,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,a].map(f=>{let p=D.relative(n,D.resolve(f)).replaceAll("\\","/"),v=hr(p);if(v===null)throw new Error("Native Git snapshot exclusion escaped the project root");return v}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`])],c={...i,...r.outputChunkBytes===void 0?{}:{outputChunkBytes:r.outputChunkBytes}},l=await Rn(e,n,["ls-files","--stage","-z",...s],c);await r.afterStageBefore?.();let u=await Rn(e,n,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await r.afterCombined?.();let d=await Rn(e,n,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function av(e){return{stageBefore:nu(e.stagedBefore),combined:nu(e.combined),stageAfter:nu(e.stagedAfter)}}async function ov(e,t,i=lu,r={}){let n=D.resolve(t.projectRoot);if(!await HP(n))return null;let a;try{a=await Vo(e,n,["rev-parse","--is-inside-work-tree"])}catch(y){throw pr(y)?y:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:y})}if(a.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let o;try{o=await nv(e,t,i,r)}catch(y){throw pr(y)?y:new Error("Native Git snapshot provider failed after repository detection",{cause:y})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,u=new Set,d=new Map,f=new Set,p=y=>{for(let k of y){let N=Fo(k),E=N.indexOf(" ");if(E<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let b=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(N.slice(0,E))?.groups;if(!b)throw new Error("Native Git snapshot provider returned a malformed staged header");let x=hr(N.slice(E+1));if(x===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(x),b.stage==="0"&&d.set(x,b.objectId),b.mode==="160000"&&b.stage==="0"&&f.add(x)}};p(s.records),p(l.records);let v=c.records.map(Fo),h=OP(v,"combined"),m=new Set(h.filter(y=>!u.has(y))),S=new Set(h.filter((y,k)=>!u.has(y)&&v[k].endsWith("/")));for(let y of f)S.delete(y);return{tracked:u,trackedObjectIds:d,untracked:m,gitlinks:f,nestedRepositories:S,omissions:[],overflow:null,evidence:null,initialFence:av(o)}}function oi(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function Jm(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function DP(e,t){return!oi(e.stageBefore,e.stageAfter)||!oi(e.stageAfter,t.stageBefore)||!oi(e.combined,t.combined)||!oi(t.stageBefore,t.stageAfter)}async function sv(e,t,i,r,n){let a;try{a=await nv(e,t,i,{...n===void 0?{}:{outputChunkBytes:n}})}catch(u){throw pr(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=r.initialFence,s=av(a),c=Jm(o)||Jm(s),l=DP(o,s);c&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),l&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),r.evidence=c||l?{schema:"comet.native.git-selection.v1",status:c&&l?"overflow-and-changed":c?"overflow":"changed",...o,finalStageBefore:s.stageBefore,finalCombined:s.combined,finalStageAfter:s.stageAfter}:null,(o.combined.overflow||s.combined.overflow)&&(r.overflow={count:Math.max(1,o.combined.recordCount-o.combined.storedRecordCount,s.combined.recordCount-s.combined.storedRecordCount),hash:K(`comet.native.git-selection-overflow.v2
153
+ ${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var BP=(1n<<256n)-1n;function LP(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function Gm(e){let t=D.resolve(e.paths.projectRoot),i=D.resolve(e.paths.nativeRoot),r=D.resolve(e.paths.runtimeDir),n=D.resolve(e.paths.configFile),a=D.join(t,".comet","current-change.json"),o=[],s=[],c=Buffer.alloc(32),l=0n,u=0,d=0,f=0,p=!1,v=!1,h=!1,m=()=>rt(e.execution)>=1?!0:(p=!0,h=!0,!1),S=N=>{let E=Buffer.from(`${N.type}\0${N.path}`,"utf8"),b=Mo("sha256").update("comet.native.physical-selection-record.v1\0").update(E).digest();for(let x=0;x<c.length;x+=1)c[x]^=b[x];if(l=l+BigInt(`0x${b.toString("hex")}`)&BP,d+=1,f+=E.byteLength,Buffer.byteLength(N.path,"utf8")>e.limits.maxPathBytes||f>e.limits.maxBytes){p=!0,h=!0;return}o.push(N)},y=async N=>{if(h||!m())return;let E;try{E=await X.opendir(N)}catch(C){if(!m())return;if(!se(C)&&!oe(C)||N===t&&se(C))throw C;v||=oe(C),p||=se(C),h=!0;return}if(!m()){try{await E.close()}catch(C){if(C.code!=="ERR_DIR_CLOSED")throw C}return}let b=!1,x;try{for(;!h&&m();){let C;try{C=await E.read()}catch(G){if(!m())break;if(!se(G)&&!oe(G)||N===t&&se(G))throw G;v||=oe(G),p||=se(G),h=!0;break}if(!m()||C===null)break;if(u+=1,u>e.limits.maxNodes){p=!0,h=!0;break}let $=D.join(N,C.name),T=FP(t,$);if($===n||$===a||nt(i,$)||nt(r,$)||e.denylist.some(G=>nt(G,$))||ft(T)!==null)continue;if(!m())break;let pe;try{pe=await X.lstat($)}catch(G){if(!m())break;if(!se(G)&&!oe(G))throw G;if(v=!0,S({path:T,type:"other"}),s.push({path:T,size:null,type:"file",reason:se(G)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(T),h||!m())break;continue}if(!m())break;let Q=LP(pe);if(Q==="directory"){if(zP(e.policy,T))continue;if(!m())break;let G;try{G=await X.realpath($)}catch(lt){if(!m())break;if(!se(lt)&&!oe(lt))throw lt;if(v=!0,S({path:T,type:Q}),s.push({path:T,size:null,type:"directory",reason:se(lt)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(T),h||!m())break;continue}if(!m())break;if(!V(e.physicalProjectRoot,G)||nt(e.physicalNativeRoot,G))continue;if(S({path:T,type:Q}),await e.hooks?.afterNode?.(T),!m()||(await y($),h))break;continue}if(S({path:T,type:Q}),await e.hooks?.afterNode?.(T),!m()||h)break}}catch(C){b=!0,x=C}let g;try{await E.close()}catch(C){g=C}let w=m();if(b)throw x;if(w&&g!==void 0&&g.code!=="ERR_DIR_CLOSED")throw g};await y(t),m(),p?(o.length=0,d=0,f=0):(o.sort((N,E)=>N.path.localeCompare(E.path,"en")),s.sort((N,E)=>N.path.localeCompare(E.path,"en")));let k=p?K(`comet.native.physical-selection-incomplete.v1
154
154
  ${JSON.stringify({maxNodes:e.limits.maxNodes,maxBytes:e.limits.maxBytes,maxPathBytes:e.limits.maxPathBytes})}`):K(`comet.native.physical-selection.v1
155
- ${JSON.stringify({visitedNodeCount:u,recordCount:d,encodedBytes:f,xor:c.toString("hex"),sum:l.toString(16).padStart(64,"0")})}`);return{records:o,omissions:s,evidence:{hash:k,visitedNodeCount:u,recordCount:d,storedRecordCount:o.length,encodedBytes:f,overflow:p,unstable:v}}}function cv(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 BP(e,t){let i=e.overflow||t.overflow,r=e.unstable||t.unstable||!cv(e,t),n=[];return i&&n.push({path:".",size:null,type:"directory",reason:"physical-enumeration-limit"}),r&&n.push({path:".",size:null,type:"directory",reason:"physical-selection-changed"}),{omissions:n,evidence:i||r?{schema:"comet.native.physical-selection.v1",status:i&&r?"overflow-and-changed":i?"overflow":"changed",before:e,after:t}:null}}function lv(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,i)=>t.localeCompare(i,"en"))}async function Um(e,t){let r=(await Vo(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!tv.test(r))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return K(`gitlink:${r}`)}async function Km(e,t){let i=await Um(e,t),r=await TP(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),n=await Um(e,t);if(n!==i)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:n,dirty:r}}function Pn(e,t){if(ft(t)!==null)return!1;let i=D.resolve(e.projectRoot,...t.split("/"));return!nt(D.resolve(e.nativeRoot),i)&&!nt(D.resolve(e.runtimeDir),i)}function LP(e,t){return D.relative(e,t).split(D.sep).join("/")}function VP(e,t){return t.map(i=>D.resolve(e,...i.split(/[\\/]/u)))}function nt(e,t){let i=D.resolve(e),r=D.resolve(t);return r===i||V(i,r)}function se(e){return EP.has(e.code??"")}function oe(e){return e.code==="ENOENT"}function du(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
156
- `)}function FP(e,t){return K(`comet.native.snapshot-policy.v1
157
- ${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function au(e,t,i){let r=new Set(t),n=[...t];for(;n.length>0;){if(i&&!i())return null;let a=n.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!r.has(a+1)&&(r.add(a+1),n.push(a+1))}return r}function qP(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function Ym(e){let t=Eo(e,"Native snapshot pattern"),i=[];for(let r=0;r<t.length;r+=1){let n=t[r];n==="*"&&t[r+1]==="*"?(r+=1,t[r+1]==="/"?(r+=1,i.push({kind:"globstar-slash"})):i.push({kind:"globstar"})):n==="*"?i.push({kind:"star"}):n==="?"?i.push({kind:"question"}):i.push({kind:"literal",value:n})}return(r,n)=>{let a=n?qP(n):void 0;if(a&&!a())return!1;let o=au(i,new Set([0]),a);if(o===null)return!1;for(let s of r){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let u=i[l];u&&(u.kind==="literal"&&u.value===s||u.kind==="question"&&s!=="/"?c.add(l+1):u.kind==="star"&&s!=="/"||u.kind==="globstar"?c.add(l):u.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=au(i,c,a),o===null||o.size===0)return!1}return au(i,o,a)?.has(i.length)??!1}}function uv(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>Eo(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),i=[...new Set(e.exclude.map(n=>Eo(n,"exclude")))].sort((n,a)=>n.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let r=FP(t,i);if("hash"in e&&e.hash!==r)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:i,hash:r},includeMatchers:t.map(Ym),excludeMatchers:i.map(Ym),excludedDirectoryPrefixes:i.flatMap(n=>{if(!n.endsWith("/**"))return[];let a=n.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((n,a)=>n.localeCompare(a,"en"))}}function MP(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function Xm(e,t,i){if(!e)return!0;let r=()=>j(i),n=!1;for(let a of e.includeMatchers){if(!r())return!1;if(a(t,r)){n=!0;break}}if(!n)return!1;for(let a of e.excludeMatchers)if(!r()||a(t,r))return!1;return!0}function An(e,t,i){let r=JSON.stringify(i);return K(`${e}
155
+ ${JSON.stringify({visitedNodeCount:u,recordCount:d,encodedBytes:f,xor:c.toString("hex"),sum:l.toString(16).padStart(64,"0")})}`);return{records:o,omissions:s,evidence:{hash:k,visitedNodeCount:u,recordCount:d,storedRecordCount:o.length,encodedBytes:f,overflow:p,unstable:v}}}function cv(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 VP(e,t){let i=e.overflow||t.overflow,r=e.unstable||t.unstable||!cv(e,t),n=[];return i&&n.push({path:".",size:null,type:"directory",reason:"physical-enumeration-limit"}),r&&n.push({path:".",size:null,type:"directory",reason:"physical-selection-changed"}),{omissions:n,evidence:i||r?{schema:"comet.native.physical-selection.v1",status:i&&r?"overflow-and-changed":i?"overflow":"changed",before:e,after:t}:null}}function lv(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,i)=>t.localeCompare(i,"en"))}async function Um(e,t){let r=(await Vo(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!tv.test(r))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return K(`gitlink:${r}`)}async function Km(e,t){let i=await Um(e,t),r=await $P(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),n=await Um(e,t);if(n!==i)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:n,dirty:r}}function Pn(e,t){if(ft(t)!==null)return!1;let i=D.resolve(e.projectRoot,...t.split("/"));return!nt(D.resolve(e.nativeRoot),i)&&!nt(D.resolve(e.runtimeDir),i)}function FP(e,t){return D.relative(e,t).split(D.sep).join("/")}function qP(e,t){return t.map(i=>D.resolve(e,...i.split(/[\\/]/u)))}function nt(e,t){let i=D.resolve(e),r=D.resolve(t);return r===i||V(i,r)}function se(e){return xP.has(e.code??"")}function oe(e){return e.code==="ENOENT"}function du(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
156
+ `)}function MP(e,t){return K(`comet.native.snapshot-policy.v1
157
+ ${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function au(e,t,i){let r=new Set(t),n=[...t];for(;n.length>0;){if(i&&!i())return null;let a=n.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!r.has(a+1)&&(r.add(a+1),n.push(a+1))}return r}function WP(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function Ym(e){let t=Eo(e,"Native snapshot pattern"),i=[];for(let r=0;r<t.length;r+=1){let n=t[r];n==="*"&&t[r+1]==="*"?(r+=1,t[r+1]==="/"?(r+=1,i.push({kind:"globstar-slash"})):i.push({kind:"globstar"})):n==="*"?i.push({kind:"star"}):n==="?"?i.push({kind:"question"}):i.push({kind:"literal",value:n})}return(r,n)=>{let a=n?WP(n):void 0;if(a&&!a())return!1;let o=au(i,new Set([0]),a);if(o===null)return!1;for(let s of r){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let u=i[l];u&&(u.kind==="literal"&&u.value===s||u.kind==="question"&&s!=="/"?c.add(l+1):u.kind==="star"&&s!=="/"||u.kind==="globstar"?c.add(l):u.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=au(i,c,a),o===null||o.size===0)return!1}return au(i,o,a)?.has(i.length)??!1}}function uv(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>Eo(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),i=[...new Set(e.exclude.map(n=>Eo(n,"exclude")))].sort((n,a)=>n.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let r=MP(t,i);if("hash"in e&&e.hash!==r)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:i,hash:r},includeMatchers:t.map(Ym),excludeMatchers:i.map(Ym),excludedDirectoryPrefixes:i.flatMap(n=>{if(!n.endsWith("/**"))return[];let a=n.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((n,a)=>n.localeCompare(a,"en"))}}function zP(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function Xm(e,t,i){if(!e)return!0;let r=()=>j(i),n=!1;for(let a of e.includeMatchers){if(!r())return!1;if(a(t,r)){n=!0;break}}if(!n)return!1;for(let a of e.excludeMatchers)if(!r()||a(t,r))return!1;return!0}function An(e,t,i){let r=JSON.stringify(i);return K(`${e}
158
158
  ${Buffer.byteLength(t)}:${t}
159
- ${Buffer.byteLength(r)}:${r}`)}function su(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function qo(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!su(i))return e.splice(t,1),i}return null}function ai(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return _e(i,r)?q(i,r):q(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function WP(e,t,i,r){if(!j(r))return{status:"budget-exhausted"};let n;try{n=await X.open(e,"r")}catch(c){if(!j(r))return{status:"budget-exhausted"};throw c}if(!j(r))return await n.close(),{status:"budget-exhausted"};let a=Mo("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!j(r))return{status:"budget-exhausted"};let c=await n.stat();if(!j(r))return{status:"budget-exhausted"};if(!c.isFile()||!ai(i,c))return{status:"changed"};for(;;){if(!j(r))return{status:"budget-exhausted"};let l=t+1-s;if(l<1)return{status:"changed"};let u=await n.read(o,0,Math.min(o.length,l),null);if(!j(r))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!j(r))return{status:"budget-exhausted"};let d=await n.stat();return j(r)?!d.isFile()||!ai(c,d)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:d}:{status:"budget-exhausted"}}if(s+u.bytesRead>t)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await n.close()}}function Ve(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Fe(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function fr(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function vt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function dv(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let i=D.posix.normalize(e);if(i!==e||D.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function zP(e,t){let i=Ve(e,`Native snapshot entry ${t}`);Fe(i,wP,`Native snapshot entry ${t}`);let r=dv(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!Wo.test(i.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(i.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:r,hash:i.hash,size:vt(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!tv.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=i.gitObjectId}return n}function JP(e,t){let i=Ve(e,`Native snapshot omission ${t}`);if(Fe(i,yP,`Native snapshot omission ${t}`),!kP.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!SP.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:dv(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:vt(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function GP(e){let t=Ve(e,"Native snapshot omission overflow");if(Fe(t,NP,"Native snapshot omission overflow"),typeof t.hash!="string"||!Wo.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let i=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==i)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:i,hash:t.hash,count:fr(t.count,"Native snapshot omission overflow count")}}function dr(e,t){let i=Ve(e,t);if(Fe(i,mP,t),typeof i.hash!="string"||!Wo.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let r=vt(i.recordCount,`${t} recordCount`),n=vt(i.storedRecordCount,`${t} storedRecordCount`),a=vt(i.stdoutBytes,`${t} stdoutBytes`);if(n>r||!i.overflow&&n!==r)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,recordCount:r,storedRecordCount:n,stdoutBytes:a,overflow:i.overflow}}function Qm(e){let t=Ve(e,"Native Git selection evidence");if(Fe(t,hP,"Native Git selection evidence"),t.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let i=dr(t.stageBefore,"Native Git selection stageBefore"),r=dr(t.combined,"Native Git selection combined"),n=dr(t.stageAfter,"Native Git selection stageAfter"),a=dr(t.finalStageBefore,"Native Git selection finalStageBefore"),o=dr(t.finalCombined,"Native Git selection finalCombined"),s=dr(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,r,n,a,o,s].some(d=>d.overflow),l=!oi(i,n)||!oi(n,a)||!oi(r,o)||!oi(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(t.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:i,combined:r,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function Zm(e,t){let i=Ve(e,t);if(Fe(i,gP,t),typeof i.hash!="string"||!Wo.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean"||typeof i.unstable!="boolean")throw new Error(`${t} flags are invalid`);let r=vt(i.visitedNodeCount,`${t} visitedNodeCount`),n=vt(i.recordCount,`${t} recordCount`),a=vt(i.storedRecordCount,`${t} storedRecordCount`),o=vt(i.encodedBytes,`${t} encodedBytes`);if(a>n||!i.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,visitedNodeCount:r,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:i.overflow,unstable:i.unstable}}function UP(e){let t=Ve(e,"Native physical selection evidence");if(Fe(t,vP,"Native physical selection evidence"),t.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let i=Zm(t.before,"Native physical selection before"),r=Zm(t.after,"Native physical selection after"),n=i.overflow||r.overflow,a=i.unstable||r.unstable||!cv(i,r);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:i,after:r}}function _i(e){let t=Ve(e,"Native content snapshot manifest");if(Fe(t,lP,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!bP.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let b=Ve(t.capture,"Native content snapshot capture");if(Fe(b,fP,"Native content snapshot capture"),b.provider!=="git"&&b.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let x=b.gitSelection===void 0?void 0:Qm(b.gitSelection),g=b.physicalSelection===void 0?void 0:UP(b.physicalSelection),w=null;if(b.projection!==void 0){let C=Ve(b.projection,"Native content snapshot projection");if(Fe(C,pP,"Native content snapshot projection"),C.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");w={provider:"git",...C.selection===void 0?{}:{selection:Qm(C.selection)}}}if(b.provider==="git"){if(g||w)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...x?{gitSelection:x}:{}}}else{if(x)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(g&&w)throw new Error("Native physical-tree capture cannot combine selection and projection");i=w?{provider:"physical-tree",projection:w}:{provider:"physical-tree",...g?{physicalSelection:g}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let r=Ve(t.limits,"Native content snapshot limits");Fe(r,uP,"Native content snapshot limits");let n={maxFiles:fr(r.maxFiles,"Native snapshot maxFiles"),maxFileBytes:fr(r.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:fr(r.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:fr(r.maxManifestBytes,"Native snapshot maxManifestBytes"),...r.maxDurationMs===void 0?{}:{maxDurationMs:fr(r.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let b=Ve(t.policy,"Native snapshot policy");if(Fe(b,dP,"Native snapshot policy"),b.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(b.include)||!Array.isArray(b.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=uv({include:b.include,exclude:b.exclude,hash:b.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(zP),s=t.omitted.map(JP),c=vt(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:GP(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(b=>b.size>n.maxFileBytes)||o.reduce((b,x)=>b+x.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(b=>b.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>cu||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(b=>b.reason==="git-enumeration-limit"),f=s.filter(b=>b.reason==="git-selection-changed");for(let b of[...d,...f])if(b.path!=="."||b.size!==null||b.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let p=i?.provider==="git"?i.gitSelection:i?.projection?.selection,v=p?.status==="overflow"||p?.status==="overflow-and-changed",h=p?.status==="changed"||p?.status==="overflow-and-changed";if(v!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let m=s.filter(b=>b.reason==="physical-enumeration-limit"),S=s.filter(b=>b.reason==="physical-selection-changed");for(let b of[...m,...S])if(b.path!=="."||b.size!==null||b.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(m.length>1||S.length>1)throw new Error("Native physical selection omissions must not be duplicated");let y=i?.physicalSelection,k=y?.status==="overflow"||y?.status==="overflow-and-changed",N=y?.status==="changed"||y?.status==="overflow-and-changed";if(k!==(m.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(N!==(S.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let E={schema:"comet.native.content-snapshot.v1",origin:t.origin,...i?{capture:i}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(du(E)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return E}async function fv(e,t,i={}){let r=_i(t);if(r.capture?.provider==="git"||r.capture?.projection||r.capture?.physicalSelection)return r;let n=D.resolve(e.projectRoot),a=iv(i),o=rv(i.gitSelectionLimits),s=await ov(a,e,o,i.gitSelectionHooks);if(s===null)return r;let c=new Set(lv(s).filter(g=>Pn(e,g))),l=[...s.gitlinks].filter(g=>c.has(g)),u=[...s.nestedRepositories].filter(g=>Pn(e,g)),d=(g,w)=>w.some(C=>g===C||g.startsWith(`${C}/`)),f=g=>d(g,l),p=g=>d(g,u),v=[...r.entries.map(g=>g.path),...r.omitted.flatMap(g=>g.type==="directory"?[g.path,`${g.path}/`]:[g.path])].filter(g=>!c.has(g)&&!f(g)&&!p(g)),h=await IP(a,n,v),m=r.entries.filter(g=>!f(g.path)&&!p(g.path)&&Pn(e,g.path)&&(c.has(g.path)||!h.has(g.path)));await sv(a,e,o,s,i.gitSelectionHooks?.outputChunkBytes);let S=[...s.omissions];for(let g of l)S.push({path:g,size:null,type:"directory",reason:"legacy-gitlink-boundary"});m.sort((g,w)=>g.path.localeCompare(w.path,"en"));let y=r.omitted.filter(g=>f(g.path)||p(g.path)||!Pn(e,g.path)?!1:h.has(g.path)?c.has(g.path)||[...c].some(w=>w.startsWith(`${g.path}/`)):!0);for(let g of S)y.some(w=>w.path===g.path&&w.reason===g.reason)||y.push(g);y.sort((g,w)=>g.path.localeCompare(w.path,"en"));let k=r.omissionOverflow?.count??0,N=r.omissionOverflow?.hash??K("comet.native.snapshot-omission-overflow.v1");s.overflow&&(k+=s.overflow.count,N=An(N,"git-selection",{source:"git-selection",...s.overflow}));let E=g=>{k+=1,N=An(N,"omission",g)};for(;y.length>cu;){let g=qo(y);if(g===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");E(g)}let b=()=>({...r,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:y.length+k===0,entries:m,omitted:y,omittedCount:y.length+k,...k>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${N}`,hash:N,count:k}}:{}}),x=b();for(;du(x)>r.limits.maxManifestBytes;){let g=qo(y);if(g===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");E(g),x=b()}return _i(x)}function KP(e,t){if(!cP.test(t))throw new Error(`Invalid Native change name: ${t}`);return D.join(U(e,t),"baseline-manifest.json")}async function pv(e,t={}){let i={maxFiles:t.limits?.maxFiles??Lo.maxFiles,maxFileBytes:t.limits?.maxFileBytes??Lo.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??Lo.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??Lo.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},r=uv(t.policy),n=iv({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=rv(t.gitSelectionLimits),o=AP(t.physicalSelectionLimits);if(i.maxFiles<1||i.maxFileBytes<1||i.maxTotalBytes<1||i.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=D.resolve(e.projectRoot),c=await X.realpath(s),l=D.resolve(e.nativeRoot),u=await X.realpath(l),d=D.resolve(e.runtimeDir),f=D.resolve(e.configFile),p=D.join(s,".comet","current-change.json"),v=VP(s,t.denylist??[]),h=[],m=[],S=new Map,y=new Map,k=0,N=0,E=K("comet.native.snapshot-omission-overflow.v1"),b=0,x=!1,g=null,w=_=>{N+=1,E=An(E,"omission",_)},C=_=>{if(k+=1,m.length<cu){m.push(_);return}if(su(_)){let A=qo(m);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");w(A),m.push(_);return}w(_)},$=_=>{k+=_.count,N+=_.count,E=An(E,"git-selection",{source:"git-selection",..._})},T=_=>{N+=1,E=An(E,"manifest-entry",{reason:"manifest-size",entry:_})},pe=async(_,A)=>{h.push(_),b+=_.size,S.set(_.path,A),x||(x=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(_.path))},Q=(_,A)=>{let I=h.findIndex(Y=>Y.path===_);if(I<0)return;let[B]=h.splice(I,1);b-=B.size,S.delete(_),C(A)},G=async(_,A,I,B)=>{if(!I.isFile()||I.isSymbolicLink()||!j(n))return;let Y;try{Y=await X.realpath(_)}catch(R){if(!j(n))return;if(!se(R)&&!oe(R))throw R;C({path:A,size:I.size,type:"file",reason:oe(R)?"changed-during-read":"unreadable"});return}if(!j(n)||!V(c,Y)||nt(u,Y))return;if(h.length>=i.maxFiles){C({path:A,size:I.size,type:"file",reason:"file-count"});return}if(I.size>i.maxFileBytes){C({path:A,size:I.size,type:"file",reason:"file-size"});return}if(b+I.size>i.maxTotalBytes){C({path:A,size:I.size,type:"file",reason:"total-size"});return}let M,O,ee;try{if(M=await WP(Y,I.size,I,n),M.status==="budget-exhausted"||!j(n))return;if(M.status==="changed"){C({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!j(n)||(ee=await X.realpath(_),!j(n)))return;O=await X.lstat(_)}catch(R){if(!j(n))return;if(!se(R)&&!oe(R))throw R;C({path:A,size:I.size,type:"file",reason:oe(R)?"changed-during-read":"unreadable"});return}if(j(n)){if(M.bytes!==I.size||ee!==Y||!ai(I,M.finalStat)||!ai(M.finalStat,O)||!O.isFile()||O.isSymbolicLink()||O.size!==I.size||O.mtimeMs!==I.mtimeMs||O.ctimeMs!==I.ctimeMs){C({path:A,size:O.isFile()?O.size:null,type:O.isFile()?"file":"other",reason:"changed-during-read"});return}j(n)&&await pe({path:A,hash:M.hash,size:O.size,type:"file",...B===void 0?{}:{gitObjectId:B}},{kind:"file",target:_,realTarget:Y,stat:O})}},lt=async(_,A,I)=>{if(!j(n))return;let B,Y,M;try{if(B=await X.readlink(_,{encoding:"buffer"}),!j(n)||(M=await X.lstat(_),!j(n)))return;Y=await X.readlink(_,{encoding:"buffer"})}catch(R){if(!j(n))return;if(!se(R)&&!oe(R))throw R;C({path:A,size:null,type:"other",reason:oe(R)?"changed-during-read":"unreadable"});return}if(!j(n))return;if(!M.isSymbolicLink()||!ai(I,M)||M.mtimeMs!==I.mtimeMs||M.ctimeMs!==I.ctimeMs||!B.equals(Y)){C({path:A,size:null,type:"other",reason:"changed-during-read"});return}let O=B.byteLength;if(h.length>=i.maxFiles){C({path:A,size:O,type:"other",reason:"file-count"});return}if(O>i.maxFileBytes){C({path:A,size:O,type:"other",reason:"file-size"});return}if(b+O>i.maxTotalBytes){C({path:A,size:O,type:"other",reason:"total-size"});return}let ee=Mo("sha256").update("symlink\0").update(B).digest("hex");j(n)&&await pe({path:A,hash:ee,size:O,type:"file"},{kind:"symlink",target:_,rawTarget:B,stat:M})},Ge=async()=>{for(let[_,A]of[...S]){if(!j(n))return;if(A.kind==="file"){let O,ee;try{if(O=await X.realpath(A.target),!j(n))return;ee=await X.lstat(A.target)}catch(R){if(!j(n))return;if(!se(R)&&!oe(R))throw R;Q(_,{path:_,size:null,type:"file",reason:se(R)?"unreadable":"changed-during-read"});continue}if(!j(n))return;(O!==A.realTarget||!ee.isFile()||ee.isSymbolicLink()||!ai(A.stat,ee)||ee.size!==A.stat.size||ee.mtimeMs!==A.stat.mtimeMs||ee.ctimeMs!==A.stat.ctimeMs)&&Q(_,{path:_,size:ee.isFile()?ee.size:null,type:ee.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let O,ee;try{if(O=await X.lstat(A.target),!j(n))return;ee=await X.readlink(A.target,{encoding:"buffer"})}catch(R){if(!j(n))return;if(!se(R)&&!oe(R))throw R;Q(_,{path:_,size:null,type:"other",reason:se(R)?"unreadable":"changed-during-read"});continue}if(!j(n))return;(!O.isSymbolicLink()||!ai(A.stat,O)||O.mtimeMs!==A.stat.mtimeMs||O.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(ee))&&Q(_,{path:_,size:null,type:"other",reason:"changed-during-read"});continue}let I,B;try{if(I=await X.realpath(A.target),!j(n))return;B=await X.lstat(A.target)}catch{if(!j(n))return;Q(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!j(n))return;if(!(I===A.realTarget&&B.isDirectory()&&!B.isSymbolicLink()&&ai(A.stat,B)&&V(c,I)&&!nt(u,I))){Q(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let M;try{if(!j(n))return;M=await Km(n,I)}catch(O){if(pr(O))throw O;Q(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!j(n))return;M.dirty?Q(_,{path:_,size:null,type:"directory",reason:"gitlink-dirty"}):M.hash!==A.hash&&Q(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"})}for(let[_,A]of y){if(!j(n))return;try{let I=await X.lstat(A);if(!j(n))return;C({path:_,size:I.isFile()?I.size:null,type:I.isFile()?"file":I.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(I){if(!j(n))return;if(oe(I))continue;if(!se(I))throw I;C({path:_,size:null,type:"file",reason:"unreadable"})}}},Re=await ov(n,e,a,t.gitSelectionHooks);if(Re===null){let _=await Gm({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let B of _.records){if(B.type!=="file"&&B.type!=="symlink"||S.has(B.path))continue;if(rt(n)<1)break;if(!Xm(r,B.path,n))continue;if(rt(n)<1)break;let Y=D.resolve(s,...B.path.split("/")),M;try{M=await X.lstat(Y)}catch(O){if(!j(n))break;if(!se(O)&&!oe(O))throw O;C({path:B.path,size:null,type:"file",reason:oe(O)?"changed-during-read":"unreadable"});continue}if(rt(n)<1)break;if(B.type==="symlink"&&M.isSymbolicLink()){if(await lt(Y,B.path,M),rt(n)<1)break;continue}if(B.type!=="file"||!M.isFile()||M.isSymbolicLink()){C({path:B.path,size:M.isFile()?M.size:null,type:M.isDirectory()?"directory":M.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await G(Y,B.path,M),rt(n)<1)break}rt(n)>=1&&await Ge();let A=await Gm({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o}),I=BP(_.evidence,A.evidence);g=I.evidence;for(let B of[..._.omissions,...A.omissions,...I.omissions])m.some(Y=>Y.path===B.path&&Y.reason===B.reason)||C(B)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let _=t.incrementalBaseline,A=new Map,I=!1;if(_){let R=_i(_);for(let Z of R.entries)Z.gitObjectId!==void 0&&A.set(Z.path,Z);I=A.size>0}let B=new Set,Y=!0;try{let R=await Rn(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(R.overflow)I=!1,Y=!1,A.clear();else for(let Z of R.records){let te=Fo(Z),we=te.indexOf(" "),he=we<0?null:hr(te.slice(we+1));if(we!==1||he===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");te[0]!=="H"&&B.add(he)}}catch(R){if(pr(R))throw R;I=!1,Y=!1,A.clear()}let M=new Set;try{let R=await Vo(n,s,["ls-files","--modified","-z"],ou);for(let Z of R.toString("utf8").split("\0")){let te=hr(Z);te!==null&&M.add(te)}}catch{I=!1,Y=!1,A.clear()}let O=new Set,ee=new Set;for(let R of lv(Re)){if(S.has(R)||!Pn(e,R))continue;if(rt(n)<1)break;if(!Xm(r,R,n))continue;if(rt(n)<1)break;let Z=D.resolve(s,...R.split("/"));if(Z===f||Z===p||nt(d,Z)||v.some(Ae=>nt(Ae,Z)))continue;if(Re.gitlinks.has(R)){if(h.length>=i.maxFiles){C({path:R,size:0,type:"file",reason:"file-count"});continue}let Ae,na;try{[Ae,na]=await Promise.all([X.realpath(Z),X.lstat(Z)])}catch{C({path:R,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(na.isSymbolicLink()||!na.isDirectory()||!V(c,Ae)||nt(u,Ae)){C({path:R,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let Li=await Km(n,Ae);if(Li.dirty){C({path:R,size:null,type:"directory",reason:"gitlink-dirty"});continue}await pe({path:R,hash:Li.hash,size:0,type:"file"},{kind:"gitlink",target:Z,realTarget:Ae,stat:na,hash:Li.hash})}catch(Li){if(pr(Li))throw Li;C({path:R,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let te;try{te=await X.lstat(Z)}catch(Ae){if(oe(Ae)&&Re.tracked.has(R)){y.set(R,Z);continue}if(!se(Ae)&&!oe(Ae))throw Ae;C({path:R,size:null,type:"file",reason:oe(Ae)?"changed-during-read":"unreadable"});continue}if(te.isSymbolicLink()){await lt(Z,R,te);continue}if(!te.isFile()){Re.nestedRepositories.has(R)||C({path:R,size:null,type:"other",reason:"changed-during-read"});continue}let we=Re.trackedObjectIds.get(R),he=we?A.get(R):void 0;if(I&&he?.gitObjectId!==void 0&&he.gitObjectId===we&&!B.has(R)&&!M.has(R)){if(h.length>=i.maxFiles){C({path:R,size:he.size,type:"file",reason:"file-count"});continue}if(he.size>i.maxFileBytes){C({path:R,size:he.size,type:"file",reason:"file-size"});continue}if(b+he.size>i.maxTotalBytes){C({path:R,size:he.size,type:"file",reason:"total-size"});continue}h.push({...he}),b+=he.size,O.add(R);continue}let qd=Y&&!B.has(R)&&!M.has(R)?we:void 0;await G(Z,R,te,qd),qd!==void 0&&ee.add(R)}if(await Ge(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await sv(n,e,a,Re,t.gitSelectionHooks?.outputChunkBytes),O.size>0||I&&ee.size>0){let R=await Vo(n,s,["ls-files","--modified","-z"],ou),Z=new Set;for(let te of R.toString("utf8").split("\0")){let we=hr(te);we!==null&&Z.add(we)}for(let te of O){if(!Z.has(te))continue;let we=h.find(he=>he.path===te);Q(te,{path:te,size:we?.size??null,type:"file",reason:"changed-during-read"})}for(let te of ee){if(!Z.has(te))continue;let we=h.find(he=>he.path===te);we&&delete we.gitObjectId}}for(let R of Re.omissions)C(R);Re.overflow&&$(Re.overflow)}h.sort((_,A)=>_.path.localeCompare(A.path,"en")),m.sort((_,A)=>_.path.localeCompare(A.path,"en"));let Wy=Re===null?{provider:"physical-tree",...g?{physicalSelection:g}:{}}:{provider:"git",...Re.evidence?{gitSelection:Re.evidence}:{}},Fd=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:Wy,createdAt:(t.now??new Date).toISOString(),complete:k===0,limits:i,...r?{policy:r.manifest}:{},entries:h,omitted:m,omittedCount:k,...N>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${E}`,hash:E,count:N}}:{}}),Vs=Fd();for(;du(Vs)>i.maxManifestBytes;){if(m.filter(A=>!su(A)).length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let I=0;I<A;I+=1){let B=qo(m);if(B===null)break;w(B)}}else if(h.length>0){let A=Math.max(1,Math.ceil(h.length/4));for(let I of h.splice(-A))k+=1,T(I)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");Vs=Fd()}return Vs}async function fu(e,t,i={}){let n=(await Ie(e.projectRoot))?.native.snapshot??Bl;return pv(e,{...i,policy:t.policy,incrementalBaseline:t,limits:{maxFiles:n.max_files,maxFileBytes:n.max_total_bytes,maxTotalBytes:n.max_total_bytes,maxDurationMs:n.max_duration_ms},deadlineMs:n.max_duration_ms})}async function zo(e,t){let i=KP(e,t),r=ue(e,i);await z(r,i);try{let n=await Bm({root:r,file:i,maxBytes:sP,label:"Native baseline snapshot manifest"});return _i(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as hR}from"crypto";import mR from"path";var qe=Object.freeze({stateRef:"runtime/run-state.json",pendingRef:"runtime/pending-action.json",trajectoryRef:"runtime/trajectory.jsonl",contextRef:"runtime/context.md",artifactsRef:"runtime/artifacts.json",checkpointRef:"runtime/checkpoints/latest.json",snapshotsRef:"runtime/skill-snapshots"});import{constants as Jo,promises as at}from"node:fs";import ot from"node:path";import{TextDecoder as lR}from"node:util";import aR from"path";var tR=Or(Xi(),1);var gD=4*1024*1024;var iR=null;function rR(e,t){let i=e;for(let r of t)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function hv(e,t){return(...i)=>{let r=iR;if(r===null)return t(...i);let n=rR(`async:${e}`,i),a=r.entries.get(n);if(a)return a.value;let o=t(...i).catch(s=>{throw r.entries.delete(n),s});return r.entries.set(n,{value:o}),o}}var kD=hv("hookWritePolicy",async e=>(await Tl(e))?.hook??{allow_paths:[]});var mv=(e,t)=>{let i=e[t];return i==null?null:String(i)};function In(e,t){let i=e[t];if(typeof i!="string"||i.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return i}function _n(e,t){let i=In(e,t);if(aR.isAbsolute(i)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(i)||i.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return i}function oR(e){let t=e.run_retries??"{}",i;try{i=typeof t=="string"?JSON.parse(t):t}catch(r){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:r})}if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let r of Object.values(i))if(!Number.isInteger(r)||Number(r)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return i}function vv(e){if(!e.run_id)return null;let t=In(e,"run_id"),i=In(e,"skill"),r=In(e,"skill_version"),n=In(e,"skill_hash"),a=_n(e,"pending_ref"),o=_n(e,"trajectory_ref"),s=_n(e,"context_ref"),c=_n(e,"artifacts_ref"),l=_n(e,"checkpoint_ref"),u=Number(e.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(e.orchestration!=="deterministic"&&e.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(e.run_status!=="running"&&e.run_status!=="waiting"&&e.run_status!=="completed"&&e.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:t,skill:i,skillVersion:r,skillHash:n,orchestration:e.orchestration,currentStep:mv(e,"current_step"),iteration:u,pending:mv(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:oR(e)}}var NB=256*1024;var sR=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function cR(e){let t={run_id:e.runId,skill:e.skill,skill_version:e.skillVersion,skill_hash:e.skillHash,orchestration:e.orchestration,current_step:e.currentStep,iteration:e.iteration,pending:e.pending,pending_ref:e.pendingRef,trajectory_ref:e.trajectoryRef,context_ref:e.contextRef,artifacts_ref:e.artifactsRef,checkpoint_ref:e.checkpointRef,run_status:e.status,run_retries:JSON.stringify(e.retries)},i=vv(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function pu(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Run state: stored value must be an object");let t=e,i=Object.keys(t).find(r=>!sR.has(r));if(i)throw new Error(`Invalid Run state: unknown field ${i}`);if(t.currentStep!==null&&(typeof t.currentStep!="string"||t.currentStep.length===0))throw new Error("Invalid Run state: currentStep must be a non-empty string or null");if(t.pending!==null&&(typeof t.pending!="string"||t.pending.length===0))throw new Error("Invalid Run state: pending must be a non-empty string or null");if(!t.retries||typeof t.retries!="object"||Array.isArray(t.retries))throw new Error("Invalid Run state: retries must be an object");return cR(t)}var vr={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};function Uo(e,t){let i=ot.relative(e,t);return i===""||!ot.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ot.sep}`)}function uR(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Go(e,t){return q({...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 dR(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Ko(e,t,i){let r=qe[t];if(i!==void 0&&i!==r)throw new Error(`Native Run ${t} ref must be ${r}`);let n=ot.resolve(e),a=ot.resolve(n,...r.slice(8).split("/"));if(!Uo(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function gv(e){let t=await at.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await at.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function fR(e,t){let i=ot.resolve(e),r=ot.resolve(t);if(!Uo(i,r))throw new Error("Native Run path is outside its change");let n=[await gv(i)],a=i;for(let o of ot.relative(i,r).split(ot.sep).filter(Boolean)){a=ot.join(a,o);let s;try{s=await gv(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!Uo(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function wv(e){for(let t of e){let i=await at.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!dR(t,i)||await at.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function pR(e,t,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${i} exceeds ${t} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function Yo(e,t,i,r,n){let a=await fR(e,ot.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await at.lstat(t)}catch(d){if(d.code==="ENOENT")return null;throw d}if(!o.isFile()||o.isSymbolicLink())throw new Error(`${r} must be a regular file`);if(o.size>i)throw new Error(`${r} exceeds ${i} bytes`);let s=uR(o),c=await at.realpath(t);if(!Uo(a[0].realPath,c))throw new Error(`${r} resolves outside its change`);let l=process.platform==="win32"?Jo.O_RDONLY:Jo.O_RDONLY|Jo.O_NOFOLLOW|Jo.O_NONBLOCK,u;try{u=await at.open(t,l)}catch(d){throw new Error(`${r} changed while opening`,{cause:d})}try{let[d,f,p]=await Promise.all([u.stat(),at.lstat(t),at.realpath(t)]);if(await wv(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||p!==c||!Go(s,d)||!Go(s,f))throw new Error(`${r} changed while opening`);await n?.afterOpen?.();let v=await pR(u,i,r);await n?.beforeFinalCheck?.();let[h,m,S]=await Promise.all([u.stat(),at.lstat(t),at.realpath(t)]);if(await wv(a),!m.isFile()||m.isSymbolicLink()||S!==c||!Go(s,h)||!Go(s,m))throw new Error(`${r} changed while reading`);let y;try{y=new lR("utf-8",{fatal:!0}).decode(v)}catch(k){throw new Error(`${r} is not valid UTF-8`,{cause:k})}return{text:y,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}function yv(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function hu(e){return pu(e)}async function gr(e,t){let i=Ko(e,"stateRef"),r=await Yo(e,i,vr.runStateBytes,"Native Run state",t);return r?pu(yv(r.text,"Native Run state")):null}async function Ii(e,t,i){let r=Ko(e,"trajectoryRef",t),n=await Yo(e,r,vr.trajectoryBytes,"Native Run trajectory",i);if(!n)return[];let a=n.text.split(/\r?\n/u).map((o,s)=>({line:o,number:s+1})).filter(({line:o})=>o.length>0);if(a.length>vr.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${vr.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 Nv(e,t,i){return(await Yo(e,Ko(e,"trajectoryRef",t),vr.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function Xo(e,t,i){let r=await Yo(e,Ko(e,"checkpointRef",t),vr.checkpointBytes,"Native Run checkpoint",i);return r?yv(r.text,"Native Run checkpoint"):null}var vR=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function mu(e){return hR("sha256").update(e).digest("hex")}function gR(e,t){if(!vR.test(t))throw new Error(`Invalid Native change name: ${t}`);return mR.join(U(e,t),"trajectory.jsonl")}function wR(e){let t=e.split(/\n/u),i=0;for(let r=0;r<t.length;r+=1){let n=t[r].endsWith("\r")?t[r].slice(0,-1):t[r];if(n.length!==0){i=r+1;try{JSON.parse(n)}catch(a){return{status:"invalid",line:r+1,message:a.message}}}}return{status:"valid",count:i}}function yR(e,t){if(/Unexpected end|Unterminated string/iu.test(e.message))return!0;let i=/position (\d+)/iu.exec(e.message)?.[1];return i!==void 0&&Number(i)>=Math.max(0,t.length-1)}function NR(e,t){let i=t.lastIndexOf(10),r=t.subarray(0,i+1),n=wR(r.toString("utf8"));if(n.status==="invalid")return{status:"invalid",file:e,line:n.line,message:n.message};if(i===t.length-1)return{status:"clean",file:e};let a=t.subarray(i+1),o=a.toString("utf8"),s=n.count+1,c,l;try{JSON.parse(o.endsWith("\r")?o.slice(0,-1):o),c="missing-newline",l=Buffer.concat([t,Buffer.from(`
160
- `)])}catch(d){if(!yR(d,o))return{status:"invalid",file:e,line:s,message:d.message};c="incomplete-json",l=r}return{inspection:{status:"repairable",file:e,reason:c,line:s,originalHash:mu(t),targetHash:mu(l),tailHash:mu(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function bR(e,t){let i=gR(e,t);await z(ue(e,i),i);let r=U(e,t),n=await Nv(r,qe.trajectoryRef);return n===null?{status:"clean",file:i}:NR(i,Buffer.from(n))}async function bv(e,t){let i=await bR(e,t);return"inspection"in i?i.inspection:i}import{createHash as kR}from"node:crypto";import{promises as Qo}from"node:fs";import Tt from"node:path";var Tn=/^[a-f0-9]{64}$/u,kv=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,SR=16*1024,gu=process.platform,ER=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function wr(e){return ER.has(e)}function xv(e,t){let i=Tt.relative(e,t);return Tt.isAbsolute(i)||i===".."||i.startsWith(`..${Tt.sep}`)?null:i.replaceAll("\\","/")||"."}function Pv(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function Rv(e,t){if(e.length===0||Pv(e)||e.includes("\\")||Tt.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let i=Tt.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function wu(e,t){return kR("sha256").update(`${e}
159
+ ${Buffer.byteLength(r)}:${r}`)}function su(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function qo(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!su(i))return e.splice(t,1),i}return null}function ai(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return _e(i,r)?q(i,r):q(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function JP(e,t,i,r){if(!j(r))return{status:"budget-exhausted"};let n;try{n=await X.open(e,"r")}catch(c){if(!j(r))return{status:"budget-exhausted"};throw c}if(!j(r))return await n.close(),{status:"budget-exhausted"};let a=Mo("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!j(r))return{status:"budget-exhausted"};let c=await n.stat();if(!j(r))return{status:"budget-exhausted"};if(!c.isFile()||!ai(i,c))return{status:"changed"};for(;;){if(!j(r))return{status:"budget-exhausted"};let l=t+1-s;if(l<1)return{status:"changed"};let u=await n.read(o,0,Math.min(o.length,l),null);if(!j(r))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!j(r))return{status:"budget-exhausted"};let d=await n.stat();return j(r)?!d.isFile()||!ai(c,d)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:d}:{status:"budget-exhausted"}}if(s+u.bytesRead>t)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await n.close()}}function Ve(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Fe(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function fr(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function vt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function dv(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let i=D.posix.normalize(e);if(i!==e||D.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function GP(e,t){let i=Ve(e,`Native snapshot entry ${t}`);Fe(i,NP,`Native snapshot entry ${t}`);let r=dv(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!Wo.test(i.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(i.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:r,hash:i.hash,size:vt(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!tv.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=i.gitObjectId}return n}function UP(e,t){let i=Ve(e,`Native snapshot omission ${t}`);if(Fe(i,bP,`Native snapshot omission ${t}`),!EP.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!CP.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:dv(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:vt(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function KP(e){let t=Ve(e,"Native snapshot omission overflow");if(Fe(t,kP,"Native snapshot omission overflow"),typeof t.hash!="string"||!Wo.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let i=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==i)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:i,hash:t.hash,count:fr(t.count,"Native snapshot omission overflow count")}}function dr(e,t){let i=Ve(e,t);if(Fe(i,gP,t),typeof i.hash!="string"||!Wo.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let r=vt(i.recordCount,`${t} recordCount`),n=vt(i.storedRecordCount,`${t} storedRecordCount`),a=vt(i.stdoutBytes,`${t} stdoutBytes`);if(n>r||!i.overflow&&n!==r)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,recordCount:r,storedRecordCount:n,stdoutBytes:a,overflow:i.overflow}}function Qm(e){let t=Ve(e,"Native Git selection evidence");if(Fe(t,vP,"Native Git selection evidence"),t.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let i=dr(t.stageBefore,"Native Git selection stageBefore"),r=dr(t.combined,"Native Git selection combined"),n=dr(t.stageAfter,"Native Git selection stageAfter"),a=dr(t.finalStageBefore,"Native Git selection finalStageBefore"),o=dr(t.finalCombined,"Native Git selection finalCombined"),s=dr(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,r,n,a,o,s].some(d=>d.overflow),l=!oi(i,n)||!oi(n,a)||!oi(r,o)||!oi(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(t.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:i,combined:r,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function Zm(e,t){let i=Ve(e,t);if(Fe(i,yP,t),typeof i.hash!="string"||!Wo.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean"||typeof i.unstable!="boolean")throw new Error(`${t} flags are invalid`);let r=vt(i.visitedNodeCount,`${t} visitedNodeCount`),n=vt(i.recordCount,`${t} recordCount`),a=vt(i.storedRecordCount,`${t} storedRecordCount`),o=vt(i.encodedBytes,`${t} encodedBytes`);if(a>n||!i.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,visitedNodeCount:r,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:i.overflow,unstable:i.unstable}}function YP(e){let t=Ve(e,"Native physical selection evidence");if(Fe(t,wP,"Native physical selection evidence"),t.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let i=Zm(t.before,"Native physical selection before"),r=Zm(t.after,"Native physical selection after"),n=i.overflow||r.overflow,a=i.unstable||r.unstable||!cv(i,r);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:i,after:r}}function _i(e){let t=Ve(e,"Native content snapshot manifest");if(Fe(t,dP,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!SP.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let b=Ve(t.capture,"Native content snapshot capture");if(Fe(b,hP,"Native content snapshot capture"),b.provider!=="git"&&b.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let x=b.gitSelection===void 0?void 0:Qm(b.gitSelection),g=b.physicalSelection===void 0?void 0:YP(b.physicalSelection),w=null;if(b.projection!==void 0){let C=Ve(b.projection,"Native content snapshot projection");if(Fe(C,mP,"Native content snapshot projection"),C.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");w={provider:"git",...C.selection===void 0?{}:{selection:Qm(C.selection)}}}if(b.provider==="git"){if(g||w)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...x?{gitSelection:x}:{}}}else{if(x)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(g&&w)throw new Error("Native physical-tree capture cannot combine selection and projection");i=w?{provider:"physical-tree",projection:w}:{provider:"physical-tree",...g?{physicalSelection:g}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let r=Ve(t.limits,"Native content snapshot limits");Fe(r,fP,"Native content snapshot limits");let n={maxFiles:fr(r.maxFiles,"Native snapshot maxFiles"),maxFileBytes:fr(r.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:fr(r.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:fr(r.maxManifestBytes,"Native snapshot maxManifestBytes"),...r.maxDurationMs===void 0?{}:{maxDurationMs:fr(r.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let b=Ve(t.policy,"Native snapshot policy");if(Fe(b,pP,"Native snapshot policy"),b.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(b.include)||!Array.isArray(b.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=uv({include:b.include,exclude:b.exclude,hash:b.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(GP),s=t.omitted.map(UP),c=vt(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:KP(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(b=>b.size>n.maxFileBytes)||o.reduce((b,x)=>b+x.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(b=>b.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>cu||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(b=>b.reason==="git-enumeration-limit"),f=s.filter(b=>b.reason==="git-selection-changed");for(let b of[...d,...f])if(b.path!=="."||b.size!==null||b.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let p=i?.provider==="git"?i.gitSelection:i?.projection?.selection,v=p?.status==="overflow"||p?.status==="overflow-and-changed",h=p?.status==="changed"||p?.status==="overflow-and-changed";if(v!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let m=s.filter(b=>b.reason==="physical-enumeration-limit"),S=s.filter(b=>b.reason==="physical-selection-changed");for(let b of[...m,...S])if(b.path!=="."||b.size!==null||b.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(m.length>1||S.length>1)throw new Error("Native physical selection omissions must not be duplicated");let y=i?.physicalSelection,k=y?.status==="overflow"||y?.status==="overflow-and-changed",N=y?.status==="changed"||y?.status==="overflow-and-changed";if(k!==(m.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(N!==(S.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let E={schema:"comet.native.content-snapshot.v1",origin:t.origin,...i?{capture:i}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(du(E)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return E}async function fv(e,t,i={}){let r=_i(t);if(r.capture?.provider==="git"||r.capture?.projection||r.capture?.physicalSelection)return r;let n=D.resolve(e.projectRoot),a=iv(i),o=rv(i.gitSelectionLimits),s=await ov(a,e,o,i.gitSelectionHooks);if(s===null)return r;let c=new Set(lv(s).filter(g=>Pn(e,g))),l=[...s.gitlinks].filter(g=>c.has(g)),u=[...s.nestedRepositories].filter(g=>Pn(e,g)),d=(g,w)=>w.some(C=>g===C||g.startsWith(`${C}/`)),f=g=>d(g,l),p=g=>d(g,u),v=[...r.entries.map(g=>g.path),...r.omitted.flatMap(g=>g.type==="directory"?[g.path,`${g.path}/`]:[g.path])].filter(g=>!c.has(g)&&!f(g)&&!p(g)),h=await jP(a,n,v),m=r.entries.filter(g=>!f(g.path)&&!p(g.path)&&Pn(e,g.path)&&(c.has(g.path)||!h.has(g.path)));await sv(a,e,o,s,i.gitSelectionHooks?.outputChunkBytes);let S=[...s.omissions];for(let g of l)S.push({path:g,size:null,type:"directory",reason:"legacy-gitlink-boundary"});m.sort((g,w)=>g.path.localeCompare(w.path,"en"));let y=r.omitted.filter(g=>f(g.path)||p(g.path)||!Pn(e,g.path)?!1:h.has(g.path)?c.has(g.path)||[...c].some(w=>w.startsWith(`${g.path}/`)):!0);for(let g of S)y.some(w=>w.path===g.path&&w.reason===g.reason)||y.push(g);y.sort((g,w)=>g.path.localeCompare(w.path,"en"));let k=r.omissionOverflow?.count??0,N=r.omissionOverflow?.hash??K("comet.native.snapshot-omission-overflow.v1");s.overflow&&(k+=s.overflow.count,N=An(N,"git-selection",{source:"git-selection",...s.overflow}));let E=g=>{k+=1,N=An(N,"omission",g)};for(;y.length>cu;){let g=qo(y);if(g===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");E(g)}let b=()=>({...r,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:y.length+k===0,entries:m,omitted:y,omittedCount:y.length+k,...k>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${N}`,hash:N,count:k}}:{}}),x=b();for(;du(x)>r.limits.maxManifestBytes;){let g=qo(y);if(g===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");E(g),x=b()}return _i(x)}function XP(e,t){if(!uP.test(t))throw new Error(`Invalid Native change name: ${t}`);return D.join(U(e,t),"baseline-manifest.json")}async function pv(e,t={}){let i={maxFiles:t.limits?.maxFiles??Lo.maxFiles,maxFileBytes:t.limits?.maxFileBytes??Lo.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??Lo.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??Lo.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},r=uv(t.policy),n=iv({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=rv(t.gitSelectionLimits),o=IP(t.physicalSelectionLimits);if(i.maxFiles<1||i.maxFileBytes<1||i.maxTotalBytes<1||i.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=D.resolve(e.projectRoot),c=await X.realpath(s),l=D.resolve(e.nativeRoot),u=await X.realpath(l),d=D.resolve(e.runtimeDir),f=D.resolve(e.configFile),p=D.join(s,".comet","current-change.json"),v=qP(s,t.denylist??[]),h=[],m=[],S=new Map,y=new Map,k=0,N=0,E=K("comet.native.snapshot-omission-overflow.v1"),b=0,x=!1,g=null,w=_=>{N+=1,E=An(E,"omission",_)},C=_=>{if(k+=1,m.length<cu){m.push(_);return}if(su(_)){let A=qo(m);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");w(A),m.push(_);return}w(_)},$=_=>{k+=_.count,N+=_.count,E=An(E,"git-selection",{source:"git-selection",..._})},T=_=>{N+=1,E=An(E,"manifest-entry",{reason:"manifest-size",entry:_})},pe=async(_,A)=>{h.push(_),b+=_.size,S.set(_.path,A),x||(x=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(_.path))},Q=(_,A)=>{let I=h.findIndex(Y=>Y.path===_);if(I<0)return;let[B]=h.splice(I,1);b-=B.size,S.delete(_),C(A)},G=async(_,A,I,B)=>{if(!I.isFile()||I.isSymbolicLink()||!j(n))return;let Y;try{Y=await X.realpath(_)}catch(R){if(!j(n))return;if(!se(R)&&!oe(R))throw R;C({path:A,size:I.size,type:"file",reason:oe(R)?"changed-during-read":"unreadable"});return}if(!j(n)||!V(c,Y)||nt(u,Y))return;if(h.length>=i.maxFiles){C({path:A,size:I.size,type:"file",reason:"file-count"});return}if(I.size>i.maxFileBytes){C({path:A,size:I.size,type:"file",reason:"file-size"});return}if(b+I.size>i.maxTotalBytes){C({path:A,size:I.size,type:"file",reason:"total-size"});return}let M,O,ee;try{if(M=await JP(Y,I.size,I,n),M.status==="budget-exhausted"||!j(n))return;if(M.status==="changed"){C({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!j(n)||(ee=await X.realpath(_),!j(n)))return;O=await X.lstat(_)}catch(R){if(!j(n))return;if(!se(R)&&!oe(R))throw R;C({path:A,size:I.size,type:"file",reason:oe(R)?"changed-during-read":"unreadable"});return}if(j(n)){if(M.bytes!==I.size||ee!==Y||!ai(I,M.finalStat)||!ai(M.finalStat,O)||!O.isFile()||O.isSymbolicLink()||O.size!==I.size||O.mtimeMs!==I.mtimeMs||O.ctimeMs!==I.ctimeMs){C({path:A,size:O.isFile()?O.size:null,type:O.isFile()?"file":"other",reason:"changed-during-read"});return}j(n)&&await pe({path:A,hash:M.hash,size:O.size,type:"file",...B===void 0?{}:{gitObjectId:B}},{kind:"file",target:_,realTarget:Y,stat:O})}},lt=async(_,A,I)=>{if(!j(n))return;let B,Y,M;try{if(B=await X.readlink(_,{encoding:"buffer"}),!j(n)||(M=await X.lstat(_),!j(n)))return;Y=await X.readlink(_,{encoding:"buffer"})}catch(R){if(!j(n))return;if(!se(R)&&!oe(R))throw R;C({path:A,size:null,type:"other",reason:oe(R)?"changed-during-read":"unreadable"});return}if(!j(n))return;if(!M.isSymbolicLink()||!ai(I,M)||M.mtimeMs!==I.mtimeMs||M.ctimeMs!==I.ctimeMs||!B.equals(Y)){C({path:A,size:null,type:"other",reason:"changed-during-read"});return}let O=B.byteLength;if(h.length>=i.maxFiles){C({path:A,size:O,type:"other",reason:"file-count"});return}if(O>i.maxFileBytes){C({path:A,size:O,type:"other",reason:"file-size"});return}if(b+O>i.maxTotalBytes){C({path:A,size:O,type:"other",reason:"total-size"});return}let ee=Mo("sha256").update("symlink\0").update(B).digest("hex");j(n)&&await pe({path:A,hash:ee,size:O,type:"file"},{kind:"symlink",target:_,rawTarget:B,stat:M})},Ge=async()=>{for(let[_,A]of[...S]){if(!j(n))return;if(A.kind==="file"){let O,ee;try{if(O=await X.realpath(A.target),!j(n))return;ee=await X.lstat(A.target)}catch(R){if(!j(n))return;if(!se(R)&&!oe(R))throw R;Q(_,{path:_,size:null,type:"file",reason:se(R)?"unreadable":"changed-during-read"});continue}if(!j(n))return;(O!==A.realTarget||!ee.isFile()||ee.isSymbolicLink()||!ai(A.stat,ee)||ee.size!==A.stat.size||ee.mtimeMs!==A.stat.mtimeMs||ee.ctimeMs!==A.stat.ctimeMs)&&Q(_,{path:_,size:ee.isFile()?ee.size:null,type:ee.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let O,ee;try{if(O=await X.lstat(A.target),!j(n))return;ee=await X.readlink(A.target,{encoding:"buffer"})}catch(R){if(!j(n))return;if(!se(R)&&!oe(R))throw R;Q(_,{path:_,size:null,type:"other",reason:se(R)?"unreadable":"changed-during-read"});continue}if(!j(n))return;(!O.isSymbolicLink()||!ai(A.stat,O)||O.mtimeMs!==A.stat.mtimeMs||O.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(ee))&&Q(_,{path:_,size:null,type:"other",reason:"changed-during-read"});continue}let I,B;try{if(I=await X.realpath(A.target),!j(n))return;B=await X.lstat(A.target)}catch{if(!j(n))return;Q(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!j(n))return;if(!(I===A.realTarget&&B.isDirectory()&&!B.isSymbolicLink()&&ai(A.stat,B)&&V(c,I)&&!nt(u,I))){Q(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let M;try{if(!j(n))return;M=await Km(n,I)}catch(O){if(pr(O))throw O;Q(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!j(n))return;M.dirty?Q(_,{path:_,size:null,type:"directory",reason:"gitlink-dirty"}):M.hash!==A.hash&&Q(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"})}for(let[_,A]of y){if(!j(n))return;try{let I=await X.lstat(A);if(!j(n))return;C({path:_,size:I.isFile()?I.size:null,type:I.isFile()?"file":I.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(I){if(!j(n))return;if(oe(I))continue;if(!se(I))throw I;C({path:_,size:null,type:"file",reason:"unreadable"})}}},Re=await ov(n,e,a,t.gitSelectionHooks);if(Re===null){let _=await Gm({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let B of _.records){if(B.type!=="file"&&B.type!=="symlink"||S.has(B.path))continue;if(rt(n)<1)break;if(!Xm(r,B.path,n))continue;if(rt(n)<1)break;let Y=D.resolve(s,...B.path.split("/")),M;try{M=await X.lstat(Y)}catch(O){if(!j(n))break;if(!se(O)&&!oe(O))throw O;C({path:B.path,size:null,type:"file",reason:oe(O)?"changed-during-read":"unreadable"});continue}if(rt(n)<1)break;if(B.type==="symlink"&&M.isSymbolicLink()){if(await lt(Y,B.path,M),rt(n)<1)break;continue}if(B.type!=="file"||!M.isFile()||M.isSymbolicLink()){C({path:B.path,size:M.isFile()?M.size:null,type:M.isDirectory()?"directory":M.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await G(Y,B.path,M),rt(n)<1)break}rt(n)>=1&&await Ge();let A=await Gm({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o}),I=VP(_.evidence,A.evidence);g=I.evidence;for(let B of[..._.omissions,...A.omissions,...I.omissions])m.some(Y=>Y.path===B.path&&Y.reason===B.reason)||C(B)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let _=t.incrementalBaseline,A=new Map,I=!1;if(_){let R=_i(_);for(let Z of R.entries)Z.gitObjectId!==void 0&&A.set(Z.path,Z);I=A.size>0}let B=new Set,Y=!0;try{let R=await Rn(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(R.overflow)I=!1,Y=!1,A.clear();else for(let Z of R.records){let te=Fo(Z),we=te.indexOf(" "),he=we<0?null:hr(te.slice(we+1));if(we!==1||he===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");te[0]!=="H"&&B.add(he)}}catch(R){if(pr(R))throw R;I=!1,Y=!1,A.clear()}let M=new Set;try{let R=await Vo(n,s,["ls-files","--modified","-z"],ou);for(let Z of R.toString("utf8").split("\0")){let te=hr(Z);te!==null&&M.add(te)}}catch{I=!1,Y=!1,A.clear()}let O=new Set,ee=new Set;for(let R of lv(Re)){if(S.has(R)||!Pn(e,R))continue;if(rt(n)<1)break;if(!Xm(r,R,n))continue;if(rt(n)<1)break;let Z=D.resolve(s,...R.split("/"));if(Z===f||Z===p||nt(d,Z)||v.some(Ae=>nt(Ae,Z)))continue;if(Re.gitlinks.has(R)){if(h.length>=i.maxFiles){C({path:R,size:0,type:"file",reason:"file-count"});continue}let Ae,na;try{[Ae,na]=await Promise.all([X.realpath(Z),X.lstat(Z)])}catch{C({path:R,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(na.isSymbolicLink()||!na.isDirectory()||!V(c,Ae)||nt(u,Ae)){C({path:R,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let Li=await Km(n,Ae);if(Li.dirty){C({path:R,size:null,type:"directory",reason:"gitlink-dirty"});continue}await pe({path:R,hash:Li.hash,size:0,type:"file"},{kind:"gitlink",target:Z,realTarget:Ae,stat:na,hash:Li.hash})}catch(Li){if(pr(Li))throw Li;C({path:R,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let te;try{te=await X.lstat(Z)}catch(Ae){if(oe(Ae)&&Re.tracked.has(R)){y.set(R,Z);continue}if(!se(Ae)&&!oe(Ae))throw Ae;C({path:R,size:null,type:"file",reason:oe(Ae)?"changed-during-read":"unreadable"});continue}if(te.isSymbolicLink()){await lt(Z,R,te);continue}if(!te.isFile()){Re.nestedRepositories.has(R)||C({path:R,size:null,type:"other",reason:"changed-during-read"});continue}let we=Re.trackedObjectIds.get(R),he=we?A.get(R):void 0;if(I&&he?.gitObjectId!==void 0&&he.gitObjectId===we&&!B.has(R)&&!M.has(R)){if(h.length>=i.maxFiles){C({path:R,size:he.size,type:"file",reason:"file-count"});continue}if(he.size>i.maxFileBytes){C({path:R,size:he.size,type:"file",reason:"file-size"});continue}if(b+he.size>i.maxTotalBytes){C({path:R,size:he.size,type:"file",reason:"total-size"});continue}h.push({...he}),b+=he.size,O.add(R);continue}let qd=Y&&!B.has(R)&&!M.has(R)?we:void 0;await G(Z,R,te,qd),qd!==void 0&&ee.add(R)}if(await Ge(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await sv(n,e,a,Re,t.gitSelectionHooks?.outputChunkBytes),O.size>0||I&&ee.size>0){let R=await Vo(n,s,["ls-files","--modified","-z"],ou),Z=new Set;for(let te of R.toString("utf8").split("\0")){let we=hr(te);we!==null&&Z.add(we)}for(let te of O){if(!Z.has(te))continue;let we=h.find(he=>he.path===te);Q(te,{path:te,size:we?.size??null,type:"file",reason:"changed-during-read"})}for(let te of ee){if(!Z.has(te))continue;let we=h.find(he=>he.path===te);we&&delete we.gitObjectId}}for(let R of Re.omissions)C(R);Re.overflow&&$(Re.overflow)}h.sort((_,A)=>_.path.localeCompare(A.path,"en")),m.sort((_,A)=>_.path.localeCompare(A.path,"en"));let Jy=Re===null?{provider:"physical-tree",...g?{physicalSelection:g}:{}}:{provider:"git",...Re.evidence?{gitSelection:Re.evidence}:{}},Fd=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:Jy,createdAt:(t.now??new Date).toISOString(),complete:k===0,limits:i,...r?{policy:r.manifest}:{},entries:h,omitted:m,omittedCount:k,...N>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${E}`,hash:E,count:N}}:{}}),Vs=Fd();for(;du(Vs)>i.maxManifestBytes;){if(m.filter(A=>!su(A)).length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let I=0;I<A;I+=1){let B=qo(m);if(B===null)break;w(B)}}else if(h.length>0){let A=Math.max(1,Math.ceil(h.length/4));for(let I of h.splice(-A))k+=1,T(I)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");Vs=Fd()}return Vs}async function fu(e,t,i={}){let n=(await Ie(e.projectRoot))?.native.snapshot??Bl;return pv(e,{...i,policy:t.policy,incrementalBaseline:t,limits:{maxFiles:n.max_files,maxFileBytes:n.max_total_bytes,maxTotalBytes:n.max_total_bytes,maxDurationMs:n.max_duration_ms},deadlineMs:n.max_duration_ms})}async function zo(e,t){let i=XP(e,t),r=ue(e,i);await z(r,i);try{let n=await Bm({root:r,file:i,maxBytes:lP,label:"Native baseline snapshot manifest"});return _i(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as vR}from"crypto";import gR from"path";var qe=Object.freeze({stateRef:"runtime/run-state.json",pendingRef:"runtime/pending-action.json",trajectoryRef:"runtime/trajectory.jsonl",contextRef:"runtime/context.md",artifactsRef:"runtime/artifacts.json",checkpointRef:"runtime/checkpoints/latest.json",snapshotsRef:"runtime/skill-snapshots"});import{constants as Jo,promises as at}from"node:fs";import ot from"node:path";import{TextDecoder as dR}from"node:util";import sR from"path";var rR=Or(Xi(),1);var wD=4*1024*1024;var nR=null;function aR(e,t){let i=e;for(let r of t)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function hv(e,t){return(...i)=>{let r=nR;if(r===null)return t(...i);let n=aR(`async:${e}`,i),a=r.entries.get(n);if(a)return a.value;let o=t(...i).catch(s=>{throw r.entries.delete(n),s});return r.entries.set(n,{value:o}),o}}var SD=hv("hookWritePolicy",async e=>(await Tl(e))?.hook??{allow_paths:[]});var mv=(e,t)=>{let i=e[t];return i==null?null:String(i)};function In(e,t){let i=e[t];if(typeof i!="string"||i.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return i}function _n(e,t){let i=In(e,t);if(sR.isAbsolute(i)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(i)||i.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return i}function cR(e){let t=e.run_retries??"{}",i;try{i=typeof t=="string"?JSON.parse(t):t}catch(r){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:r})}if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let r of Object.values(i))if(!Number.isInteger(r)||Number(r)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return i}function vv(e){if(!e.run_id)return null;let t=In(e,"run_id"),i=In(e,"skill"),r=In(e,"skill_version"),n=In(e,"skill_hash"),a=_n(e,"pending_ref"),o=_n(e,"trajectory_ref"),s=_n(e,"context_ref"),c=_n(e,"artifacts_ref"),l=_n(e,"checkpoint_ref"),u=Number(e.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(e.orchestration!=="deterministic"&&e.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(e.run_status!=="running"&&e.run_status!=="waiting"&&e.run_status!=="completed"&&e.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:t,skill:i,skillVersion:r,skillHash:n,orchestration:e.orchestration,currentStep:mv(e,"current_step"),iteration:u,pending:mv(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:cR(e)}}var bB=256*1024;var lR=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function uR(e){let t={run_id:e.runId,skill:e.skill,skill_version:e.skillVersion,skill_hash:e.skillHash,orchestration:e.orchestration,current_step:e.currentStep,iteration:e.iteration,pending:e.pending,pending_ref:e.pendingRef,trajectory_ref:e.trajectoryRef,context_ref:e.contextRef,artifacts_ref:e.artifactsRef,checkpoint_ref:e.checkpointRef,run_status:e.status,run_retries:JSON.stringify(e.retries)},i=vv(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function pu(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Run state: stored value must be an object");let t=e,i=Object.keys(t).find(r=>!lR.has(r));if(i)throw new Error(`Invalid Run state: unknown field ${i}`);if(t.currentStep!==null&&(typeof t.currentStep!="string"||t.currentStep.length===0))throw new Error("Invalid Run state: currentStep must be a non-empty string or null");if(t.pending!==null&&(typeof t.pending!="string"||t.pending.length===0))throw new Error("Invalid Run state: pending must be a non-empty string or null");if(!t.retries||typeof t.retries!="object"||Array.isArray(t.retries))throw new Error("Invalid Run state: retries must be an object");return uR(t)}var vr={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};function Uo(e,t){let i=ot.relative(e,t);return i===""||!ot.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ot.sep}`)}function fR(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Go(e,t){return q({...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 pR(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Ko(e,t,i){let r=qe[t];if(i!==void 0&&i!==r)throw new Error(`Native Run ${t} ref must be ${r}`);let n=ot.resolve(e),a=ot.resolve(n,...r.slice(8).split("/"));if(!Uo(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function gv(e){let t=await at.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await at.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function hR(e,t){let i=ot.resolve(e),r=ot.resolve(t);if(!Uo(i,r))throw new Error("Native Run path is outside its change");let n=[await gv(i)],a=i;for(let o of ot.relative(i,r).split(ot.sep).filter(Boolean)){a=ot.join(a,o);let s;try{s=await gv(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!Uo(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function wv(e){for(let t of e){let i=await at.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!pR(t,i)||await at.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function mR(e,t,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${i} exceeds ${t} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function Yo(e,t,i,r,n){let a=await hR(e,ot.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await at.lstat(t)}catch(d){if(d.code==="ENOENT")return null;throw d}if(!o.isFile()||o.isSymbolicLink())throw new Error(`${r} must be a regular file`);if(o.size>i)throw new Error(`${r} exceeds ${i} bytes`);let s=fR(o),c=await at.realpath(t);if(!Uo(a[0].realPath,c))throw new Error(`${r} resolves outside its change`);let l=process.platform==="win32"?Jo.O_RDONLY:Jo.O_RDONLY|Jo.O_NOFOLLOW|Jo.O_NONBLOCK,u;try{u=await at.open(t,l)}catch(d){throw new Error(`${r} changed while opening`,{cause:d})}try{let[d,f,p]=await Promise.all([u.stat(),at.lstat(t),at.realpath(t)]);if(await wv(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||p!==c||!Go(s,d)||!Go(s,f))throw new Error(`${r} changed while opening`);await n?.afterOpen?.();let v=await mR(u,i,r);await n?.beforeFinalCheck?.();let[h,m,S]=await Promise.all([u.stat(),at.lstat(t),at.realpath(t)]);if(await wv(a),!m.isFile()||m.isSymbolicLink()||S!==c||!Go(s,h)||!Go(s,m))throw new Error(`${r} changed while reading`);let y;try{y=new dR("utf-8",{fatal:!0}).decode(v)}catch(k){throw new Error(`${r} is not valid UTF-8`,{cause:k})}return{text:y,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}function yv(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function hu(e){return pu(e)}async function gr(e,t){let i=Ko(e,"stateRef"),r=await Yo(e,i,vr.runStateBytes,"Native Run state",t);return r?pu(yv(r.text,"Native Run state")):null}async function Ii(e,t,i){let r=Ko(e,"trajectoryRef",t),n=await Yo(e,r,vr.trajectoryBytes,"Native Run trajectory",i);if(!n)return[];let a=n.text.split(/\r?\n/u).map((o,s)=>({line:o,number:s+1})).filter(({line:o})=>o.length>0);if(a.length>vr.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${vr.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 Nv(e,t,i){return(await Yo(e,Ko(e,"trajectoryRef",t),vr.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function Xo(e,t,i){let r=await Yo(e,Ko(e,"checkpointRef",t),vr.checkpointBytes,"Native Run checkpoint",i);return r?yv(r.text,"Native Run checkpoint"):null}var wR=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function mu(e){return vR("sha256").update(e).digest("hex")}function yR(e,t){if(!wR.test(t))throw new Error(`Invalid Native change name: ${t}`);return gR.join(U(e,t),"trajectory.jsonl")}function NR(e){let t=e.split(/\n/u),i=0;for(let r=0;r<t.length;r+=1){let n=t[r].endsWith("\r")?t[r].slice(0,-1):t[r];if(n.length!==0){i=r+1;try{JSON.parse(n)}catch(a){return{status:"invalid",line:r+1,message:a.message}}}}return{status:"valid",count:i}}function bR(e,t){if(/Unexpected end|Unterminated string/iu.test(e.message))return!0;let i=/position (\d+)/iu.exec(e.message)?.[1];return i!==void 0&&Number(i)>=Math.max(0,t.length-1)}function kR(e,t){let i=t.lastIndexOf(10),r=t.subarray(0,i+1),n=NR(r.toString("utf8"));if(n.status==="invalid")return{status:"invalid",file:e,line:n.line,message:n.message};if(i===t.length-1)return{status:"clean",file:e};let a=t.subarray(i+1),o=a.toString("utf8"),s=n.count+1,c,l;try{JSON.parse(o.endsWith("\r")?o.slice(0,-1):o),c="missing-newline",l=Buffer.concat([t,Buffer.from(`
160
+ `)])}catch(d){if(!bR(d,o))return{status:"invalid",file:e,line:s,message:d.message};c="incomplete-json",l=r}return{inspection:{status:"repairable",file:e,reason:c,line:s,originalHash:mu(t),targetHash:mu(l),tailHash:mu(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function SR(e,t){let i=yR(e,t);await z(ue(e,i),i);let r=U(e,t),n=await Nv(r,qe.trajectoryRef);return n===null?{status:"clean",file:i}:kR(i,Buffer.from(n))}async function bv(e,t){let i=await SR(e,t);return"inspection"in i?i.inspection:i}import{createHash as ER}from"node:crypto";import{promises as Qo}from"node:fs";import Tt from"node:path";var Tn=/^[a-f0-9]{64}$/u,kv=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,CR=16*1024,gu=process.platform,xR=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function wr(e){return xR.has(e)}function xv(e,t){let i=Tt.relative(e,t);return Tt.isAbsolute(i)||i===".."||i.startsWith(`..${Tt.sep}`)?null:i.replaceAll("\\","/")||"."}function Pv(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function Rv(e,t){if(e.length===0||Pv(e)||e.includes("\\")||Tt.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let i=Tt.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function wu(e,t){return ER("sha256").update(`${e}
161
161
  ${t}`).digest("hex")}async function Sv(e,t){let i=await Qo.realpath(t),r=await Qo.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=gu==="win32"?Tt.normalize(i).toLowerCase():i;return wu(e,`${n}
162
162
  ${r.dev}
163
163
  ${r.ino}
164
- ${r.birthtimeMs}`)}async function Ev(e,t){let i=await Qo.realpath(t),r=await Qo.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=gu==="win32"?Tt.normalize(i).toLowerCase():i;return wu(e,n)}function CR(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 vu(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||Pv(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function Av(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(vu(e.changeBranch,"Native workspace change branch"),vu(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 xR(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,i=new Set(["provider","baseCommit","targetBranch","targetCommit"]),r=Object.keys(t).filter(n=>!i.has(n));if(r.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${r.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!kv.test(t.baseCommit)||typeof t.targetCommit!="string"||!kv.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");vu(t.targetBranch,"Native workspace Git target branch")}function Zo(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,i=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),r=Object.keys(t).filter(o=>!i.has(o));if(r.length>0)throw new Error(`Native workspace identity has unknown field(s): ${r.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!Tn.test(String(t.projectRootId))||!Tn.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");CR(t.capturedAt),Rv(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&&!Tn.test(String(t.projectRootPathId))||a&&!Tn.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Tn.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&xR(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(Av(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 PR(e,t){return Tt.join(U(e,t),"workspace.json")}function RR(e,t){let i=PR(e,t),r=ue(e,i),n=xv(r,i);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:r,ref:Rv(n,"Native workspace file ref")}}async function AR(e,t){try{let i=RR(e,t),r=await re({root:i.root,ref:i.ref,maxBytes:SR});return JSON.parse(r.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function _v(e,t){let i=Ee(e.projectRoot),r={projectRoot:Tt.resolve(e.projectRoot),currentBranch:i.currentBranch,isSecondaryWorktree:i.isSecondaryWorktree};try{let n=await jt(e,t);if(n===null)return{...r,bindingState:"missing",isolation:null,changeBranch:null,targetBranch:null,finish:null};if(n.schema!=="comet.native.workspace.v3")return{...r,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:n.git?.targetBranch??null,finish:null};let a=await jn({paths:e,identity:n});return{...r,bindingState:a.state==="aligned"?"aligned":"drifted",isolation:n.isolation,changeBranch:n.changeBranch,targetBranch:n.targetBranch,finish:n.finish}}catch{return{...r,bindingState:"invalid",isolation:null,changeBranch:null,targetBranch:null,finish:null}}}async function _R(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=xv(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let i=Ee(e.paths.projectRoot),r=i.isGitWorktree?Ei(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??i.currentBranch,a=n==null?null:Ei(e.paths.projectRoot,n),o=r!==null&&n!==null&&n!==void 0&&a!==null?{provider:"git",baseCommit:r,targetBranch:n,targetCommit:a}:void 0,[s,c,l,u]=await Promise.all([Sv("comet.native.workspace-project-root.v2",e.paths.projectRoot),Sv("comet.native.workspace-native-root.v2",e.paths.nativeRoot),Ev("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),Ev("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&&Av(e.binding);let f={capturedAt:d,capturedRevision:e.revision,nativeRootRef:t,projectRootId:s,nativeRootId:c,projectRootPathId:l,nativeRootPathId:u,...o?{git:o}:{},...e.sessionId?{sessionHash:wu("comet.native.workspace-session.v2",`${s}
164
+ ${r.birthtimeMs}`)}async function Ev(e,t){let i=await Qo.realpath(t),r=await Qo.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=gu==="win32"?Tt.normalize(i).toLowerCase():i;return wu(e,n)}function PR(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 vu(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||Pv(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function Av(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(vu(e.changeBranch,"Native workspace change branch"),vu(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 RR(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,i=new Set(["provider","baseCommit","targetBranch","targetCommit"]),r=Object.keys(t).filter(n=>!i.has(n));if(r.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${r.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!kv.test(t.baseCommit)||typeof t.targetCommit!="string"||!kv.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");vu(t.targetBranch,"Native workspace Git target branch")}function Zo(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,i=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),r=Object.keys(t).filter(o=>!i.has(o));if(r.length>0)throw new Error(`Native workspace identity has unknown field(s): ${r.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!Tn.test(String(t.projectRootId))||!Tn.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");PR(t.capturedAt),Rv(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&&!Tn.test(String(t.projectRootPathId))||a&&!Tn.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Tn.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&RR(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(Av(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 AR(e,t){return Tt.join(U(e,t),"workspace.json")}function _R(e,t){let i=AR(e,t),r=ue(e,i),n=xv(r,i);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:r,ref:Rv(n,"Native workspace file ref")}}async function IR(e,t){try{let i=_R(e,t),r=await re({root:i.root,ref:i.ref,maxBytes:CR});return JSON.parse(r.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function _v(e,t){let i=Ee(e.projectRoot),r={projectRoot:Tt.resolve(e.projectRoot),currentBranch:i.currentBranch,isSecondaryWorktree:i.isSecondaryWorktree};try{let n=await jt(e,t);if(n===null)return{...r,bindingState:"missing",isolation:null,changeBranch:null,targetBranch:null,finish:null};if(n.schema!=="comet.native.workspace.v3")return{...r,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:n.git?.targetBranch??null,finish:null};let a=await jn({paths:e,identity:n});return{...r,bindingState:a.state==="aligned"?"aligned":"drifted",isolation:n.isolation,changeBranch:n.changeBranch,targetBranch:n.targetBranch,finish:n.finish}}catch{return{...r,bindingState:"invalid",isolation:null,changeBranch:null,targetBranch:null,finish:null}}}async function TR(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=xv(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let i=Ee(e.paths.projectRoot),r=i.isGitWorktree?Ei(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??i.currentBranch,a=n==null?null:Ei(e.paths.projectRoot,n),o=r!==null&&n!==null&&n!==void 0&&a!==null?{provider:"git",baseCommit:r,targetBranch:n,targetCommit:a}:void 0,[s,c,l,u]=await Promise.all([Sv("comet.native.workspace-project-root.v2",e.paths.projectRoot),Sv("comet.native.workspace-native-root.v2",e.paths.nativeRoot),Ev("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),Ev("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&&Av(e.binding);let f={capturedAt:d,capturedRevision:e.revision,nativeRootRef:t,projectRootId:s,nativeRootId:c,projectRootPathId:l,nativeRootPathId:u,...o?{git:o}:{},...e.sessionId?{sessionHash:wu("comet.native.workspace-session.v2",`${s}
165
165
  ${c}
166
- ${e.sessionId}`)}:{}},p=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return Zo(p),p}async function jt(e,t){let i=await AR(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(Zo(i),i)}async function es(e){Zo(e.identity);let t=await _R({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),i=[],r=[];return t.nativeRootRef!==e.identity.nativeRootRef&&i.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&i.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&i.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&i.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&i.push("native-root-legacy-identity")),gu==="win32"&&i.length>0&&i.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?r.push("workspace-inspection-unavailable"):i.length>0&&r.push("workspace-root-changed"),{state:r.length===0?"aligned":r.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:r,driftComponents:i}}async function jn(e){if(Zo(e.identity),e.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await es(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=Ee(e.paths.projectRoot);return e.identity.changeBranch===null?i.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:i.isGitWorktree?i.currentBranch!==e.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${e.identity.changeBranch}, but the current branch is ${i.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!i.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function Iv(e,t){let i=await jt(e,t);if(i===null)return null;let r=await jn({paths:e,identity:i});if(r.state==="drifted")throw new Error(`${r.code}: ${r.message}`);return i}var $v=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],TR=new Set($v),Ov=new Set([...$v,"minimum_runtime_version","revision"]),jR=new Set([...Ov,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),$R=new Set(["capability","operation","source","base_hash"]),OR=new Set(["shape","build","verify","archive"]),HR=new Set(["implicit","confirmed"]),DR=new Set(["pending","pass","fail"]),ji="comet-state.yaml",Nu=/^[a-f0-9]{64}$/u,Hv=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,BR=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,ts=class extends Error{constructor(i,r){super(`Native change ${i} uses ${r}; run comet native doctor ${i} --repair before mutating it`);this.change=i;this.schema=r;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},Ti=class extends Error{constructor(i,r){super(i!==Pt||r===null?`Unsupported Native change schema ${i} for runtime protocol ${3}`:`Native change ${i} requires runtime protocol ${r}; current protocol is ${3}`);this.schema=i;this.minimumRuntimeVersion=r;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},is=class extends Error{constructor(i,r,n){super(`Native change ${i} revision conflict: expected ${r}, actual ${n}`);this.change=i;this.expectedRevision=r;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},$n=class extends Error{constructor(i,r){super(`Native working directory already contains active change${r.length===1?"":"s"} ${r.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=i;this.activeChanges=r;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},rs=class extends Error{constructor(i,r,n,a,o,s=null,c=null){super(`Native change ${i} baseline is incomplete (${r} omitted entr${r===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=i;this.omittedCount=r;this.omittedByReason=n;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},wL=sa("en");function Hn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Dv(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Dn(e){if(!Hv.test(e))throw new Error(`Invalid Native change name: ${e}`)}function LR(e){if(!Hv.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Bv(e,t){if(e.length===0||si.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function VR(e,t){let i=Hn(e,`spec_changes[${t}]`);if(Dv(i,$R,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(LR(i.capability),i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`Invalid spec operation for ${i.capability}`);let r=i.source,n=i.base_hash;if(r!==void 0&&typeof r!="string")throw new Error(`Spec source for ${i.capability} must be a string`);if(typeof r=="string"&&Bv(r,`Spec source for ${i.capability}`),i.operation==="create"){if(!r)throw new Error(`Create spec ${i.capability} requires source`);if(n!==null)throw new Error(`Create spec ${i.capability} requires null base_hash`)}else if(i.operation==="replace"){if(!r)throw new Error(`Replace spec ${i.capability} requires source`);if(typeof n!="string"||!Nu.test(n))throw new Error(`Replace spec ${i.capability} requires a SHA-256 base_hash`)}else{if(r!==void 0)throw new Error(`Remove spec ${i.capability} forbids source`);if(typeof n!="string"||!Nu.test(n))throw new Error(`Remove spec ${i.capability} requires a SHA-256 base_hash`)}return{capability:i.capability,operation:i.operation,...typeof r=="string"?{source:r}:{},base_hash:n}}function FR(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 ku(e,t){if(Dv(e,t,ji),typeof e.name!="string")throw new Error("Native change name is required");if(Dn(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"||!OR.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&&!HR.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let i=e.spec_changes.map(VR),r=i.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(r.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(r)].join(", ")}`);if(typeof e.verification_result!="string"||!DR.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"&&Bv(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!FR(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:i,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function lr(e){let t=Hn(e,ji);if(t.schema!==At)throw new Error(`Expected ${At}`);return{schema:At,...ku(t,TR)}}function On(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function yu(e,t,i){if(e===null)return null;let r=typeof e=="string"?BR.exec(e):null;if(!r||r[1]!==i)throw new Error(`${t} must be null or runtime/evidence/${i}/<sha256>.json relative to the Native change`);return e}function qR(e){if(e==null)return null;if(typeof e!="string"||!Nu.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function MR(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 ur(e){let t=Hn(e,ji);if(t.schema!==Rt)throw new Error(`Expected ${Rt}`);if(On(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Rt} minimum_runtime_version must be 2`);return{schema:Rt,minimum_runtime_version:2,revision:On(t.revision,"Native v2 revision"),...ku(t,Ov)}}function ni(e){let t=Hn(e,ji);if(t.schema!==Pt){if(t.schema===At||t.schema===Rt){let o=t.schema===At?lr(t):ur(t);throw new ts(o.name,o.schema)}throw new Ti(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=On(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new Ti(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let r=On(t.revision,"Native revision"),n=ku(t,jR),a=qR(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Pt,minimum_runtime_version:3,revision:r,verification_protocol:MR(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:yu(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:yu(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:yu(t.partial_allowance,"Native partial_allowance","allowances")}}function WR(e){let t=Hn(e,ji);if(t.schema===At){let n=lr(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Pt}`}}if(t.schema===Rt){let n=ur(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Pt}`}}if(t.schema!==Pt){let n=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new Ti(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let i=On(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new Ti(t.schema,i).message};let r=ni(t);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function me(e,t){Dn(t);let i=si.join(e.changesDir,t);if(!V(e.changesDir,i))throw new Error("Native change path escaped");return i}async function ns(e,t){let i=U(e,t),r=si.join(i,"schema-migration.json");await z(V(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await jv.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Lv(e,t){let i=U(e,t),r=si.join(i,"checkpoint-journal.json");await z(V(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await jv.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function zR(e,t=si.dirname(e)){let i=si.relative(t,e).split(si.sep).join("/"),r=await re({root:t,ref:i,maxBytes:null,includeHash:!1}),n=(0,bu.parseDocument)(r.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function Su(e,t){let i=si.join(me(e,t),ji);await z(e.nativeRoot,i);let r=WR(await zR(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await ns(e,t)?{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimumRuntimeVersion,state:r.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(r.status==="current"&&r.state&&await JR(e,r.state),r)}async function JR(e,t){if(await zo(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function gt(e,t){let i=await Su(e,t);if(i.status==="migration-required")throw new ts(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new Ti(i.schema,i.minimumRuntimeVersion);return await Iv(e,t),i.state}var Fv=["outcome","scope","nonGoals","acceptanceExamples"],GR=[...Fv,"constraints","decisions","openQuestions","verificationExpectations"],UR=["acceptanceEvidence","commandsAndResults","skippedChecks","specConsistency","knownLimitationsAndRisks","conclusion"],qv={maxFileBytes:hn};function Mv(e){let t=new Map,i=null,r=[],n=()=>{i!==null&&t.set(i,r.join(`
167
- `).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(n(),i=o[1].trim(),r=[]):i!==null&&r.push(a)}return n(),t}async function KR(e,t){let i=Vv.resolve(e,...t.split(/[\\/]/u));if(!V(e,i))throw new Error(`Artifact escapes Native change: ${t}`);let r=await Eu.realpath(e),n=await Eu.realpath(i);if(!V(r,n))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await Eu.stat(n)).isFile())throw new Error(`Artifact is not a file: ${t}`);return n}function Bn(e){return{valid:e.length===0,findings:e}}function Wv(e){let t=new Set(["blocker","blocking","coverage","decision","open_question","question","requirement","requirements","source","source_coverage","state","status","决策","来源","覆盖","问题","状态","需求","阻塞"]),i=null;for(let r of e.split(/\r?\n/u)){let n=r.match(/^\s*(`{3,}|~{3,})/u);if(n){let s=n[1]?.[0];i===null?i=s:i===s&&(i=null);continue}if(i!==null)continue;let a=r.trim();if(/^(?:[-*+]\s+|\d+[.)]\s+)(?:\[[ xX]\]\s+)?\[blocking\](?=$|[\s::—-])/iu.test(a)||a.includes("|")&&a.split("|").some(s=>/^\s*\[blocking\](?=$|[\s::—-])/iu.test(s)))return!0;let o=a.match(/^([\p{L}\p{N}_./-]+)\s*[::]\s*\[blocking\](?=$|[\s::—-])/iu);if(o){let s=o[1]?.toLocaleLowerCase("en-US")??"";if(t.has(s)||/[./_-]/u.test(s))return!0}}return!1}async function Cu(e,t){let i=[],r;try{r=(await re({root:e,ref:t,maxBytes:qv.maxFileBytes})).text}catch(a){return Bn([{code:"brief-missing",message:a.message,path:t}])}let n=new Map;for(let[a,o]of Mv(r))n.set(oa(a)??a,o);for(let a of GR)n.has(a)||i.push({code:"brief-section-missing",message:`Missing brief section: ${a}`,path:t});for(let a of Fv)(n.get(a)??"").length===0&&i.push({code:"brief-section-empty",message:`Brief section is empty: ${a}`,path:t});return Wv(r)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),Bn(i)}async function xu(e,t){let i=[],r;try{r=(await re({root:e,ref:t,maxBytes:qv.maxFileBytes})).text}catch(a){return Bn([{code:"verification-missing",message:a.message,path:t}])}let n=new Map;for(let[a,o]of Mv(r))n.set(zd(a)??a,o);for(let a of UR)n.has(a)?(n.get(a)??"").length===0&&i.push({code:"verification-section-empty",message:`Verification section is empty: ${a}`,path:t}):i.push({code:"verification-section-missing",message:`Missing verification section: ${a}`,path:t});return Bn(i)}function as(e,t){return Vv.join(e.specsDir,t,"spec.md")}async function zv(e,t){let i=[],r=me(e,t.name);for(let n of t.spec_changes){let a=as(e,n.capability),o=null;try{await z(e.nativeRoot,a),o=await iu(a)}catch(s){if(s.code!=="ENOENT"){i.push({code:"spec-canonical-unsafe",message:s.message,path:a});continue}}if(n.operation==="create"&&o!==null&&i.push({code:"spec-create-exists",message:`Canonical spec already exists: ${n.capability}`,path:a}),n.operation!=="create"&&o===null&&i.push({code:"spec-base-missing",message:`Canonical spec is missing: ${n.capability}`,path:a}),n.operation!=="create"&&o!==null&&o!==n.base_hash&&i.push({code:"spec-base-conflict",message:`Canonical spec changed for ${n.capability}: expected ${n.base_hash}, actual ${o}`,path:a}),n.source)try{await KR(r,n.source)}catch(s){i.push({code:"spec-source-invalid",message:s.message,path:n.source})}}return Bn(i)}import Jv from"node:path";var YR="comet.native.contract.v1",XR="comet.native.acceptance-set.v1",Gv=/^[a-f0-9]{64}$/u,Ln={maxAcceptanceCriteria:bn.maxCriteria};function Uv(e,t){let i=Jv.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||Jv.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized project-relative ref`);return e}function Kv(e){return H("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
168
- `))}function QR(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(Gv))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(Gv))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=Uv(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:Kv(e.markdown)},markdown:e.markdown}}function ZR(e,t){return Yv(e.id,t.id)}function Yv(e,t){return e<t?-1:e>t?1:0}function Xv(e){let t=Uv(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(QR).sort((d,f)=>Yv(d.snapshot.capability,f.snapshot.capability)),r=i.map(({snapshot:d})=>d.capability);if(new Set(r).size!==r.length)throw new Error("Native contract contains duplicate capabilities");let n=[t,...i.flatMap(({snapshot:d})=>d.source===null?[]:[d.source])];if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate artifact sources");let a=Jl(e.briefMarkdown,t,Ln.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(...Gl(f,d.source,Ln.maxAcceptanceCriteria-a.length)),a.push(...Nm(f,d.source,Ln.maxAcceptanceCriteria-a.length)));if(a.sort(ZR),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>Ln.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${Ln.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:Kv(e.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=H(XR,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:H(YR,u)}}var os={maxSpecs:64,maxFileBytes:hn,maxTotalBytes:4*1024*1024};async function yr(e){if(e.specChanges.length>os.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await re({root:e.changeDir,ref:e.briefRef,maxBytes:os.maxFileBytes}),i=t.size,r=[];for(let n of e.specChanges){if(n.operation==="remove"){r.push({capability:n.capability,operation:"remove",source:null,baseHash:n.base_hash,markdown:null});continue}if(!n.source)throw new Error(`Native contract ${n.capability} has no proposed spec source`);let a=await re({root:e.changeDir,ref:n.source,maxBytes:os.maxFileBytes});if(i+=a.size,i>os.maxTotalBytes)throw new Error("Native contract exceeds its total byte budget");r.push({capability:n.capability,operation:n.operation,source:a.ref,baseHash:n.base_hash,markdown:a.text})}return{contract:Xv({briefSource:t.ref,briefMarkdown:t.text,specs:r}),sourceCount:r.filter(n=>n.source!==null).length+1,totalBytes:i}}import{randomUUID as eA}from"crypto";import{promises as ss}from"fs";import Zv from"path";var Pu="comet.selection.v2",tA=16*1024;function Ru(e){return Zv.join(e,".comet","current-change.json")}function iA(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Qv(e){return e===null||typeof e=="string"}function eg(e){let t;try{t=JSON.parse(e)}catch(i){throw new Error(`current change selection contains invalid JSON: ${i instanceof Error?i.message:String(i)}`,{cause:i})}if(!iA(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&&!Qv(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Pu,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Pu)throw new Error(`current change selection schema must be ${Pu}`);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(!Qv(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 tg(e){let t;try{let r=Ru(e),{bytes:n}=await Pi(r,tA,{label:"current change selection"});t=n.toString("utf8")}catch(r){if(r.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${r instanceof Error?r.message:String(r)}`,{cause:r})}return{status:"selected",...eg(t)}}async function ig(e,t){let i=eg(JSON.stringify(t));if(i.legacy)throw new Error("cannot write a legacy current change selection");let r=Ru(e),n=`${r}.${eA()}.tmp`;await ss.mkdir(Zv.dirname(r),{recursive:!0});try{await ss.writeFile(n,`${JSON.stringify(i.selection,null,2)}
169
- `,"utf8"),await ss.rename(n,r)}catch(a){throw await ss.rm(n,{force:!0}),a}}import{promises as UA}from"node:fs";import Lu from"node:path";var Ou=Or(Xi(),1);import{promises as hg}from"node:fs";import Me from"node:path";import{execFileSync as rA}from"node:child_process";var nA=3e4,aA=8*1024*1024,Au=class extends Error{constructor(i,r,n){super(`git ${r.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=i;this.args=r;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr};function oA(e,t){try{return rA("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:nA,maxBuffer:aA,windowsHide:!0})}catch(i){let r=typeof i.stderr=="string"?i.stderr.trim():Buffer.isBuffer(i.stderr)?i.stderr.toString("utf8").trim():"";throw new Au(e,t,r)}}function cs(e,t){return oA(e,t).trim()}import Iu from"node:path";import{promises as rg}from"node:fs";var ls=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var _u="comet.native.supervisor.v2",cA=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function lA(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native Supervisor parent name: ${e}`);return`comet/supervisor/${e}/integration`}function uA(e,t){return Iu.join(ii(e,t),"supervisor")}function us(e,t){return Iu.join(uA(e,t),"state.json")}function ng(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!==_u)throw new Error(`Native Supervisor state schema must be ${_u}`);if(!Number.isSafeInteger(t.stateVersion)||typeof t.stateVersion!="number"||t.stateVersion<1)throw new Error("Native Supervisor state version is invalid");if(typeof t.parent!="string"||!t.parent)throw new Error("Native Supervisor state parent is invalid");if(!t.integration||typeof t.integration!="object")throw new Error("Native Supervisor integration state is missing");for(let[n,a]of Object.entries(t.integration))if(typeof a!="string"||a.length===0)throw new Error(`Native Supervisor integration field ${n} is invalid`);if(Vn(t.integration.targetCommit,"Native Supervisor target commit"),Vn(t.integration.headCommit,"Native Supervisor integration head commit"),!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let i=new Set,r=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(i.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(i.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.projectRoot!==void 0&&n.projectRoot!==null&&(typeof n.projectRoot!="string"||n.projectRoot.length===0))throw new Error(`Native Supervisor child ${n.name} projectRoot is invalid`);for(let[a,o]of[["base",n.baseCommit],["candidate",n.candidateCommit],["verified",n.verifiedCommit],["integration",n.integrationCommit]])o!==null&&Vn(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(Vn(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),r.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(r.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.role==="builder"&&n.status!=="active"||n.task.role==="verifier"&&!["active","needs-reverify"].includes(n.status))throw new Error(`Native Supervisor child ${n.name} task status is invalid`)}}}async function $i(e,t){try{let i=await rg.readFile(us(e,t),"utf8"),r=JSON.parse(i);return ng(r),r}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Tu(e,t){ng(t),await rg.mkdir(e.changesRuntimeDir,{recursive:!0}),await Qe(us(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function Vn(e,t){if(!cA.test(e))throw new Error(`${t} must be a Git commit`)}function dA(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function ag(e){Vn(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:r})=>r)),i=e.contract.children.map(r=>({name:r.name,summary:r.summary,dependsOn:[...r.depends_on],status:r.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null}));for(let r of i)for(let n of r.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${r.name} depends on unknown child ${n}`);return{schema:_u,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:i,history:[],finalVerification:{status:"pending",summary:null}}}async function ju(e){let t=lA(e.parent),i=Ei(e.paths.projectRoot,t);if(!i)return null;let r=Ei(e.paths.projectRoot,e.targetBranch);if(!r)return null;let n=Zi(e.paths.projectRoot).map(o=>Iu.resolve(o)).find(o=>Ee(o).currentBranch===t);if(!n)return null;let a=ag({parent:e.parent,targetBranch:e.targetBranch,targetCommit:r,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(i!==r){for(let o of a.children)o.status=o.dependsOn.length===0?"blocked":"pending",o.blocker=o.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;a.integration.headCommit=i}return dA(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function og(e){let t=e.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.dependsOn],covers:[],status:i.status,phase:null,projectRoot:i.projectRoot??i.task?.projectRoot??null,message:i.blocker}));return{contractHash:null,confirmed:!0,parentBranch:e.integration.branch,children:t,readyChildren:t.filter(({status:i})=>i==="ready").map(({name:i})=>i),allDone:t.every(({status:i})=>i==="integrated"||i==="archived")}}var sg="children.yaml",Fn="comet.native.children.v1",Nr="comet.native.children.v2",mg=Nr,fA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,cg=new Set(["schema","children"]),pA=new Set(["schema","acceptance_index","children"]),hA=new Set(["name","depends_on","covers"]),mA=new Set(["name","summary","depends_on"]),vA=new Set(["name","depends_on","covers"]);function fs(e,t,i=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${i}`);return e}function ds(e,t,i){let r=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(r.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...r.length>0?[`unexpected ${r.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${i} fields are invalid: ${a.join("; ")}`)}}function lg(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((i,r)=>i.localeCompare(r,"en"))}function $u(e,t){let i=Me.normalize(Me.resolve(e)),r=Me.normalize(Me.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function gA(e){let t=new Map(e.map(a=>[a.name,a])),i=new Set,r=new Set,n=a=>{if(!r.has(a)){if(i.has(a))throw new Error(`Native children dependency cycle includes ${a}`);i.add(a);for(let o of t.get(a).depends_on)n(o);i.delete(a),r.add(a)}};for(let a of e)n(a.name)}function ug(e,t,i=t){let r=new Set(t);for(let o of e){let s=o.covers.filter(c=>!r.has(c));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=i.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function wA(e,t,i){let r={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===mg&&e.acceptance_index){let n=i.requiredAcceptanceIds??t??[],a=i.allowedAcceptanceIds??n,o=Object.keys(e.acceptance_index);r.missing=n.filter(l=>!(l in e.acceptance_index)),r.extra=o.filter(l=>!a.includes(l));let s=new Map((i.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of o){let u=s.get(l),d=e.acceptance_index[l];u&&d&&(d.source!==u.source||d.text!==u.text)&&r.mismatched.push(l)}let c=new Set(o);for(let l of e.children)r.unknownCovers.push(...l.covers.filter(u=>!c.has(u)));return r.uncovered=o.filter(l=>!dg(e.children,l)),fg(r)?r:null}if(e.schema===Fn&&t){let n=new Set(t);for(let a of e.children)r.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return r.uncovered=t.filter(a=>!dg(e.children,a)),fg(r)?r:null}return null}function dg(e,t){return e.some(i=>i.covers.includes(t))}function fg(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function vg(e){let t=new Set(e.acceptance.map(({id:n})=>n)),i=new Set(e.acceptance.filter(({source:n})=>n===e.brief).map(({id:n})=>n)),r=new Set(i);for(let n of e.history.filter(({outcome:a})=>a==="fail"))for(let a of n.unresolved_ids)t.has(a)&&r.add(a);if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let n=[...e.history].reverse().find(({outcome:a})=>a==="fail");for(let a of n?.unresolved_ids??[])i.add(a)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...i],allowedAcceptanceIds:[...r]}}function yA(e){let t=fs(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),i={};for(let[r,n]of Object.entries(t)){let a=fs(n,`Native children acceptance_index.${r}`);if(ds(a,new Set(["source","text"]),`Native children acceptance_index.${r}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${r}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${r}.text must be a non-empty string`);i[r]={source:a.source,text:a.text}}return i}function NA(e,t,i){let r=i.requiredAcceptanceIds??t??[],n=i.allowedAcceptanceIds??r,a=Object.keys(e),o=r.filter(l=>!(l in e)),s=a.filter(l=>!n.includes(l));if(o.length>0||s.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${o.join(", ")||"none"}; extra ${s.join(", ")||"none"}`);let c=new Map((i.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of a){let u=c.get(l);if(!u)continue;let d=e[l];if(d.source!==u.source||d.text!==u.text){let f=["source","text"].filter(p=>d[p]!==u[p]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${f.join(", ")} exactly from the current acceptance catalog`)}}}function bA(e,t,i={}){let r=(0,Ou.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${r.errors[0].message}`);let n=fs(r.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==Fn&&a!==Nr)throw ds(n,cg,"Native children contract"),new Error(`Native children schema must be ${Fn} or ${Nr}`);let o=a===Fn?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(ds(n,o==="indexed-v2"?pA:cg,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let c=n.children.map((f,p)=>{let v=fs(f,`Native child ${p}`);if(ds(v,o==="indexed-v2"?vA:o==="summary-v2"?mA:hA,`Native ${s} child fields (child ${p})`),typeof v.name!="string"||!fA.test(v.name))throw new Error(`Native child ${p} name is invalid`);let h=o==="summary-v2";if(h){if(typeof v.summary!="string"||v.summary.trim().length===0)throw new Error(`Native child ${v.name} summary must be a non-empty string`);if(v.summary.length>2e3)throw new Error(`Native child ${v.name} summary exceeds 2000 characters`)}return{name:v.name,summary:h?v.summary:null,depends_on:lg(v.depends_on,`Native child ${v.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?lg(v.covers,`Native child ${v.name} covers`):[]}}),l=c.map(({name:f})=>f);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let u=new Set(l);for(let f of c){let p=f.depends_on.filter(v=>!u.has(v));if(p.length>0)throw new Error(`Native child ${f.name} depends on unknown child: ${p.join(", ")}`)}gA(c);let d=i.policy==="advisory";if(a===mg){if(o==="indexed-v2"){let f=yA(n.acceptance_index);d||NA(f,t,i);let p=Object.keys(f);return d||ug(c,p,p),{schema:Nr,acceptance_index:f,children:c}}return{schema:Nr,children:c}}return t&&!d&&ug(c,t),{schema:Fn,children:c}}async function ps(e){let t=Me.join(e.changeDir,sg);try{await hg.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let i=await re({root:e.changeDir,ref:sg}),r=e.policy==="advisory",n=r?{...e.validation,policy:"advisory"}:e.validation??{},a=bA(i.text,e.acceptanceIds,n);return{contract:a,hash:i.hash,size:i.size,drift:r?wA(a,e.acceptanceIds,e.validation??{}):null}}function kA(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let i=e.slice(t.index+t[0].length);return i.split(/^#\s+/mu,1)[0]??i}function SA(e){let t=kA(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let i=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),r=t.match(/\bChild\s+\d+\b/giu);return Math.max(i?.length??0,r?.length??0)>=2}async function gg(e){try{let t=await re({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return SA(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function wg(e){return H("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:i,text:r})=>({id:t,source:i,text:r})),children:e.children})}async function EA(e){let t=Zi(e.projectRoot);t.some(r=>$u(r,e.projectRoot))||t.push(e.projectRoot);let i=[];for(let r of[...new Set(t.map(n=>Me.resolve(n)))]){let n=await Ie(r);n&&i.push({projectRoot:r,paths:await Ri(r,n.native.artifact_root),parent:$u(r,e.projectRoot)})}return i.some(({parent:r})=>r)||i.push({projectRoot:e.projectRoot,paths:e,parent:!0}),i}async function CA(e,t){let i=Me.join(e.paths.changesDir,t,"comet-state.yaml");try{return await En(i)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function xA(e,t){let i;try{i=await hg.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[];for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=Me.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await En(o);t.has(s.name)&&r.push({file:o,state:s})}catch{}return r}function PA(e,t,i){let r=Me.relative(e.projectRoot,t);if(!r||r===".."||r.startsWith(`..${Me.sep}`))return null;let n=r.split(Me.sep).join("/");try{let a=(0,Ou.parseDocument)(cs(e.projectRoot,["show",`${i}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:Sn(a.toJS({mapAsMap:!1}))}catch{return null}}function RA(e,t,i){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==i||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${i??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function pg(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Hu(e){let t=Me.join(e.paths.changesDir,e.state.name),i=await gg(t),r=await ps({changeDir:t,validation:vg(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:m})=>m)}:{},policy:"advisory"});if(!r)return e.state.children_contract_hash?{...i?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:i?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null;let n=wg({acceptance:e.state.acceptance,children:r.contract}),a=e.state.workspace.change_branch,o=e.state.phase!=="shape"&&e.state.children_contract_hash===n&&!r.drift;if(r.contract.schema===Nr){let m=await $i(e.paths,e.state.name);if(!m){let k=e.state.workspace.target_branch??e.state.workspace.change_branch;if(k){let N=await ju({paths:e.paths,parent:e.state.name,targetBranch:k,contract:r.contract});N&&(m=N,await Tu(e.paths,N))}}if(m){let k=og(m);return e.state.children_contract_hash!==n||r.drift?{...k,schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:!1,readyChildren:[],allDone:!1,children:k.children.map(N=>({...N,message:r.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...k,schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o}}let S=new Map(r.contract.children.map(k=>[k.name,k])),y=r.contract.children.map(k=>({name:k.name,summary:k.summary,dependsOn:[...k.depends_on],covers:[],status:o&&k.depends_on.every(N=>r.contract.children.filter(({name:E})=>E!==k.name).every(({name:E})=>E!==N))?"ready":"pending",phase:null,projectRoot:null,message:o?null:"Parent Shape confirmation is required"}));for(let k of y){if(k.status!=="ready")continue;S.get(k.name).depends_on.length>0&&(k.status="pending")}return{schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:y,readyChildren:y.filter(({status:k})=>k==="ready").map(({name:k})=>k),allDone:!1}}let s=await EA(e.paths),c=new Set(r.contract.children.map(({name:m})=>m)),l=new Map,u=new Map;for(let m of s){let S=m.parent&&a?`refs/heads/${a}`:"HEAD";for(let y of await xA(m,c)){let k={...y,source:m,committedState:PA(m,y.file,S)};l.set(y.state.name,[...l.get(y.state.name)??[],k])}for(let y of c){let k=await CA(m,y);k&&u.set(y,[...u.get(y)??[],{source:m,state:k}])}}let d=new Map;for(let m of r.contract.children){let S=(l.get(m.name)??[]).find(({source:N,committedState:E})=>N.parent&&E?.name===m.name&&pg(E,a));if(S){d.set(m.name,{kind:"done",phase:S.state.phase,projectRoot:S.source.projectRoot,message:null});continue}let y=l.get(m.name)?.[0];if(y){d.set(m.name,{kind:"blocked",phase:y.state.phase,projectRoot:y.source.projectRoot,message:`Native child ${m.name} is archived but not merged into parent branch ${a??"(missing)"}`});continue}let k=u.get(m.name)??[];k.length>1?d.set(m.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${m.name} has multiple active workspace owners`}):k[0]&&d.set(m.name,RA(k[0].state,k[0].source,a))}let f=new Map(r.contract.children.map(m=>[m.name,m])),p=new Map,v=m=>{let S=p.get(m);if(S)return S;let y=f.get(m),N=y.depends_on.map(v).every(({status:C})=>C==="done"),E=d.get(m),b=E?.kind==="active"&&N?y.depends_on.filter(C=>!(l.get(C)??[]).some(({source:$,committedState:T})=>$u($.projectRoot,E.projectRoot)&&T?.name===C&&pg(T,a))):[],x,g=E?.message??null;E?.kind==="done"?(x=N?"done":"blocked",N||(g=`Native child ${m} was merged before its dependencies`)):E?.kind==="active"?(x=N&&b.length===0?"active":"blocked",N?b.length>0&&(g=`Native child ${m} does not include merged dependencies: ${b.join(", ")}`):g=`Native child ${m} started before its dependencies merged`):E?.kind==="blocked"?x="blocked":(x=o&&N?"ready":"pending",o||(g="Parent Shape confirmation is required"));let w={name:m,summary:y.summary,dependsOn:[...y.depends_on],covers:[...y.covers],status:x,phase:E?.phase??null,projectRoot:E?.projectRoot??null,message:g};return p.set(m,w),w},h=r.contract.children.map(({name:m})=>v(m));return{schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:h,readyChildren:h.filter(({status:m})=>m==="ready").map(({name:m})=>m),allDone:h.every(({status:m})=>m==="done")}}var bV=["$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 AA=/\b(Bearer|Basic)\s+[^\s"']+/giu,_A=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,IA=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,TA=/\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,jA=/("(?:[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,$A=/(["'])((?:[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,OA=/\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\b(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)/giu;function We(e){return e.replace(AA,"$1 [REDACTED]").replace(_A,"[REDACTED PRIVATE KEY]").replace(IA,"$1[REDACTED]@").replace(TA,"[REDACTED TOKEN]").replace(jA,'$1"[REDACTED]"').replace($A,"$1$2$1$3$4[REDACTED]$4").replace(OA,"$1$2[REDACTED]")}import{promises as FA}from"node:fs";import yg from"node:path";function hs(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ms(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function wt(e,t,i=!1){if(typeof e!="string"||!i&&e.length===0)throw new Error(`${t} must be ${i?"a string":"a non-empty string"}`);return e}function Ng(e,t){return e===null?null:wt(e,t)}function gs(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function qA(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 MA(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function vs(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function Du(e,t){if(e===null)return null;let i=wt(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO timestamp`);return i}function Bu(e,t){let i=wt(e,t);if(!yg.isAbsolute(i))throw new Error(`${t} must be absolute`);return yg.resolve(i)}function WA(e,t){let i=`Native local checks[${t}]`,r=hs(e,i);if(ms(r,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),i),!Array.isArray(r.argv)||r.argv.length===0)throw new Error(`${i}.argv must be a non-empty array`);let n=r.argv.map((l,u)=>wt(l,`${i}.argv[${u}]`,!0)),a=vs(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=Du(r.startedAt,`${i}.startedAt`),s=Du(r.completedAt,`${i}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${i} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${i} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${i} completed check requires startedAt and completedAt`);let c=gs(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:wt(r.id,`${i}.id`),name:wt(r.name,`${i}.name`),operationId:wt(r.operationId,`${i}.operationId`),status:a,repeatable:MA(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:gs(r.executionCount,`${i}.executionCount`),argv:n,cwd:Bu(r.cwd,`${i}.cwd`),exitCode:qA(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:wt(r.log,`${i}.log`)}}function zA(e){let t="Native local execution state",i=hs(e,t);if(ms(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),i.schema!==Io)throw new Error(`Native local execution schema must be ${Io}`);let r=hs(i.workspace,"Native local workspace");ms(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=hs(i.execution,"Native local execution");ms(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=Du(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:wt(o.operationId,"Native local execution.operationId"),stage:vs(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:vs(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Ng(o.executionId,"Native local execution.executionId"),status:vs(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:gs(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(i.checks))throw new Error("Native local checks must be an array");let a=i.checks.map(WA);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:Io,change:wt(i.change,"Native local change"),basedOnStateVersion:gs(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:Bu(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Bu(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Ng(r.branch,"Native local workspace.branch")},execution:n,checks:a}}async function bg(e){let t;try{t=await FA.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}let i;try{i=JSON.parse(t)}catch(r){throw new Error(`Native local execution state is invalid JSON: ${r.message}`,{cause:r})}return zA(i)}var KA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,YA="comet-state.yaml",XA="state.json",t1=sa("en");function kg(e,t){if(!KA.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=Lu.join(e.changesDir,t);if(!V(e.changesDir,i))throw new Error("Native change path escaped");return i}function Sg(e,t){return Lu.join(kg(e,t),YA)}function QA(e,t){return Lu.join(ii(e,t),XA)}async function ws(e,t){try{let i=await UA.readFile(Sg(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}async function Vu(e,t){return En(Sg(e,t))}async function Eg(e){let t=await Vu(e.paths,e.name),i=QA(e.paths,e.name);try{let r=await bg(i);return r===null?{state:t,local:null,localStatus:"missing"}:r.change!==t.name||r.basedOnStateVersion!==t.state_version?{state:t,local:null,localStatus:"stale"}:{state:t,local:r,localStatus:"available"}}catch(r){return r.code==="ENOENT"?{state:t,local:null,localStatus:"missing"}:{state:t,local:null,localStatus:"invalid"}}}var u1=16*1024;async function Cg(e){let t=await tg(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(Dn(t.selection.change),t.selection)}async function xg(e,t){return it(e,`select change ${t}`,async()=>{Dn(t),await ws(e,t)?await Vu(e,t):await gt(e,t),await ig(e.projectRoot,{schema:"comet.selection.v2",workflow:"native",change:t,branch:null})})}async function Pg(e,t){let i=[],r=U(e,t.name),n=ri(r,qe.stateRef),a;try{a=await gr(r)}catch(u){return[{code:"run-state-invalid",message:`Native Run state is invalid: ${u.message}`,path:n}]}if(!a)return(t.run_id!==null||t.phase!=="shape")&&i.push({code:"run-state-missing",message:"Native change references a missing Run state",path:n}),i;if(t.run_id===null)return[{code:"run-state-unexpected",message:"Native change has a Run state but no run_id",path:n}];a.runId!==t.run_id&&i.push({code:"run-id-mismatch",message:`Native Run id ${a.runId} does not match change run_id ${t.run_id}`,path:n}),(a.pending||a.status==="waiting")&&i.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:n}),a.currentStep!==t.phase&&i.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:n});let o=ri(r,a.trajectoryRef),s=await bv(e,t.name);if(s.status==="repairable")return i.push({code:"trajectory-tail-incomplete",message:`Native trajectory final line is incomplete at line ${s.line}; doctor repair can discard ${s.discardedBytes} incomplete byte(s)`,path:o}),i;if(s.status==="invalid")return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),i;let c;try{if(c=await Ii(r,a.trajectoryRef),c.length===0||c.some((u,d)=>!u||typeof u!="object"||u.sequence!==d+1||u.runId!==a.runId||typeof u.type!="string"||!u.data||typeof u.data!="object"||Array.isArray(u.data)))throw new Error("trajectory events are missing or inconsistent")}catch(u){return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),i}let l=ri(r,a.checkpointRef);try{let u=await Xo(r,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&i.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):i.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){i.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return i}import W_ from"path";import{isDeepStrictEqual as od}from"util";var br={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var ZA=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function e_(e,t){return e<t?-1:e>t?1:0}function t_(e,t,i,r){if(!Array.isArray(e)||e.length>i||!r&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let n=e.map(a=>{if(typeof a!="string"||!ZA.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(e_)}function Fu(e=[]){return t_(e,"Native repair failed check IDs",br.maxFailedCheckIds,!0)}function Rg(e,t){let i=new Set(t);return e.every(r=>i.has(r))}function i_(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:Rg(e.failedAcceptanceIds,t.failedAcceptanceIds)&&Rg(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function qu(e,t){let i=1,r=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if(i_(r,a))break;i+=1,r=a}return i}import Ug from"node:path";import{createHash as Hg}from"node:crypto";import Ag from"path";var Mu="comet.native.implementation-scope.v2",Dg="comet.native.content-snapshot-projection.v1",qn="comet.native.content-snapshot-projection.v1",Bg="comet.native.implementation-scope.v2",r_="comet.native.unresolved-scope-id.v1",n_="comet.native.scope-detail-overflow.v1",a_="comet.native.snapshot-projection-overflow.v2",Gu=/^[a-f0-9]{64}$/u,Hi=1024*1024,o_=128,s_=128;function ve(e,t){return e<t?-1:e>t?1:0}function Wu(e){if(!Gu.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function c_(e,t){return e===t?0:e===null?-1:t===null?1:ve(e,t)}function li(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a normalized project-relative path`);let i=Ag.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||Ag.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function Lg(e,t){return e==="."?e:li(e,t)}function kr(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function l_(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:li(e.path,`${t} path`),hash:e.hash,size:kr(e.size,`${t} size`),type:"file"}}function u_(e,t){return{path:Lg(e.path,`${t} path`),size:e.size===null?null:kr(e.size,`${t} size`),type:e.type,reason:e.reason}}function d_(e,t){return ve(e.path,t.path)||ve(e.hash,t.hash)||e.size-t.size}function f_(e,t){return ve(e.path,t.path)||ve(e.reason,t.reason)||ve(e.type,t.type)||(e.size??-1)-(t.size??-1)}function Wn(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
166
+ ${e.sessionId}`)}:{}},p=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return Zo(p),p}async function jt(e,t){let i=await IR(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(Zo(i),i)}async function es(e){Zo(e.identity);let t=await TR({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),i=[],r=[];return t.nativeRootRef!==e.identity.nativeRootRef&&i.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&i.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&i.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&i.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&i.push("native-root-legacy-identity")),gu==="win32"&&i.length>0&&i.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?r.push("workspace-inspection-unavailable"):i.length>0&&r.push("workspace-root-changed"),{state:r.length===0?"aligned":r.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:r,driftComponents:i}}async function jn(e){if(Zo(e.identity),e.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await es(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=Ee(e.paths.projectRoot);return e.identity.changeBranch===null?i.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:i.isGitWorktree?i.currentBranch!==e.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${e.identity.changeBranch}, but the current branch is ${i.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!i.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function Iv(e,t){let i=await jt(e,t);if(i===null)return null;let r=await jn({paths:e,identity:i});if(r.state==="drifted")throw new Error(`${r.code}: ${r.message}`);return i}var $v=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],$R=new Set($v),Ov=new Set([...$v,"minimum_runtime_version","revision"]),OR=new Set([...Ov,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),HR=new Set(["capability","operation","source","base_hash"]),DR=new Set(["shape","build","verify","archive"]),BR=new Set(["implicit","confirmed"]),LR=new Set(["pending","pass","fail"]),ji="comet-state.yaml",Nu=/^[a-f0-9]{64}$/u,Hv=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,VR=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,ts=class extends Error{constructor(i,r){super(`Native change ${i} uses ${r}; run comet native doctor ${i} --repair before mutating it`);this.change=i;this.schema=r;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},Ti=class extends Error{constructor(i,r){super(i!==Pt||r===null?`Unsupported Native change schema ${i} for runtime protocol ${3}`:`Native change ${i} requires runtime protocol ${r}; current protocol is ${3}`);this.schema=i;this.minimumRuntimeVersion=r;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},is=class extends Error{constructor(i,r,n){super(`Native change ${i} revision conflict: expected ${r}, actual ${n}`);this.change=i;this.expectedRevision=r;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},$n=class extends Error{constructor(i,r){super(`Native working directory already contains active change${r.length===1?"":"s"} ${r.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=i;this.activeChanges=r;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},rs=class extends Error{constructor(i,r,n,a,o,s=null,c=null){super(`Native change ${i} baseline is incomplete (${r} omitted entr${r===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=i;this.omittedCount=r;this.omittedByReason=n;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},yL=sa("en");function Hn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Dv(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Dn(e){if(!Hv.test(e))throw new Error(`Invalid Native change name: ${e}`)}function FR(e){if(!Hv.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Bv(e,t){if(e.length===0||si.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function qR(e,t){let i=Hn(e,`spec_changes[${t}]`);if(Dv(i,HR,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(FR(i.capability),i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`Invalid spec operation for ${i.capability}`);let r=i.source,n=i.base_hash;if(r!==void 0&&typeof r!="string")throw new Error(`Spec source for ${i.capability} must be a string`);if(typeof r=="string"&&Bv(r,`Spec source for ${i.capability}`),i.operation==="create"){if(!r)throw new Error(`Create spec ${i.capability} requires source`);if(n!==null)throw new Error(`Create spec ${i.capability} requires null base_hash`)}else if(i.operation==="replace"){if(!r)throw new Error(`Replace spec ${i.capability} requires source`);if(typeof n!="string"||!Nu.test(n))throw new Error(`Replace spec ${i.capability} requires a SHA-256 base_hash`)}else{if(r!==void 0)throw new Error(`Remove spec ${i.capability} forbids source`);if(typeof n!="string"||!Nu.test(n))throw new Error(`Remove spec ${i.capability} requires a SHA-256 base_hash`)}return{capability:i.capability,operation:i.operation,...typeof r=="string"?{source:r}:{},base_hash:n}}function MR(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 ku(e,t){if(Dv(e,t,ji),typeof e.name!="string")throw new Error("Native change name is required");if(Dn(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"||!DR.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&&!BR.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let i=e.spec_changes.map(qR),r=i.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(r.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(r)].join(", ")}`);if(typeof e.verification_result!="string"||!LR.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"&&Bv(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!MR(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:i,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function lr(e){let t=Hn(e,ji);if(t.schema!==At)throw new Error(`Expected ${At}`);return{schema:At,...ku(t,$R)}}function On(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function yu(e,t,i){if(e===null)return null;let r=typeof e=="string"?VR.exec(e):null;if(!r||r[1]!==i)throw new Error(`${t} must be null or runtime/evidence/${i}/<sha256>.json relative to the Native change`);return e}function WR(e){if(e==null)return null;if(typeof e!="string"||!Nu.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function zR(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 ur(e){let t=Hn(e,ji);if(t.schema!==Rt)throw new Error(`Expected ${Rt}`);if(On(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Rt} minimum_runtime_version must be 2`);return{schema:Rt,minimum_runtime_version:2,revision:On(t.revision,"Native v2 revision"),...ku(t,Ov)}}function ni(e){let t=Hn(e,ji);if(t.schema!==Pt){if(t.schema===At||t.schema===Rt){let o=t.schema===At?lr(t):ur(t);throw new ts(o.name,o.schema)}throw new Ti(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=On(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new Ti(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let r=On(t.revision,"Native revision"),n=ku(t,OR),a=WR(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Pt,minimum_runtime_version:3,revision:r,verification_protocol:zR(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:yu(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:yu(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:yu(t.partial_allowance,"Native partial_allowance","allowances")}}function JR(e){let t=Hn(e,ji);if(t.schema===At){let n=lr(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Pt}`}}if(t.schema===Rt){let n=ur(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Pt}`}}if(t.schema!==Pt){let n=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new Ti(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let i=On(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new Ti(t.schema,i).message};let r=ni(t);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function me(e,t){Dn(t);let i=si.join(e.changesDir,t);if(!V(e.changesDir,i))throw new Error("Native change path escaped");return i}async function ns(e,t){let i=U(e,t),r=si.join(i,"schema-migration.json");await z(V(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await jv.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Lv(e,t){let i=U(e,t),r=si.join(i,"checkpoint-journal.json");await z(V(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await jv.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function GR(e,t=si.dirname(e)){let i=si.relative(t,e).split(si.sep).join("/"),r=await re({root:t,ref:i,maxBytes:null,includeHash:!1}),n=(0,bu.parseDocument)(r.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function Su(e,t){let i=si.join(me(e,t),ji);await z(e.nativeRoot,i);let r=JR(await GR(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await ns(e,t)?{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimumRuntimeVersion,state:r.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(r.status==="current"&&r.state&&await UR(e,r.state),r)}async function UR(e,t){if(await zo(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function gt(e,t){let i=await Su(e,t);if(i.status==="migration-required")throw new ts(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new Ti(i.schema,i.minimumRuntimeVersion);return await Iv(e,t),i.state}var Fv=["outcome","scope","nonGoals","acceptanceExamples"],KR=[...Fv,"constraints","decisions","openQuestions","verificationExpectations"],YR=["acceptanceEvidence","commandsAndResults","skippedChecks","specConsistency","knownLimitationsAndRisks","conclusion"],qv={maxFileBytes:hn};function Mv(e){let t=new Map,i=null,r=[],n=()=>{i!==null&&t.set(i,r.join(`
167
+ `).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(n(),i=o[1].trim(),r=[]):i!==null&&r.push(a)}return n(),t}async function XR(e,t){let i=Vv.resolve(e,...t.split(/[\\/]/u));if(!V(e,i))throw new Error(`Artifact escapes Native change: ${t}`);let r=await Eu.realpath(e),n=await Eu.realpath(i);if(!V(r,n))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await Eu.stat(n)).isFile())throw new Error(`Artifact is not a file: ${t}`);return n}function Bn(e){return{valid:e.length===0,findings:e}}function Wv(e){let t=new Set(["blocker","blocking","coverage","decision","open_question","question","requirement","requirements","source","source_coverage","state","status","决策","来源","覆盖","问题","状态","需求","阻塞"]),i=null;for(let r of e.split(/\r?\n/u)){let n=r.match(/^\s*(`{3,}|~{3,})/u);if(n){let s=n[1]?.[0];i===null?i=s:i===s&&(i=null);continue}if(i!==null)continue;let a=r.trim();if(/^(?:[-*+]\s+|\d+[.)]\s+)(?:\[[ xX]\]\s+)?\[blocking\](?=$|[\s::—-])/iu.test(a)||a.includes("|")&&a.split("|").some(s=>/^\s*\[blocking\](?=$|[\s::—-])/iu.test(s)))return!0;let o=a.match(/^([\p{L}\p{N}_./-]+)\s*[::]\s*\[blocking\](?=$|[\s::—-])/iu);if(o){let s=o[1]?.toLocaleLowerCase("en-US")??"";if(t.has(s)||/[./_-]/u.test(s))return!0}}return!1}async function Cu(e,t){let i=[],r;try{r=(await re({root:e,ref:t,maxBytes:qv.maxFileBytes})).text}catch(a){return Bn([{code:"brief-missing",message:a.message,path:t}])}let n=new Map;for(let[a,o]of Mv(r))n.set(oa(a)??a,o);for(let a of KR)n.has(a)||i.push({code:"brief-section-missing",message:`Missing brief section: ${a}`,path:t});for(let a of Fv)(n.get(a)??"").length===0&&i.push({code:"brief-section-empty",message:`Brief section is empty: ${a}`,path:t});return Wv(r)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),Bn(i)}async function xu(e,t){let i=[],r;try{r=(await re({root:e,ref:t,maxBytes:qv.maxFileBytes})).text}catch(a){return Bn([{code:"verification-missing",message:a.message,path:t}])}let n=new Map;for(let[a,o]of Mv(r))n.set(zd(a)??a,o);for(let a of YR)n.has(a)?(n.get(a)??"").length===0&&i.push({code:"verification-section-empty",message:`Verification section is empty: ${a}`,path:t}):i.push({code:"verification-section-missing",message:`Missing verification section: ${a}`,path:t});return Bn(i)}function as(e,t){return Vv.join(e.specsDir,t,"spec.md")}async function zv(e,t){let i=[],r=me(e,t.name);for(let n of t.spec_changes){let a=as(e,n.capability),o=null;try{await z(e.nativeRoot,a),o=await iu(a)}catch(s){if(s.code!=="ENOENT"){i.push({code:"spec-canonical-unsafe",message:s.message,path:a});continue}}if(n.operation==="create"&&o!==null&&i.push({code:"spec-create-exists",message:`Canonical spec already exists: ${n.capability}`,path:a}),n.operation!=="create"&&o===null&&i.push({code:"spec-base-missing",message:`Canonical spec is missing: ${n.capability}`,path:a}),n.operation!=="create"&&o!==null&&o!==n.base_hash&&i.push({code:"spec-base-conflict",message:`Canonical spec changed for ${n.capability}: expected ${n.base_hash}, actual ${o}`,path:a}),n.source)try{await XR(r,n.source)}catch(s){i.push({code:"spec-source-invalid",message:s.message,path:n.source})}}return Bn(i)}import Jv from"node:path";var QR="comet.native.contract.v1",ZR="comet.native.acceptance-set.v1",Gv=/^[a-f0-9]{64}$/u,Ln={maxAcceptanceCriteria:bn.maxCriteria};function Uv(e,t){let i=Jv.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||Jv.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized project-relative ref`);return e}function Kv(e){return H("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
168
+ `))}function eA(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(Gv))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(Gv))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=Uv(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:Kv(e.markdown)},markdown:e.markdown}}function tA(e,t){return Yv(e.id,t.id)}function Yv(e,t){return e<t?-1:e>t?1:0}function Xv(e){let t=Uv(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(eA).sort((d,f)=>Yv(d.snapshot.capability,f.snapshot.capability)),r=i.map(({snapshot:d})=>d.capability);if(new Set(r).size!==r.length)throw new Error("Native contract contains duplicate capabilities");let n=[t,...i.flatMap(({snapshot:d})=>d.source===null?[]:[d.source])];if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate artifact sources");let a=Jl(e.briefMarkdown,t,Ln.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(...Gl(f,d.source,Ln.maxAcceptanceCriteria-a.length)),a.push(...Nm(f,d.source,Ln.maxAcceptanceCriteria-a.length)));if(a.sort(tA),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>Ln.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${Ln.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:Kv(e.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=H(ZR,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:H(QR,u)}}var os={maxSpecs:64,maxFileBytes:hn,maxTotalBytes:4*1024*1024};async function yr(e){if(e.specChanges.length>os.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await re({root:e.changeDir,ref:e.briefRef,maxBytes:os.maxFileBytes}),i=t.size,r=[];for(let n of e.specChanges){if(n.operation==="remove"){r.push({capability:n.capability,operation:"remove",source:null,baseHash:n.base_hash,markdown:null});continue}if(!n.source)throw new Error(`Native contract ${n.capability} has no proposed spec source`);let a=await re({root:e.changeDir,ref:n.source,maxBytes:os.maxFileBytes});if(i+=a.size,i>os.maxTotalBytes)throw new Error("Native contract exceeds its total byte budget");r.push({capability:n.capability,operation:n.operation,source:a.ref,baseHash:n.base_hash,markdown:a.text})}return{contract:Xv({briefSource:t.ref,briefMarkdown:t.text,specs:r}),sourceCount:r.filter(n=>n.source!==null).length+1,totalBytes:i}}import{randomUUID as iA}from"crypto";import{promises as ss}from"fs";import Zv from"path";var Pu="comet.selection.v2",rA=16*1024;function Ru(e){return Zv.join(e,".comet","current-change.json")}function nA(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Qv(e){return e===null||typeof e=="string"}function eg(e){let t;try{t=JSON.parse(e)}catch(i){throw new Error(`current change selection contains invalid JSON: ${i instanceof Error?i.message:String(i)}`,{cause:i})}if(!nA(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&&!Qv(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Pu,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Pu)throw new Error(`current change selection schema must be ${Pu}`);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(!Qv(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 tg(e){let t;try{let r=Ru(e),{bytes:n}=await Pi(r,rA,{label:"current change selection"});t=n.toString("utf8")}catch(r){if(r.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${r instanceof Error?r.message:String(r)}`,{cause:r})}return{status:"selected",...eg(t)}}async function ig(e,t){let i=eg(JSON.stringify(t));if(i.legacy)throw new Error("cannot write a legacy current change selection");let r=Ru(e),n=`${r}.${iA()}.tmp`;await ss.mkdir(Zv.dirname(r),{recursive:!0});try{await ss.writeFile(n,`${JSON.stringify(i.selection,null,2)}
169
+ `,"utf8"),await ss.rename(n,r)}catch(a){throw await ss.rm(n,{force:!0}),a}}import{promises as YA}from"node:fs";import Lu from"node:path";var Ou=Or(Xi(),1);import{promises as hg}from"node:fs";import Me from"node:path";import{execFileSync as aA}from"node:child_process";var oA=3e4,sA=8*1024*1024,Au=class extends Error{constructor(i,r,n){super(`git ${r.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=i;this.args=r;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr};function cA(e,t){try{return aA("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:oA,maxBuffer:sA,windowsHide:!0})}catch(i){let r=typeof i.stderr=="string"?i.stderr.trim():Buffer.isBuffer(i.stderr)?i.stderr.toString("utf8").trim():"";throw new Au(e,t,r)}}function cs(e,t){return cA(e,t).trim()}import Iu from"node:path";import{promises as rg}from"node:fs";var ls=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var _u="comet.native.supervisor.v2",uA=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function dA(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native Supervisor parent name: ${e}`);return`comet/supervisor/${e}/integration`}function fA(e,t){return Iu.join(ii(e,t),"supervisor")}function us(e,t){return Iu.join(fA(e,t),"state.json")}function ng(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!==_u)throw new Error(`Native Supervisor state schema must be ${_u}`);if(!Number.isSafeInteger(t.stateVersion)||typeof t.stateVersion!="number"||t.stateVersion<1)throw new Error("Native Supervisor state version is invalid");if(typeof t.parent!="string"||!t.parent)throw new Error("Native Supervisor state parent is invalid");if(!t.integration||typeof t.integration!="object")throw new Error("Native Supervisor integration state is missing");for(let[n,a]of Object.entries(t.integration))if(typeof a!="string"||a.length===0)throw new Error(`Native Supervisor integration field ${n} is invalid`);if(Vn(t.integration.targetCommit,"Native Supervisor target commit"),Vn(t.integration.headCommit,"Native Supervisor integration head commit"),!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let i=new Set,r=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(i.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(i.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.projectRoot!==void 0&&n.projectRoot!==null&&(typeof n.projectRoot!="string"||n.projectRoot.length===0))throw new Error(`Native Supervisor child ${n.name} projectRoot is invalid`);for(let[a,o]of[["base",n.baseCommit],["candidate",n.candidateCommit],["verified",n.verifiedCommit],["integration",n.integrationCommit]])o!==null&&Vn(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(Vn(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),r.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(r.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.role==="builder"&&n.status!=="active"||n.task.role==="verifier"&&!["active","needs-reverify"].includes(n.status))throw new Error(`Native Supervisor child ${n.name} task status is invalid`)}}}async function $i(e,t){try{let i=await rg.readFile(us(e,t),"utf8"),r=JSON.parse(i);return ng(r),r}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Tu(e,t){ng(t),await rg.mkdir(e.changesRuntimeDir,{recursive:!0}),await Qe(us(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function Vn(e,t){if(!uA.test(e))throw new Error(`${t} must be a Git commit`)}function pA(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function ag(e){Vn(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:r})=>r)),i=e.contract.children.map(r=>({name:r.name,summary:r.summary,dependsOn:[...r.depends_on],status:r.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null}));for(let r of i)for(let n of r.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${r.name} depends on unknown child ${n}`);return{schema:_u,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:i,history:[],finalVerification:{status:"pending",summary:null}}}async function ju(e){let t=dA(e.parent),i=Ei(e.paths.projectRoot,t);if(!i)return null;let r=Ei(e.paths.projectRoot,e.targetBranch);if(!r)return null;let n=Zi(e.paths.projectRoot).map(o=>Iu.resolve(o)).find(o=>Ee(o).currentBranch===t);if(!n)return null;let a=ag({parent:e.parent,targetBranch:e.targetBranch,targetCommit:r,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(i!==r){for(let o of a.children)o.status=o.dependsOn.length===0?"blocked":"pending",o.blocker=o.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;a.integration.headCommit=i}return pA(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function og(e){let t=e.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.dependsOn],covers:[],status:i.status,phase:null,projectRoot:i.projectRoot??i.task?.projectRoot??null,message:i.blocker}));return{contractHash:null,confirmed:!0,parentBranch:e.integration.branch,children:t,readyChildren:t.filter(({status:i})=>i==="ready").map(({name:i})=>i),allDone:t.every(({status:i})=>i==="integrated"||i==="archived")}}var sg="children.yaml",Fn="comet.native.children.v1",Nr="comet.native.children.v2",mg=Nr,hA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,cg=new Set(["schema","children"]),mA=new Set(["schema","acceptance_index","children"]),vA=new Set(["name","depends_on","covers"]),gA=new Set(["name","summary","depends_on"]),wA=new Set(["name","depends_on","covers"]);function fs(e,t,i=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${i}`);return e}function ds(e,t,i){let r=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(r.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...r.length>0?[`unexpected ${r.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${i} fields are invalid: ${a.join("; ")}`)}}function lg(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((i,r)=>i.localeCompare(r,"en"))}function $u(e,t){let i=Me.normalize(Me.resolve(e)),r=Me.normalize(Me.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function yA(e){let t=new Map(e.map(a=>[a.name,a])),i=new Set,r=new Set,n=a=>{if(!r.has(a)){if(i.has(a))throw new Error(`Native children dependency cycle includes ${a}`);i.add(a);for(let o of t.get(a).depends_on)n(o);i.delete(a),r.add(a)}};for(let a of e)n(a.name)}function ug(e,t,i=t){let r=new Set(t);for(let o of e){let s=o.covers.filter(c=>!r.has(c));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=i.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function NA(e,t,i){let r={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===mg&&e.acceptance_index){let n=i.requiredAcceptanceIds??t??[],a=i.allowedAcceptanceIds??n,o=Object.keys(e.acceptance_index);r.missing=n.filter(l=>!(l in e.acceptance_index)),r.extra=o.filter(l=>!a.includes(l));let s=new Map((i.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of o){let u=s.get(l),d=e.acceptance_index[l];u&&d&&(d.source!==u.source||d.text!==u.text)&&r.mismatched.push(l)}let c=new Set(o);for(let l of e.children)r.unknownCovers.push(...l.covers.filter(u=>!c.has(u)));return r.uncovered=o.filter(l=>!dg(e.children,l)),fg(r)?r:null}if(e.schema===Fn&&t){let n=new Set(t);for(let a of e.children)r.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return r.uncovered=t.filter(a=>!dg(e.children,a)),fg(r)?r:null}return null}function dg(e,t){return e.some(i=>i.covers.includes(t))}function fg(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function vg(e){let t=new Set(e.acceptance.map(({id:n})=>n)),i=new Set(e.acceptance.filter(({source:n})=>n===e.brief).map(({id:n})=>n)),r=new Set(i);for(let n of e.history.filter(({outcome:a})=>a==="fail"))for(let a of n.unresolved_ids)t.has(a)&&r.add(a);if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let n=[...e.history].reverse().find(({outcome:a})=>a==="fail");for(let a of n?.unresolved_ids??[])i.add(a)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...i],allowedAcceptanceIds:[...r]}}function bA(e){let t=fs(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),i={};for(let[r,n]of Object.entries(t)){let a=fs(n,`Native children acceptance_index.${r}`);if(ds(a,new Set(["source","text"]),`Native children acceptance_index.${r}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${r}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${r}.text must be a non-empty string`);i[r]={source:a.source,text:a.text}}return i}function kA(e,t,i){let r=i.requiredAcceptanceIds??t??[],n=i.allowedAcceptanceIds??r,a=Object.keys(e),o=r.filter(l=>!(l in e)),s=a.filter(l=>!n.includes(l));if(o.length>0||s.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${o.join(", ")||"none"}; extra ${s.join(", ")||"none"}`);let c=new Map((i.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of a){let u=c.get(l);if(!u)continue;let d=e[l];if(d.source!==u.source||d.text!==u.text){let f=["source","text"].filter(p=>d[p]!==u[p]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${f.join(", ")} exactly from the current acceptance catalog`)}}}function SA(e,t,i={}){let r=(0,Ou.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${r.errors[0].message}`);let n=fs(r.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==Fn&&a!==Nr)throw ds(n,cg,"Native children contract"),new Error(`Native children schema must be ${Fn} or ${Nr}`);let o=a===Fn?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(ds(n,o==="indexed-v2"?mA:cg,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let c=n.children.map((f,p)=>{let v=fs(f,`Native child ${p}`);if(ds(v,o==="indexed-v2"?wA:o==="summary-v2"?gA:vA,`Native ${s} child fields (child ${p})`),typeof v.name!="string"||!hA.test(v.name))throw new Error(`Native child ${p} name is invalid`);let h=o==="summary-v2";if(h){if(typeof v.summary!="string"||v.summary.trim().length===0)throw new Error(`Native child ${v.name} summary must be a non-empty string`);if(v.summary.length>2e3)throw new Error(`Native child ${v.name} summary exceeds 2000 characters`)}return{name:v.name,summary:h?v.summary:null,depends_on:lg(v.depends_on,`Native child ${v.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?lg(v.covers,`Native child ${v.name} covers`):[]}}),l=c.map(({name:f})=>f);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let u=new Set(l);for(let f of c){let p=f.depends_on.filter(v=>!u.has(v));if(p.length>0)throw new Error(`Native child ${f.name} depends on unknown child: ${p.join(", ")}`)}yA(c);let d=i.policy==="advisory";if(a===mg){if(o==="indexed-v2"){let f=bA(n.acceptance_index);d||kA(f,t,i);let p=Object.keys(f);return d||ug(c,p,p),{schema:Nr,acceptance_index:f,children:c}}return{schema:Nr,children:c}}return t&&!d&&ug(c,t),{schema:Fn,children:c}}async function ps(e){let t=Me.join(e.changeDir,sg);try{await hg.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let i=await re({root:e.changeDir,ref:sg}),r=e.policy==="advisory",n=r?{...e.validation,policy:"advisory"}:e.validation??{},a=SA(i.text,e.acceptanceIds,n);return{contract:a,hash:i.hash,size:i.size,drift:r?NA(a,e.acceptanceIds,e.validation??{}):null}}function EA(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let i=e.slice(t.index+t[0].length);return i.split(/^#\s+/mu,1)[0]??i}function CA(e){let t=EA(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let i=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),r=t.match(/\bChild\s+\d+\b/giu);return Math.max(i?.length??0,r?.length??0)>=2}async function gg(e){try{let t=await re({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return CA(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function wg(e){return H("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:i,text:r})=>({id:t,source:i,text:r})),children:e.children})}async function xA(e){let t=Zi(e.projectRoot);t.some(r=>$u(r,e.projectRoot))||t.push(e.projectRoot);let i=[];for(let r of[...new Set(t.map(n=>Me.resolve(n)))]){let n=await Ie(r);n&&i.push({projectRoot:r,paths:await Ri(r,n.native.artifact_root),parent:$u(r,e.projectRoot)})}return i.some(({parent:r})=>r)||i.push({projectRoot:e.projectRoot,paths:e,parent:!0}),i}async function PA(e,t){let i=Me.join(e.paths.changesDir,t,"comet-state.yaml");try{return await En(i)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function RA(e,t){let i;try{i=await hg.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[];for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=Me.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await En(o);t.has(s.name)&&r.push({file:o,state:s})}catch{}return r}function AA(e,t,i){let r=Me.relative(e.projectRoot,t);if(!r||r===".."||r.startsWith(`..${Me.sep}`))return null;let n=r.split(Me.sep).join("/");try{let a=(0,Ou.parseDocument)(cs(e.projectRoot,["show",`${i}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:Sn(a.toJS({mapAsMap:!1}))}catch{return null}}function _A(e,t,i){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==i||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${i??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function pg(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Hu(e){let t=Me.join(e.paths.changesDir,e.state.name),i=await gg(t),r=await ps({changeDir:t,validation:vg(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:m})=>m)}:{},policy:"advisory"});if(!r)return e.state.children_contract_hash?{...i?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:i?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null;let n=wg({acceptance:e.state.acceptance,children:r.contract}),a=e.state.workspace.change_branch,o=e.state.phase!=="shape"&&e.state.children_contract_hash===n&&!r.drift;if(r.contract.schema===Nr){let m=await $i(e.paths,e.state.name);if(!m){let k=e.state.workspace.target_branch??e.state.workspace.change_branch;if(k){let N=await ju({paths:e.paths,parent:e.state.name,targetBranch:k,contract:r.contract});N&&(m=N,await Tu(e.paths,N))}}if(m){let k=og(m);return e.state.children_contract_hash!==n||r.drift?{...k,schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:!1,readyChildren:[],allDone:!1,children:k.children.map(N=>({...N,message:r.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...k,schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o}}let S=new Map(r.contract.children.map(k=>[k.name,k])),y=r.contract.children.map(k=>({name:k.name,summary:k.summary,dependsOn:[...k.depends_on],covers:[],status:o&&k.depends_on.every(N=>r.contract.children.filter(({name:E})=>E!==k.name).every(({name:E})=>E!==N))?"ready":"pending",phase:null,projectRoot:null,message:o?null:"Parent Shape confirmation is required"}));for(let k of y){if(k.status!=="ready")continue;S.get(k.name).depends_on.length>0&&(k.status="pending")}return{schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:y,readyChildren:y.filter(({status:k})=>k==="ready").map(({name:k})=>k),allDone:!1}}let s=await xA(e.paths),c=new Set(r.contract.children.map(({name:m})=>m)),l=new Map,u=new Map;for(let m of s){let S=m.parent&&a?`refs/heads/${a}`:"HEAD";for(let y of await RA(m,c)){let k={...y,source:m,committedState:AA(m,y.file,S)};l.set(y.state.name,[...l.get(y.state.name)??[],k])}for(let y of c){let k=await PA(m,y);k&&u.set(y,[...u.get(y)??[],{source:m,state:k}])}}let d=new Map;for(let m of r.contract.children){let S=(l.get(m.name)??[]).find(({source:N,committedState:E})=>N.parent&&E?.name===m.name&&pg(E,a));if(S){d.set(m.name,{kind:"done",phase:S.state.phase,projectRoot:S.source.projectRoot,message:null});continue}let y=l.get(m.name)?.[0];if(y){d.set(m.name,{kind:"blocked",phase:y.state.phase,projectRoot:y.source.projectRoot,message:`Native child ${m.name} is archived but not merged into parent branch ${a??"(missing)"}`});continue}let k=u.get(m.name)??[];k.length>1?d.set(m.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${m.name} has multiple active workspace owners`}):k[0]&&d.set(m.name,_A(k[0].state,k[0].source,a))}let f=new Map(r.contract.children.map(m=>[m.name,m])),p=new Map,v=m=>{let S=p.get(m);if(S)return S;let y=f.get(m),N=y.depends_on.map(v).every(({status:C})=>C==="done"),E=d.get(m),b=E?.kind==="active"&&N?y.depends_on.filter(C=>!(l.get(C)??[]).some(({source:$,committedState:T})=>$u($.projectRoot,E.projectRoot)&&T?.name===C&&pg(T,a))):[],x,g=E?.message??null;E?.kind==="done"?(x=N?"done":"blocked",N||(g=`Native child ${m} was merged before its dependencies`)):E?.kind==="active"?(x=N&&b.length===0?"active":"blocked",N?b.length>0&&(g=`Native child ${m} does not include merged dependencies: ${b.join(", ")}`):g=`Native child ${m} started before its dependencies merged`):E?.kind==="blocked"?x="blocked":(x=o&&N?"ready":"pending",o||(g="Parent Shape confirmation is required"));let w={name:m,summary:y.summary,dependsOn:[...y.depends_on],covers:[...y.covers],status:x,phase:E?.phase??null,projectRoot:E?.projectRoot??null,message:g};return p.set(m,w),w},h=r.contract.children.map(({name:m})=>v(m));return{schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:h,readyChildren:h.filter(({status:m})=>m==="ready").map(({name:m})=>m),allDone:h.every(({status:m})=>m==="done")}}var kV=["$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 IA=/\b(Bearer|Basic)\s+[^\s"']+/giu,TA=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,jA=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,$A=/\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,OA=/("(?:[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,HA=/(["'])((?:[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,DA=/\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\b(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)/giu;function We(e){return e.replace(IA,"$1 [REDACTED]").replace(TA,"[REDACTED PRIVATE KEY]").replace(jA,"$1[REDACTED]@").replace($A,"[REDACTED TOKEN]").replace(OA,'$1"[REDACTED]"').replace(HA,"$1$2$1$3$4[REDACTED]$4").replace(DA,"$1$2[REDACTED]")}import{promises as MA}from"node:fs";import yg from"node:path";function hs(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ms(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function wt(e,t,i=!1){if(typeof e!="string"||!i&&e.length===0)throw new Error(`${t} must be ${i?"a string":"a non-empty string"}`);return e}function Ng(e,t){return e===null?null:wt(e,t)}function gs(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function WA(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 zA(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function vs(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function Du(e,t){if(e===null)return null;let i=wt(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO timestamp`);return i}function Bu(e,t){let i=wt(e,t);if(!yg.isAbsolute(i))throw new Error(`${t} must be absolute`);return yg.resolve(i)}function JA(e,t){let i=`Native local checks[${t}]`,r=hs(e,i);if(ms(r,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),i),!Array.isArray(r.argv)||r.argv.length===0)throw new Error(`${i}.argv must be a non-empty array`);let n=r.argv.map((l,u)=>wt(l,`${i}.argv[${u}]`,!0)),a=vs(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=Du(r.startedAt,`${i}.startedAt`),s=Du(r.completedAt,`${i}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${i} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${i} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${i} completed check requires startedAt and completedAt`);let c=gs(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:wt(r.id,`${i}.id`),name:wt(r.name,`${i}.name`),operationId:wt(r.operationId,`${i}.operationId`),status:a,repeatable:zA(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:gs(r.executionCount,`${i}.executionCount`),argv:n,cwd:Bu(r.cwd,`${i}.cwd`),exitCode:WA(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:wt(r.log,`${i}.log`)}}function GA(e){let t="Native local execution state",i=hs(e,t);if(ms(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),i.schema!==Io)throw new Error(`Native local execution schema must be ${Io}`);let r=hs(i.workspace,"Native local workspace");ms(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=hs(i.execution,"Native local execution");ms(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=Du(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:wt(o.operationId,"Native local execution.operationId"),stage:vs(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:vs(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Ng(o.executionId,"Native local execution.executionId"),status:vs(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:gs(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(i.checks))throw new Error("Native local checks must be an array");let a=i.checks.map(JA);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:Io,change:wt(i.change,"Native local change"),basedOnStateVersion:gs(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:Bu(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Bu(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Ng(r.branch,"Native local workspace.branch")},execution:n,checks:a}}async function bg(e){let t;try{t=await MA.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}let i;try{i=JSON.parse(t)}catch(r){throw new Error(`Native local execution state is invalid JSON: ${r.message}`,{cause:r})}return GA(i)}var XA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,QA="comet-state.yaml",ZA="state.json",i1=sa("en");function kg(e,t){if(!XA.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=Lu.join(e.changesDir,t);if(!V(e.changesDir,i))throw new Error("Native change path escaped");return i}function Sg(e,t){return Lu.join(kg(e,t),QA)}function e_(e,t){return Lu.join(ii(e,t),ZA)}async function ws(e,t){try{let i=await YA.readFile(Sg(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}async function Vu(e,t){return En(Sg(e,t))}async function Eg(e){let t=await Vu(e.paths,e.name),i=e_(e.paths,e.name);try{let r=await bg(i);return r===null?{state:t,local:null,localStatus:"missing"}:r.change!==t.name||r.basedOnStateVersion!==t.state_version?{state:t,local:null,localStatus:"stale"}:{state:t,local:r,localStatus:"available"}}catch(r){return r.code==="ENOENT"?{state:t,local:null,localStatus:"missing"}:{state:t,local:null,localStatus:"invalid"}}}var d1=16*1024;async function Cg(e){let t=await tg(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(Dn(t.selection.change),t.selection)}async function xg(e,t){return it(e,`select change ${t}`,async()=>{Dn(t),await ws(e,t)?await Vu(e,t):await gt(e,t),await ig(e.projectRoot,{schema:"comet.selection.v2",workflow:"native",change:t,branch:null})})}async function Pg(e,t){let i=[],r=U(e,t.name),n=ri(r,qe.stateRef),a;try{a=await gr(r)}catch(u){return[{code:"run-state-invalid",message:`Native Run state is invalid: ${u.message}`,path:n}]}if(!a)return(t.run_id!==null||t.phase!=="shape")&&i.push({code:"run-state-missing",message:"Native change references a missing Run state",path:n}),i;if(t.run_id===null)return[{code:"run-state-unexpected",message:"Native change has a Run state but no run_id",path:n}];a.runId!==t.run_id&&i.push({code:"run-id-mismatch",message:`Native Run id ${a.runId} does not match change run_id ${t.run_id}`,path:n}),(a.pending||a.status==="waiting")&&i.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:n}),a.currentStep!==t.phase&&i.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:n});let o=ri(r,a.trajectoryRef),s=await bv(e,t.name);if(s.status==="repairable")return i.push({code:"trajectory-tail-incomplete",message:`Native trajectory final line is incomplete at line ${s.line}; doctor repair can discard ${s.discardedBytes} incomplete byte(s)`,path:o}),i;if(s.status==="invalid")return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),i;let c;try{if(c=await Ii(r,a.trajectoryRef),c.length===0||c.some((u,d)=>!u||typeof u!="object"||u.sequence!==d+1||u.runId!==a.runId||typeof u.type!="string"||!u.data||typeof u.data!="object"||Array.isArray(u.data)))throw new Error("trajectory events are missing or inconsistent")}catch(u){return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),i}let l=ri(r,a.checkpointRef);try{let u=await Xo(r,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&i.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):i.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){i.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return i}import J_ from"path";import{isDeepStrictEqual as od}from"util";var br={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var t_=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function i_(e,t){return e<t?-1:e>t?1:0}function r_(e,t,i,r){if(!Array.isArray(e)||e.length>i||!r&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let n=e.map(a=>{if(typeof a!="string"||!t_.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(i_)}function Fu(e=[]){return r_(e,"Native repair failed check IDs",br.maxFailedCheckIds,!0)}function Rg(e,t){let i=new Set(t);return e.every(r=>i.has(r))}function n_(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:Rg(e.failedAcceptanceIds,t.failedAcceptanceIds)&&Rg(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function qu(e,t){let i=1,r=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if(n_(r,a))break;i+=1,r=a}return i}import Ug from"node:path";import{createHash as Hg}from"node:crypto";import Ag from"path";var Mu="comet.native.implementation-scope.v2",Dg="comet.native.content-snapshot-projection.v1",qn="comet.native.content-snapshot-projection.v1",Bg="comet.native.implementation-scope.v2",a_="comet.native.unresolved-scope-id.v1",o_="comet.native.scope-detail-overflow.v1",s_="comet.native.snapshot-projection-overflow.v2",Gu=/^[a-f0-9]{64}$/u,Hi=1024*1024,c_=128,l_=128;function ve(e,t){return e<t?-1:e>t?1:0}function Wu(e){if(!Gu.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function u_(e,t){return e===t?0:e===null?-1:t===null?1:ve(e,t)}function li(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a normalized project-relative path`);let i=Ag.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||Ag.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function Lg(e,t){return e==="."?e:li(e,t)}function kr(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function d_(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:li(e.path,`${t} path`),hash:e.hash,size:kr(e.size,`${t} size`),type:"file"}}function f_(e,t){return{path:Lg(e.path,`${t} path`),size:e.size===null?null:kr(e.size,`${t} size`),type:e.type,reason:e.reason}}function p_(e,t){return ve(e.path,t.path)||ve(e.hash,t.hash)||e.size-t.size}function h_(e,t){return ve(e.path,t.path)||ve(e.reason,t.reason)||ve(e.type,t.type)||(e.size??-1)-(t.size??-1)}function Wn(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
170
170
  `,"utf8")}function ci(e,t,i){let r=`${t}
171
- ${Nn(i)}`;e.update(`${Buffer.byteLength(r,"utf8")}:`),e.update(r)}function p_(e){if(Wn(e)<=Hi)return e;let t=[...e.entries],i=[...e.omitted],r=e.omittedCount,n=e.omissionOverflow?.count??0,a=Hg("sha256");a.update(`${a_}
172
- `),e.omissionOverflow&&ci(a,"existing-overflow",e.omissionOverflow);let o=(f,p)=>{p||(r+=1),n+=1,ci(a,"omission",f)},s=f=>{r+=1,n+=1,ci(a,"entry",f)},c=()=>{for(let f=i.length-1;f>=0;f-=1){let p=i[f];if(!(p.reason==="git-enumeration-limit"||p.reason==="git-selection-changed"||p.reason==="physical-enumeration-limit"||p.reason==="physical-selection-changed"))return i.splice(f,1),p}return null},l=()=>({...e,complete:r===0,entries:t,omitted:i,omittedCount:r,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:n}}),u=l();for(;Wn(u)>Hi;){if(i.filter(p=>p.reason!=="git-enumeration-limit"&&p.reason!=="git-selection-changed"&&p.reason!=="physical-enumeration-limit"&&p.reason!=="physical-selection-changed").length>0){let p=Math.max(1,Math.ceil(i.length/4));for(let v=0;v<p;v+=1){let h=c();if(h===null)break;o(h,!0)}}else if(t.length>0){let p=Math.max(1,Math.ceil(t.length/4));for(let v of t.splice(-p))s(v)}else throw new Error("Native snapshot projection metadata exceeds its evidence byte budget");u=l()}let d=a.digest("hex");return{...u,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${d}`,hash:d,count:n}}}function zu(e){let t=_i(e),i=t.entries.map((n,a)=>l_(n,`Snapshot entry ${a}`));if(i.sort(d_),new Set(i.map(n=>n.path)).size!==i.length)throw new Error("Snapshot entries must not contain duplicate paths");let r=t.omitted.map((n,a)=>u_(n,`Snapshot omission ${a}`));return r.sort(f_),p_({schema:Dg,origin:t.origin,...t.capture?{capture:t.capture}:{},complete:t.complete,limits:{maxFiles:t.limits.maxFiles,maxFileBytes:t.limits.maxFileBytes,maxTotalBytes:t.limits.maxTotalBytes,maxManifestBytes:t.limits.maxManifestBytes,...t.limits.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},...t.policy?{policy:t.policy}:{},entries:i,omitted:r,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:{ref:t.omissionOverflow.ref,hash:t.omissionOverflow.hash,count:t.omissionOverflow.count}}:{}})}function zn(e){let t=new Map;for(let[i,r]of e.entries()){if(r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${i} kind is invalid`);let n={path:li(r.path,`Declared artifact ${i} path`),kind:r.kind},a=t.get(n.path);if(a&&a.kind!==n.kind)throw new Error(`Declared artifact path has conflicting kinds: ${n.path}`);t.set(n.path,n)}return[...t.values()].sort((i,r)=>ve(i.path,r.path)||ve(i.kind,r.kind))}function Jn(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function _g(e){return e?{hash:e.hash,size:e.size}:null}function Uu(e,t,i){let r=0,n=0;for(;r<e.entries.length||n<t.entries.length;){let a=e.entries[r],o=t.entries[n],s=a===void 0?1:o===void 0?-1:ve(a.path,o.path),c=s<=0?a:void 0,l=s>=0?o:void 0;if(s<=0&&(r+=1),s>=0&&(n+=1),c&&l&&c.hash===l.hash&&c.size===l.size||c&&!l&&!t.complete)continue;let u=c?.path??l?.path;u!==void 0&&i({path:u,kind:c?l?"modified":"removed":"added",before:_g(c),after:_g(l)})}}function Vg(e,t){return{...e,attributedTo:t.filter(i=>Jn(i,e.path))}}function Ku(e){let t=zn(e.declaredArtifacts),i=[];return Uu(e.baseline,e.current,r=>{i.push(Vg(r,t))}),i}function $t(e,t){return{id:`scope:${H(r_,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function h_(e,t){let i=t.omitted.map(r=>$t({kind:"snapshot-omission",source:e,path:r.path,evidence:{reason:r.reason,size:r.size,type:r.type}},`${e} snapshot omitted ${r.path}: ${r.reason}`));return t.complete||i.push($t({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&i.push($t({kind:"snapshot-omission-overflow",source:e,path:null,evidence:{count:t.omissionOverflow.count,hash:t.omissionOverflow.hash,ref:t.omissionOverflow.ref}},`${e} snapshot has ${t.omissionOverflow.count} unlisted omissions`)),i}function Ig(e,t){return h_(e,{...t,omitted:[]}).filter(i=>i.kind!=="snapshot-omission")}function Ju(e,t){return ve(e.kind,t.kind)||ve(e.source,t.source)||c_(e.path,t.path)||ve(e.id,t.id)}function m_(e){return[...new Map(e.map(i=>[i.id,i])).values()].sort(Ju)}function Fg(e){return[...new Set(e.map((t,i)=>li(t,`Git path ${i}`)))].sort(ve)}function Tg(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 v_(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 qg(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=Fg(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:Tg(e.baseCommit,"Native external drift base commit"),targetBranch:v_(e.targetBranch,"Native external drift target branch"),targetCommit:Tg(e.targetCommit,"Native external drift target commit"),paths:t}}function Mg(e){if(typeof e.contractHash!="string"||!Gu.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:zn(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:Fg(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:qg(e.externalDrift)}}}function g_(e,t,i,r,n){let a=[],o=r===void 0?null:new Set(r),s=[],c=[],l=0,u=!1,d=0,f=0;return Uu(e,t,p=>{let v=i.some(h=>Jn(h,p.path));if(d+=1,c.push(p.path),!v&&!n?.has(p.path)&&(f+=1),o?.has(p.path)&&s.push(p.path),!u&&a.length<o_){let h=Vg(p,i),m=Wn(h);l+m<=Hi?(a.push(h),l+=m):u=!0}}),{candidates:a,gitPathsPresentInChanges:s,changePaths:c,totalChanges:d,totalUnattributed:f}}function Wg(e,t){return $t({kind:"scope-detail-overflow",source:"implementation-scope",path:null,evidence:{changeCount:t.changes,hash:e,unattributedCount:t.unattributed,unresolvedCount:t.unresolved}},`Implementation scope summarized ${t.changes} additional change details and ${t.unresolved} unresolved details (${t.unattributed} unattributed); overflow hash ${e}`)}function w_(e){let t=/^Implementation scope summarized ([0-9]+) additional change details and ([0-9]+) unresolved details \(([0-9]+) unattributed\); overflow hash ([a-f0-9]{64})$/u.exec(e.reason);if(!t)throw new Error("Implementation scope detail overflow is invalid");let i={changes:kr(Number(t[1]),"Scope overflow change count"),unresolved:kr(Number(t[2]),"Scope overflow unresolved count"),unattributed:kr(Number(t[3]),"Scope overflow unattributed count")},r=Oi(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(Wg(r,i)))throw new Error("Implementation scope detail overflow is inconsistent");return{...i,hash:r}}function y_(e){let t=Hg("sha256");t.update(`${n_}
173
- `);let i=0;Uu(e.baseline,e.current,n=>{if(i>=e.detailedChangeCount){ci(t,"change",n);let a=0;for(let o of e.declaredArtifacts)Jn(o,n.path)&&(a+=1,ci(t,"change-attribution",o));ci(t,"change-end",{attributionCount:a}),a===0&&ci(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}i+=1});let r=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)r>=e.detailedOmissionCount&&ci(t,"snapshot-omission",{source:n,...o}),r+=1;return t.digest("hex")}function zg(e,t,i){let{contractHash:r,declaredArtifacts:n,noCodeReason:a}=i,o=g_(e,t,n,i.gitChangedPaths,i.externalDrift?new Set(i.externalDrift.paths):void 0);if(i.externalDrift){let x=new Set(i.externalDrift.paths),g=new Set(o.changePaths),w=i.externalDrift.paths.filter(C=>!g.has(C)||n.some($=>Jn($,C)));if(w.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${w.slice(0,8).join(", ")}`);if(x.size!==i.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=H(qn,e),c=H(qn,t),l=[],u=new Set(i.externalDrift?.paths??[]);for(let[x,g]of[["baseline",e],["current",t]])for(let w of g.omitted){if(l.length>=s_)break;l.push($t({kind:"snapshot-omission",source:x,path:w.path,evidence:{reason:w.reason,size:w.size,type:w.type}},`${x} snapshot omitted ${w.path}: ${w.reason}`))}let d=e.omitted.length+t.omitted.length,f=[...Ig("baseline",e),...Ig("current",t),...o.totalChanges===0&&a===null?[$t({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:s,currentProjectionHash:c}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],p=()=>{if(i.gitChangedPaths===void 0)return;let x=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:i.gitChangedPaths,pathsPresentInSnapshotChanges:i.gitChangedPaths.filter(g=>x.has(g)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(g=>!x.has(g))}},v=x=>{let g=o.candidates.slice(0,x.detailedChangeCount),w=g.filter(Ge=>Ge.attributedTo.length===0&&!u.has(Ge.path)),C=o.totalChanges-g.length,$=o.totalUnattributed-w.length,T=d-x.detailedOmissionCount,pe=$+T,Q=[...w.map(Ge=>$t({kind:"unattributed-change",source:"implementation-scope",path:Ge.path,evidence:{after:Ge.after,before:Ge.before,changeKind:Ge.kind}},`Changed path is not covered by a declared artifact: ${Ge.path}`)),...l.slice(0,x.detailedOmissionCount),...f,...pe>0?[Wg(x.overflowHash,{changes:C,unattributed:$,unresolved:pe})]:[]],G=m_(Q),lt=x.includeGitAdvisory?p():void 0;return{schema:Mu,contractHash:r,baselineProjectionRef:Wu(s),baselineProjectionHash:s,currentProjectionRef:Wu(c),currentProjectionHash:c,complete:G.length===0,declaredArtifacts:n,changes:g,unattributed:w,unresolvedScopes:G,noCodeReason:a,...lt?{gitAdvisory:lt}:{},...i.externalDrift?{externalDrift:i.externalDrift}:{}}},h=o.candidates.length,m=l.length,S=i.gitChangedPaths!==void 0,y="0".repeat(64);for(;;){let x=v({detailedChangeCount:h,detailedOmissionCount:m,includeGitAdvisory:S,overflowHash:y});if(Wn({...x,scopeHash:y})<=Hi)break;if(S){S=!1;continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}if(h>0){h-=Math.max(1,Math.ceil(h/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let N=o.totalChanges>h||d>m?y_({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:h,detailedOmissionCount:m}):y,E=v({detailedChangeCount:h,detailedOmissionCount:m,includeGitAdvisory:S,overflowHash:N}),b={...E,scopeHash:H(Bg,E)};if(Wn(b)>Hi)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return b}function Yu(e){let t=zu(e.baseline),i=zu(e.current),r=Mg(e);return{authority:r,baseline:t,current:i,scope:zg(t,i,r)}}var N_=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"]);function yt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Nt(e,t,i,r){let n=new Set([...t,...i]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${r} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${r} is missing field(s): ${o.join(", ")}`)}function Oi(e,t){if(typeof e!="string"||!Gu.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function jg(e,t,i){let r=Wu(t);if(e!==r)throw new Error(`${i} ref/hash mismatch`);return r}function ys(e,t){let i=yt(e,"Native snapshot projection");if(Nt(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==Dg)throw new Error("Native snapshot projection schema is invalid");let r=_i({schema:"comet.native.content-snapshot.v1",origin:i.origin,...i.capture===void 0?{}:{capture:i.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:i.complete,limits:i.limits,...i.policy===void 0?{}:{policy:i.policy},entries:i.entries,omitted:i.omitted,omittedCount:i.omittedCount,...i.omissionOverflow===void 0?{}:{omissionOverflow:i.omissionOverflow}}),n=zu(r);if(H(qn,i)!==H(qn,n))throw new Error("Native snapshot projection is not canonical");let a=H(qn,n);if(t!==void 0&&Oi(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function Xu(e,t){let i=yt(e,`Declared artifact ${t}`);if(Nt(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:li(i.path,`Declared artifact ${t} path`),kind:i.kind}}function $g(e,t){if(e===null)return null;let i=yt(e,t);return Nt(i,["hash","size"],[],t),{hash:Oi(i.hash,`${t} hash`),size:kr(i.size,`${t} size`)}}function Og(e,t){let i=yt(e,`Implementation change ${t}`);if(Nt(i,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),i.kind!=="added"&&i.kind!=="modified"&&i.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(i.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let r=i.attributedTo.map(Xu),n=zn(r);if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=$g(i.before,`Implementation change ${t} before`),o=$g(i.after,`Implementation change ${t} after`);if(i.kind==="added"&&(a!==null||o===null)||i.kind==="removed"&&(a===null||o!==null)||i.kind==="modified"&&(a===null||o===null||JSON.stringify(a)===JSON.stringify(o)))throw new Error(`Implementation change ${t} before/after state is invalid`);return{path:li(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:r}}function b_(e,t){let i=yt(e,`Unresolved scope ${t}`);Nt(i,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let r=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof i.kind!="string"||!r.has(i.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(i.source!=="baseline"&&i.source!=="current"&&i.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof i.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(i.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(i.path!==null&&typeof i.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof i.reason!="string"||i.reason.length===0||i.reason.trim()!==i.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:i.id,kind:i.kind,source:i.source,path:i.path===null?null:i.kind==="snapshot-omission"?Lg(i.path,`Unresolved scope ${t} path`):li(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function Mn(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of paths`);let i=e.map((n,a)=>li(n,`${t} ${a}`)),r=[...new Set(i)].sort(ve);if(JSON.stringify(i)!==JSON.stringify(r))throw new Error(`${t} must be sorted and unique`);return i}function Jg(e){let t=yt(e,"Native implementation external drift");if(Nt(t,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),t.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let i=Mn(t.paths,"Native external drift paths");return qg({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:i})}function Ns(e){let t=yt(e,"Native implementation scope"),i=[...N_].filter(w=>w!=="gitAdvisory"&&w!=="externalDrift");if(Nt(t,i,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==Mu)throw new Error("Native implementation scope schema is invalid");let r=Oi(t.contractHash,"Implementation scope contractHash"),n=Oi(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=jg(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=Oi(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=jg(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(Xu);if(JSON.stringify(c)!==JSON.stringify(zn(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(Og),u=[...l].sort((w,C)=>ve(w.path,C.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(w=>w.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(w=>`${w.kind}:${w.path}`));if(l.some(w=>w.attributedTo.some(C=>!d.has(`${C.kind}:${C.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(w=>JSON.stringify(w.attributedTo)!==JSON.stringify(c.filter(C=>Jn(C,w.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(Og),p=t.externalDrift===void 0?void 0:Jg(t.externalDrift),v=new Set(p?.paths??[]),h=l.filter(w=>w.attributedTo.length===0&&!v.has(w.path));if(JSON.stringify(f)!==JSON.stringify(h))throw new Error("Implementation scope unattributed changes are inconsistent");let m=t.unresolvedScopes.map(b_),S=m.filter(w=>w.kind==="scope-detail-overflow");if(S.length>1)throw new Error("Implementation scope has multiple detail overflow records");let y=S[0]===void 0?null:w_(S[0]);if(y&&(y.changes+y.unresolved===0||y.unattributed>y.changes||y.unattributed>y.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let k=t.noCodeReason,N=[...h.map(w=>$t({kind:"unattributed-change",source:"implementation-scope",path:w.path,evidence:{after:w.after,before:w.before,changeKind:w.kind}},`Changed path is not covered by a declared artifact: ${w.path}`)),...l.length+(y?.changes??0)===0&&k===null?[$t({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:n,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],E=m.filter(w=>w.kind==="unattributed-change"||w.kind==="missing-no-code-reason");if(JSON.stringify(m)!==JSON.stringify([...m].sort(Ju))||new Set(m.map(w=>w.id)).size!==m.length||JSON.stringify(E)!==JSON.stringify(N.sort(Ju))||t.complete!==(m.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let b;if(t.gitAdvisory!==void 0){let w=yt(t.gitAdvisory,"Implementation scope Git advisory");if(Nt(w,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),w.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let C=Mn(w.changedPaths,"Git changed paths"),$=Mn(w.pathsPresentInSnapshotChanges,"Git present paths"),T=Mn(w.pathsAbsentFromSnapshotChanges,"Git absent paths"),pe=[...$,...T].sort(ve);if(JSON.stringify(pe)!==JSON.stringify(C)||T.some(Q=>l.some(G=>G.path===Q)))throw new Error("Implementation scope Git advisory partition is invalid");b={advisoryOnly:!0,changedPaths:C,pathsPresentInSnapshotChanges:$,pathsAbsentFromSnapshotChanges:T}}let x={schema:Mu,contractHash:r,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:m,noCodeReason:k,...b?{gitAdvisory:b}:{},...p?{externalDrift:p}:{}},g=Oi(t.scopeHash,"Implementation scope scopeHash");if(H(Bg,x)!==g)throw new Error("Implementation scope content hash mismatch");return{...x,scopeHash:g}}function k_(e){let t=yt(e,"Native implementation scope authority");if(Nt(t,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths","externalDrift"],"Native implementation scope authority"),!Array.isArray(t.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let i=t.declaredArtifacts.map(Xu);if(JSON.stringify(i)!==JSON.stringify(zn(i)))throw new Error("Native implementation scope authority declarations must be canonical");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let r;t.gitChangedPaths!==void 0&&(r=Mn(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:Jg(t.externalDrift),a=Mg({contractHash:t.contractHash,declaredArtifacts:i,noCodeReason:t.noCodeReason,...r===void 0?{}:{gitChangedPaths:r},...n===void 0?{}:{externalDrift:n}});if(a.contractHash!==t.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return a}function Gn(e){let t=yt(e,"Native implementation scope bundle");Nt(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=k_(t.authority),r=ys(t.baseline),n=ys(t.current),a=Ns(t.scope),o=zg(r,n,i);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:i,baseline:r,current:n,scope:o}}function Gg(e){let t=Ns(e.scope);return Gn({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 Yg=/^[a-f0-9]{64}$/u;var S_="comet.native.acceptance-trace.v2",E_="comet.native.partial-allowance.v1",C_="comet.native.verification-evidence.v2";function Ot(e,t){if(!Yg.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Xg(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function Qg(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 Qu(e,t,i=2e3){let r=We(e).trim();if(r.length===0||r.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return r}function Un(e,t){let i=Ug.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||Ug.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function x_(e,t,i){let r=Un(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(r))return r;let n=ft(r),a=r.toLowerCase(),o=i?Un(i,"Native root ref").toLowerCase():null;if(n||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${t} is excluded as sensitive (${n??"native-runtime"}): ${r}`);return r}function Zu(e){let t=Un(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 Sr(e,t){return e<t?-1:e>t?1:0}function bs(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ks(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function Zg(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function Kg(e,t,i){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let r=`runtime/evidence/${t}/${i}.json`;if(e!==r)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function P_(e){let t=bs(e,"Native acceptance trace");if(ks(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"||!Yg.test(t.criteriaHash)||!Number.isSafeInteger(t.total)||!Number.isSafeInteger(t.evidenced)||!Number.isSafeInteger(t.skipped)||!Array.isArray(t.entries))throw new Error("Native acceptance trace is invalid");let i=Un(t.nativeRootRef,"Native root ref"),r=t.entries.map((o,s)=>{let c=bs(o,`Native acceptance trace entry ${s}`);if(ks(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=>Zu(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Sr))||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:Un(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Qu(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(r)!==JSON.stringify([...r].sort((o,s)=>Sr(o.acceptanceId,s.acceptanceId)))||new Set(r.map(o=>o.acceptanceId)).size!==r.length||t.total!==r.length||t.evidenced!==r.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==r.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let n={schema:"comet.native.acceptance-trace.v2",nativeRootRef:i,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:r},a=Ot(t.traceHash,"Native acceptance trace hash");if(H(S_,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function ew(e){let t=bs(e,"Native partial allowance");if(ks(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(Sr))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let i={schema:"comet.native.partial-allowance.v1",change:Qg(t.change),scopeHash:Ot(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Qu(t.reason,"Partial allowance reason"),confirmedSummary:Qu(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:Xg(t.sourceRevision),confirmedAt:Zg(t.confirmedAt,"Native partial allowance timestamp")};if(i.reason!==t.reason||i.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let r=Ot(t.allowanceHash,"Native partial allowance hash");if(H(E_,i)!==r)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:r}}function ed(e){let t=bs(e,"Native verification evidence");if(ks(t,["schema","change","sourceRevision","result","freshness","contractHash","acceptanceCriteriaHash","implementationScopeRef","implementationScopeHash","reportRef","reportHash","acceptanceTrace","partialAllowanceRef","partialAllowanceHash","requiredReceiptRefs","receiptRefs","createdAt","envelopeHash"],"Native verification evidence"),t.schema!=="comet.native.verification-evidence.v2"||typeof t.change!="string"||t.result!=="pass"&&t.result!=="fail"||t.freshness!=="complete"&&t.freshness!=="partial"||typeof t.implementationScopeHash!="string"||typeof t.reportRef!="string"||!Array.isArray(t.requiredReceiptRefs)||!Array.isArray(t.receiptRefs))throw new Error("Native verification evidence is invalid");let i=Ot(t.implementationScopeHash,"Native verification implementation scope hash"),r=P_(t.acceptanceTrace),n=Ot(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(r.criteriaHash!==n)throw new Error("Native verification acceptance trace does not match its criteria hash");let a=t.partialAllowanceRef!==null||t.partialAllowanceHash!==null;if(t.partialAllowanceRef===null!=(t.partialAllowanceHash===null)||t.freshness==="complete"&&a||t.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=t.partialAllowanceHash===null?null:Ot(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>Zu(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(Sr)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(r.entries.flatMap(f=>f.evidenceRefs))].sort(Sr);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=t.requiredReceiptRefs.map(f=>Zu(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Sr)))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:Qg(t.change),sourceRevision:Xg(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:Ot(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:Kg(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:x_(t.reportRef,"Native verification report ref"),reportHash:Ot(t.reportHash,"Native verification report hash"),acceptanceTrace:r,partialAllowanceRef:o===null?null:Kg(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:Zg(t.createdAt,"Native verification timestamp")},d=Ot(t.envelopeHash,"Native verification envelope hash");if(H(C_,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}function td(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 tw="repairStagnation",$e={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},A_=/^[a-f0-9]{64}$/u;var __=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),I_=["data","runId","sequence","timestamp","type"],iw=["disposition","overrideSummaryHash","signatureHash"],T_=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],rw=12;function rd(e,t){return e<t?-1:e>t?1:0}function nw(e,t,i){let r=Object.keys(e).sort(rd);if(r.length!==t.length||r.some((n,a)=>n!==t[a]))throw new Error(`${i} fields are invalid`)}function Ss(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function Kn(e,t){if(typeof e!="string"||!A_.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function j_(e){if(!Array.isArray(e)||e.length>br.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(rd)}function aw(e){if(typeof e!="string"||e.length===0||e.length>$e.maxRunIdCharacters||Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function id(e,t,i,r,n=!1){if(i.nodes+=1,i.nodes>$e.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>$e.maxDataDepth)throw new Error("Native repair trajectory event data exceeds its depth boundary");if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${r} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>$e.maxTextCharacters&&(!n||e.length>$e.maxEventDataCharacters))throw new Error(`${r} contains oversized text`);if(i.characters+=e.length,i.characters>$e.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${r} contains a non-JSON value`);if(i.ancestors.has(e))throw new Error(`${r} contains a cycle`);i.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>$e.maxArrayEntries)throw new Error(`${r} contains an oversized array`);e.forEach((s,c)=>id(s,t+1,i,`${r}[${c}]`));return}let a=Ss(e,r),o=Object.keys(a);if(o.length>$e.maxObjectFields)throw new Error(`${r} contains too many fields`);for(let s of o){if(s.length===0||s.length>$e.maxKeyCharacters)throw new Error(`${r} contains an invalid field name`);if(i.characters+=s.length,i.characters>$e.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");id(a[s],t+1,i,`${r}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function $_(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 O_(e,t,i){let r=Ss(e,`Native repair trajectory event ${t+1}`);if(nw(r,I_,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(r.sequence)||r.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if($_(r.timestamp),typeof r.type!="string"||!__.has(r.type))throw new Error("Native repair trajectory event type is invalid");if(aw(r.runId)!==i)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let n={nodes:0,characters:0,ancestors:new Set};return id(r.data,0,n,"Native trajectory event data"),Ss(r.data,"Native repair trajectory event data"),{event:r,dataNodes:n.nodes,dataCharacters:n.characters}}function nd(e){let t=Ss(e,"Native repair trajectory projection"),i=Object.keys(t).sort(rd),r=i.length===iw.length&&i.every((l,u)=>l===iw[u]);r||nw(t,T_,"Native repair trajectory projection");let n=Kn(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:Kn(t.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&t.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(r)return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=Kn(t.contractHash,"Native repair trajectory contract hash"),s=j_(t.failedAcceptanceIds),c=Fu(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 H_(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 D_(e,t){let i=t.filter(s=>s.kind==="failure"),r=i.length+1,n=e.maxVerifyFailures??rw;if(r>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=qu({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=r>=n?"hard-stop":a<br.warningAtConsecutiveFailures?"continue":a<br.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function B_(e,t,i){let r=t.filter(a=>a.kind==="failure"),n=i?.maxVerifyFailures??rw;if(r.length>=n)throw new Error("Native repair trajectory cannot override a hard stop");if(i?.disposition!=="manual-stop"||i.signatureHash!==e.signatureHash||r.at(-1)?.signatureHash!==e.signatureHash)throw new Error("Native repair trajectory override does not match the latest manual stop");if(t.some(a=>a.kind==="override"&&a.signatureHash===e.signatureHash))throw new Error("Native repair trajectory signature was already overridden")}function ow(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>$e.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=aw(e.runId);if(!Number.isSafeInteger(e.committedTrajectoryOffset)||e.committedTrajectoryOffset<0||e.committedTrajectoryOffset>e.trajectory.length)throw new Error("Native repair committed trajectory offset is invalid");let i=[],r=null,n=null,a=null,o=0,s=0,c=0;for(let l=0;l<e.committedTrajectoryOffset;l+=1){let u=O_(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>$e.maxTotalDataNodes||c>$e.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,p=Object.hasOwn(f,"repairScopeHash")?Kn(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?Kn(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,tw)){if(r?.contractHash===null&&d.type==="state_transitioned"&&f.previousPhase==="build"&&f.nextPhase==="verify"&&(p!==null&&n!==null&&p!==n||p===null&&(r?.disposition==="manual-stop"||r?.disposition==="hard-stop"))){i.length=0,r=null,n=p,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let v=nd(f[tw]);if(H_(f,v),v.overrideSummaryHash===null)v.contractHash!==null&&a!==null&&v.contractHash!==a&&(i.length=0,o=0),v.contractHash!==null&&(a=v.contractHash),v.contractHash===null&&p!==null&&n!==null&&p!==n&&(i.length=0,o=0),p!==null&&(n=p),D_(v,i),o+=1,i.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:v.signatureHash,...v.contractHash===null?{}:{failedAcceptanceIds:[...v.failedAcceptanceIds],failedCheckIds:[...v.failedCheckIds]}});else{if(r?.contractHash===null&&p!==null&&n!==null&&p!==n)throw new Error("Native repair override cannot cross implementation scope progress");B_(v,i,r);let h=i.at(-1);if(!h||h.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");i.push({kind:"override",revision:d.sequence,iteration:h.iteration,signatureHash:v.signatureHash,summaryHash:v.overrideSummaryHash})}if(r=v,i.length>br.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:r}}function sw(e){return ow(e).history}function cw(e){let t=ow(e).latestProjection;return t?{...t}:null}var Er={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:[]},ad=K("comet-native-runtime:v3:scope-reopen"),L_=[{skillVersion:"3",skillHash:K("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:K("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:K("comet-native-runtime:v1")}];function lw(e){return e.skillVersion===Er.definition.metadata.version&&e.skillHash===ad||L_.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}function uw(e){return K(JSON.stringify({summary:e.summary,returnToBuild:e.returnToBuild??!1,confirmed:e.confirmed??!1,artifacts:[...e.artifacts??[]].sort(),noCodeReason:e.noCodeReason??null,verificationResult:e.verificationResult??null,verificationReport:e.verificationReport??null,allowPartialScopeHash:e.allowPartialScopeHash??null,partialReason:e.partialReason??null,repairOverrideSignature:e.repairOverrideSignature??null,repairOverrideSummary:e.repairOverrideSummary??null}))}var mw=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],z_=new Set(mw),vw=new Set([...mw,"minimum_runtime_version","revision"]),J_=new Set([...vw,"operation"]),G_=512*1024,sd=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),U_=new Set([...sd,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),cd=class extends Error{constructor(i){super(`Native transition for ${i} requires doctor migration before recovery`);this.change=i;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function ud(e,t){return W_.join(U(e,t),"transition.json")}function Cs(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function dd(e,t){let i=Object.keys(e).find(r=>!t.has(r));if(i)throw new Error(`Native transition journal contains unknown field: ${i}`)}function Es(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function ld(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let i=e,r=Object.keys(i),n=r.find(u=>!U_.has(u)),a=[...sd].find(u=>!Object.hasOwn(i,u)),o=sd.size+(Object.hasOwn(i,"implementationScopeHash")?1:0)+(Object.hasOwn(i,"repairScopeHash")?1:0)+(Object.hasOwn(i,"repairStagnation")?1:0)+(Object.hasOwn(i,"returnToBuild")?1:0);if(n||a||r.length!==o)throw new Error(`Native transition journal event data keys are invalid${n?`: ${n}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(i.previousPhase)||!["shape","build","verify","archive"].includes(i.nextPhase))throw new Error("Native transition journal event phases are invalid");if(i.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if(i.returnToBuild!==void 0&&typeof i.returnToBuild!="boolean")throw new Error("Native transition journal returnToBuild flag is invalid");if(td(i.summary,"Native transition journal event summary"),We(i.summary)!==i.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(i.artifacts)||i.artifacts.length>128||i.artifacts.some(u=>typeof u!="string"||u.length===0||Buffer.byteLength(u,"utf8")>512))throw new Error("Native transition journal event artifacts are invalid");if(i.noCodeReason!==null&&(td(i.noCodeReason,"Native transition journal event no-code reason"),We(i.noCodeReason)!==i.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(i.verificationResult!==null&&i.verificationResult!=="pass"&&i.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(i,"implementationScopeHash")?i.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||i.previousPhase!=="build"&&i.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(i,"repairStagnation")?nd(i.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(i.previousPhase!=="verify"||i.nextPhase!=="build"||i.verificationResult!=="fail")||!u&&(i.previousPhase!=="build"||i.nextPhase!=="verify"||i.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(i,"repairScopeHash")?i.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||i.previousPhase!=="build"&&i.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:t,summary:i.summary,artifacts:[...i.artifacts],noCodeReason:i.noCodeReason,verificationResult:i.verificationResult,...i.returnToBuild===!0?{returnToBuild:!0}:{},...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function K_(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let i=e,r=Object.keys(i),n=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(r.length===n.size&&r.every(a=>n.has(a))&&i.reason==="spec-rebase")return ld({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return ld(e,t)}function fd(e,t,i=!1){if(e.change!==t)throw new Error("Native transition journal change mismatch");if(typeof e.id!="string"||e.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof e.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(e.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native transition journal timestamp is invalid");let r=i?K_(e.eventData,e.evidenceHash):ld(e.eventData,e.evidenceHash),n=hu(e.nextRun),a=e.previousRun===null?null:hu(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:r}}function dw(e,t,i=!1){if(e.skill!==Er.definition.metadata.name||(i?!lw(e):e.skillVersion!==Er.definition.metadata.version||e.skillHash!==ad)||e.orchestration!==Er.definition.orchestration.mode||e.pendingRef!==qe.pendingRef||e.trajectoryRef!==qe.trajectoryRef||e.contextRef!==qe.contextRef||e.artifactsRef!==qe.artifactsRef||e.checkpointRef!==qe.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function fw(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 pw(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 pd(e,t,i,r=!1,n="advance"){let{previousRun:a,nextRun:o}=i;if(dw(o,"next Run",r||a!==null),pw(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(dw(a,"previous Run",!0),pw(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(!od(fw(a),fw(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function Y_(e,t,i){return K(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function gw(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function hw(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function hd(e,t,i,r,n=!1){let a=i.eventData,o=hw(e),s=hw(t);if(a.previousPhase!==e.phase||a.nextPhase!==t.phase)throw new Error("Native transition journal event phases do not match its states");if(e.archived||t.archived)throw new Error("Native transition journal cannot mutate an archived change");if(r==="runtime-rebuild"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&od(e.spec_changes,t.spec_changes);if(e.phase==="shape"||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||!c||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native Runtime rebuild transition semantics are invalid");return}if(r==="evidence-retreat"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&e.run_id===t.run_id&&od(e.spec_changes,t.spec_changes),l=uw({summary:a.summary,...a.returnToBuild?{returnToBuild:!0}:{}});if(!(e.phase==="archive"&&e.verification_result==="pass"||e.phase==="verify"&&e.verification_result==="pending")||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||i.evidenceHash!==l||!c||o===null||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native transition journal evidence retreat semantics are invalid");return}if(r==="spec-rebase"){let c=Y_(e.name,a.summary,t.spec_changes),l=K(`spec-rebase:${e.name}:${a.summary}`);if(e.phase==="shape"||t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||t.verification_report!==null||!n&&i.evidenceHash!==c||n&&i.evidenceHash!==c&&i.evidenceHash!==l||"implementation_scope"in t&&(t.implementation_scope!==null||t.verification_evidence!==null||t.partial_allowance!==null))throw new Error("Native transition journal spec rebase semantics are invalid");return}if(e.phase==="shape"){if(t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!=="pending"||t.verification_result!=="pending"||e.verification_report!==null||t.verification_report!==null||o!==null&&s!==null&&(o.implementation_scope!==null||o.verification_evidence!==null||o.partial_allowance!==null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null))throw new Error("Native transition journal Shape to Build semantics are invalid");return}if(e.phase==="build"){if(t.phase!=="verify"||a.verificationResult!==null||a.artifacts.length===0&&a.noCodeReason===null||t.verification_result!=="pending"||t.verification_report!==null||o!==null&&s!==null&&(s.implementation_scope===null||s.verification_evidence!==null||s.implementation_scope!==o.implementation_scope&&s.partial_allowance!==null&&s.partial_allowance===o.partial_allowance))throw new Error("Native transition journal Build to Verify semantics are invalid");return}if(e.phase==="verify"){let c=a.verificationResult==="pass"?"archive":"build";if(a.verificationResult!=="pass"&&a.verificationResult!=="fail"||t.phase!==c||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!==a.verificationResult||t.verification_report===null||o!==null&&s!==null&&(o.implementation_scope===null||s.implementation_scope!==o.implementation_scope||s.partial_allowance!==o.partial_allowance||o.verification_evidence!==null||s.verification_evidence===null))throw new Error("Native transition journal Verify outcome semantics are invalid");return}throw new Error("Native transition journal cannot advance from Archive")}function X_(e,t){let i=Cs(e);if(dd(i,J_),i.schema!==sr)throw new Error(`Expected Native transition schema ${sr}`);let r=Es(i.minimum_runtime_version,"Native transition minimum_runtime_version");if(r>3)throw new Error(`Native transition requires runtime protocol ${r}; current protocol is ${3}`);if(r!==3)throw new Error(`Native transition ${sr} minimum_runtime_version must be ${3}`);let n=Es(i.revision,"Native transition revision");if(n!==1)throw new Error("Native transition journal revision must be 1");if(i.operation!=="advance"&&i.operation!=="spec-rebase"&&i.operation!=="evidence-retreat"&&i.operation!=="runtime-rebuild")throw new Error("Native transition journal operation is invalid");let a=fd(i,t),o=ni(i.previousState),s=ni(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(hd(o,s,a,i.operation),pd(o,s,a,!1,i.operation),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:sr,minimum_runtime_version:3,revision:n,operation:i.operation,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function Q_(e,t){let i=Cs(e);if(dd(i,z_),i.schema!==Cn)throw new Error(`Expected Native transition schema ${Cn}`);let r=fd(i,t,!0),n=lr(i.previousState),a=lr(i.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return hd(n,a,r,gw(n,a,r.eventData),!0),pd(n,a,r,!0),{schema:Cn,id:r.id,change:t,evidenceHash:r.evidenceHash,createdAt:r.createdAt,previousState:n,nextState:a,previousRun:r.previousRun,nextRun:r.nextRun,eventData:r.eventData}}function Z_(e,t){let i=Cs(e);if(dd(i,vw),i.schema!==cr)throw new Error(`Expected Native transition schema ${cr}`);if(Es(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${cr} minimum_runtime_version must be 2`);let n=Es(i.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=fd(i,t,!0),o=ur(i.previousState),s=ur(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(hd(o,s,a,gw(o,s,a.eventData),!0),pd(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:cr,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 eI(e,t){let i=Cs(e);if(i.schema===sr)return{status:"current",journal:X_(i,t)};if(i.schema===Cn)return{status:"migration-required",journal:Q_(i,t)};if(i.schema===cr)return{status:"migration-required",journal:Z_(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function tI(e,t){let i=ud(e,t),r=ue(e,i);await z(r,i);try{let n=await mt({root:r,file:i,maxBytes:G_,label:`Native transition journal ${t}`});return eI(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function ww(e,t){let i=await tI(e,t);if(!i)return null;if(i.status==="migration-required")throw new cd(t);return i.journal}var iI=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function rI(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function nI(e){return e?e.map(rI).join(" "):null}function aI(e){if(e===null)return null;let t=e.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/gu);return!t||t[0]!=="comet"?null:t.map(i=>{if(i.startsWith('"')&&i.endsWith('"'))try{return JSON.parse(i)}catch{return i.slice(1,-1)}return i.startsWith("'")&&i.endsWith("'")?i.slice(1,-1):i})}function ze(e,t,i,r={}){return{input:e,flags:t,required:r.required??!0,placeholder:i,...r.choices?{choices:r.choices}:{},...r.repeatable?{repeatable:!0}:{},...r.alternativeGroup?{alternativeGroup:r.alternativeGroup}:{}}}function oI(e){return e.map(t=>ze(t,[],null))}function sI(e){let t=["comet","native","next",e.name,"--summary","<summary>"],i=[ze("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),i.push(ze("shared-understanding-confirmation",["--confirmed"],null)),{commandArgs:t,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:i};if(e.phase==="build"){t.push("--artifact","<project-relative-path>"),i.push(ze("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),ze("artifact-or-no-code-reason",["--no-code-reason"],"<reason>",{alternativeGroup:"build-evidence"}));let r=["summary","artifact-or-no-code-reason"];return e.approval!=="confirmed"&&(t.push("--confirmed"),r.push("shared-understanding-confirmation"),i.push(ze("shared-understanding-confirmation",["--confirmed"],null))),{commandArgs:t,requiredInputs:r,inputOptions:i}}return e.phase==="verify"?(t.push("--result","<pass|fail>","--report","<change-relative-path>"),i.push(ze("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),ze("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:i}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function ge(e,t){let i=t.commandArgs===void 0?aI(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?nI(i??null):t.command,commandArgs:i??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??oI(t.requiredInputs??[])}}function xs(e){let i=(e.findings??[]).filter(d=>!wr(d.code)),r=i.find(d=>d.requiresUserDecision),n=i.find(d=>d.repairCommand!==null||iI.test(d.code)),a=i.find(d=>d.code==="repair-iteration-limit"||d.code==="repair-override-exhausted"),o=i.find(d=>d.code==="repair-stagnation-stop"),s=i.find(d=>d.requiredAction==="return-to-bound-working-directory"||d.requiredAction==="repair-workspace-binding"),c=i.find(d=>d.code==="runtime-missing"),l=[...new Set(i.map(d=>d.requiredAction))].sort();if(e.done)return ge(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return ge(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[ze("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(r)return ge(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return ge(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return ge(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return ge(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[ze("summary",["--summary"],"<summary>")]});if(n)return ge(e.state,{disposition:"blocked",action:"repair",command:n.repairCommand,requiredInputs:l});if(e.evidenceRetreat){let d=["comet","native","next",e.state.name,"--summary","<summary>"];return ge(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[ze("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return ge(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(i.length>0)return e.state.phase==="archive"?ge(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?ge(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):ge(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:l});if(e.state.phase==="archive"){if(e.archiveReady&&e.archivePreflightHash){if(!/^[a-f0-9]{64}$/u.test(e.archivePreflightHash))throw new Error("Native Archive continuation preflight must be a SHA-256 hash");let d=["comet","native","archive",e.state.name,"--expect-preflight",e.archivePreflightHash];return e.archiveConfirmation==="required"?(d.push("--confirmed"),ge(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[ze("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):ge(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return ge(e.state,{disposition:e.archiveReady?"continue":"blocked",action:e.archiveReady?"archive":"none",commandArgs:e.archiveReady?["comet","native","archive",e.state.name,"--dry-run"]:null,requiredInputs:e.archiveReady?[]:["archive-readiness"]})}let u=sI(e.state);return ge(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import Yn from"path";var yw=8,cI={"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 lI(e){let t=cI[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"}:wr(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 uI(e,t,i){if(!i.path)return null;let r;if(Yn.isAbsolute(i.path)?r=Yn.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?r=Yn.resolve(me(e,t.name),...i.path.split(/[\\/]/u)):r=Yn.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!V(e.projectRoot,r))return null;let n=Yn.relative(e.projectRoot,r).replaceAll("\\","/");return n===""?".":n}function dI(e,t,i){return e==="next"?`comet native next ${t.name} --summary "<summary>"${i==="contract-changed-after-approval"||i==="shape-confirmation-required"||i==="approval-confirmation-required"?" --confirmed":""}`:e==="status"?`comet native status ${t.name} --details`:null}function md(e){return e.findings.map(t=>{let i=lI(t.code);return{code:t.code,message:t.message,severity:i.severity,path:uI(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:dI(i.retry,e.state,t.code),repairCommand:i.repair==="doctor"?`comet native doctor ${e.state.name} --repair${t.code.startsWith("transition-")?" --strategy continue":""}`:null,requiresUserDecision:t.code==="brief-blocking-question"||t.code==="shape-confirmation-required"||t.code==="approval-confirmation-required"||t.code==="contract-changed-after-approval"||t.code==="verification-scope-partial"||t.code==="repair-iteration-limit"||t.code==="repair-override-exhausted"}}).sort((t,i)=>{let r={error:0,warning:1,info:2};return r[t.severity]-r[i.severity]||t.code.localeCompare(i.code)||(t.path??"").localeCompare(i.path??"")||t.message.localeCompare(i.message)})}function vd(e){let t=[...new Set(e.map(i=>i.code))];return{total:e.length,errors:e.filter(i=>i.severity==="error").length,warnings:e.filter(i=>i.severity==="warning").length,info:e.filter(i=>i.severity==="info").length,requiresUserDecision:e.some(i=>i.requiresUserDecision),codes:t.slice(0,yw),truncated:t.length>yw}}import Cr from"path";var di={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},xr=/^[a-f0-9]{64}$/u;function Ps(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Rs(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function ui(e,t,i=2e3){if(typeof e!="string"||e.length===0||e.length>i)throw new Error(`${t} must be a non-empty string of at most ${i} characters`);return e}function Nw(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function gd(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function fI(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||Cr.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=Cr.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function bw(e,t){return Cr.join(U(e,t),"checkpoints","progress.json")}function Xn(e,t){return Cr.join(U(e,t),"checkpoint-journal.json")}function kw(e,t,i){if(!xr.test(i))throw new Error("Native checkpoint manifest hash is invalid");return Cr.join(U(e,t),"checkpoints","manifests",`${i}.json`)}function pI(e){if(!xr.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function wd(e,t,i){let r=await mt({root:e,file:t,maxBytes:di.maxDocumentBytes,label:i});return JSON.parse(r.bytes.toString("utf8"))}function hI(e,t){let i=Ps(e,`checkpoint manifest artifact ${t}`);Rs(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let r=fI(ui(i.path,`checkpoint artifact ${t} path`,4096)),n=ft(r);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${r}`);if(typeof i.hash!="string"||!xr.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:r,hash:i.hash,size:gd(i.size,`checkpoint artifact ${t} size`)}}function yd(e,t){let i=Ps(e,"Native checkpoint manifest");if(Rs(i,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),i.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(i.change!==t)throw new Error("Native checkpoint manifest change mismatch");if(!Array.isArray(i.artifacts))throw new Error("Native checkpoint manifest artifacts must be an array");if(i.artifacts.length>di.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let r=i.artifacts.map(hI),n=[...r].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(r)!==JSON.stringify(n))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(r.map(o=>o.path)).size!==r.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=gd(i.totalBytes,"checkpoint manifest totalBytes");if(r.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");if(a>di.maxTotalBytes)throw new Error("Native checkpoint manifest totalBytes exceeds its budget");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:r,totalBytes:a}}function Sw(e){return K(JSON.stringify(yd(e,e.change)))}function Ew(e,t){let i=Ps(e,"Native progress checkpoint");if(Rs(i,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),i.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(i.change!==t)throw new Error("Native checkpoint change mismatch");let r=i.phase;if(r!=="shape"&&r!=="build"&&r!=="verify"&&r!=="archive")throw new Error("Native checkpoint phase is invalid");let n=Nw(i.previousRevision,"Native checkpoint previousRevision"),a=Nw(i.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=ui(i.manifestHash,"Native checkpoint manifestHash",64);if(!xr.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=pI(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=ui(i.inputHash,"Native checkpoint inputHash",64);if(!xr.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=ui(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=gd(i.artifactCount,"Native checkpoint artifactCount");if(u>di.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=ui(i.summary,"Native checkpoint summary"),f=ui(i.nextAction,"Native checkpoint nextAction");if(We(d)!==d||We(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:ui(i.id,"Native checkpoint id",128),change:t,phase:r,previousRevision:n,stateRevision:a,summary:d,nextAction:f,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function mI(e,t){let i=Ps(e,"Native checkpoint journal");if(Rs(i,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),i.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(i.change!==t)throw new Error("Native checkpoint journal change mismatch");let r=ni(i.previousState),n=ni(i.nextState),a=Ew(i.checkpoint,t),o=yd(i.manifest,t),s=ui(i.inputHash,"Native checkpoint journal inputHash",64),c=K(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!xr.test(s)||s!==a.inputHash||s!==c||i.id!==a.id||i.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(r.name!==t||n.name!==t||n.revision!==r.revision+1||a.previousRevision!==r.revision||a.stateRevision!==n.revision||a.phase!==n.phase||a.manifestHash!==Sw(o)||a.artifactCount!==o.artifacts.length)throw new Error("Native checkpoint journal state mismatch");return{schema:"comet.native.checkpoint-journal.v1",id:a.id,change:t,inputHash:s,createdAt:a.createdAt,previousState:r,nextState:n,checkpoint:a,manifest:o}}async function vI(e,t,i){let r=Cr.resolve(e.projectRoot,...t.split("/"));if(!V(e.projectRoot,r)||V(e.nativeRoot,r)||V(e.runtimeDir,r))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=El(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await mt({root:e.projectRoot,file:r,maxBytes:di.maxFileBytes,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot,e.runtimeDir],hooks:{afterParentChainCaptured:()=>i?.afterParentChainCaptured?.(t),afterOpen:()=>i?.afterOpen?.(t),beforeRead:()=>i?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function gI(e,t){let i=bw(e,t),r=ue(e,i);await z(r,i);try{return Ew(await wd(r,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function wI(e,t,i){let r=kw(e,t,i),n=ue(e,r);await z(n,r);let a=await wd(n,r,"Native checkpoint manifest"),o=yd(a,t);if(Cw(e,o),Sw(o)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function Nd(e,t){let i=Xn(e,t),r=ue(e,i);await z(r,i);try{let n=mI(await wd(r,i,"Native checkpoint journal"),t);return Cw(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}function Cw(e,t){for(let i of t.artifacts){let r=El(e,i.path);if(r)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${r}): ${i.path}`)}}async function xw(e){let t;try{t=await gI(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:bw(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let i=[],r=[];t.stateRevision!==e.stateRevision&&i.push("state-revision-changed");let n=null;try{n=await wI(e.paths,e.name,t.manifestHash);let a=K(JSON.stringify({summary:t.summary,nextAction:t.nextAction,artifacts:n.artifacts}));if(t.inputHash!==a||t.artifactCount!==n.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");for(let o of n.artifacts)try{let s=await vI(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&i.push(`artifact-changed:${o.path}`)}catch{i.push(`artifact-unavailable:${o.path}`)}}catch(a){i.push("checkpoint-manifest-invalid"),r.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:kw(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:i.length===0?"fresh":"stale",reasons:i,findings:r}}var Pw=240,Rw=8,As=50;function Aw(e){let t=Array.from(e);return t.length<=Pw?e:`${t.slice(0,Pw-1).join("")}…`}function yI(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function NI(e){let t=[...new Set(e.map(yI))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,Rw),reasonCount:e.length,codesTruncated:t.length>Rw};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,As),reasonsTruncated:e.length>As}}}async function _w(e){let t=null;try{let s=await Nd(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:Xn(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:Xn(e.paths,e.state.name)}}let i=await xw({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),r=t?[t.code,...i.reasons]:i.reasons,n=NI(r);if(!i.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:di.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:Aw(i.checkpoint.summary),nextAction:Aw(i.checkpoint.nextAction),artifactCount:i.checkpoint.artifactCount},o=i.manifest?{...a,summary:i.checkpoint.summary,nextAction:i.checkpoint.nextAction,manifestHash:i.checkpoint.manifestHash,manifestRef:i.checkpoint.manifestRef,artifacts:i.manifest.artifacts,totalBytes:i.manifest.totalBytes}:null;return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:di.maxArtifacts}}import{promises as sj}from"node:fs";import uy from"node:path";import Iw from"node:path";var bI="comet.native.archive-preflight.v1",kI="comet.native.archive-preflight.v1",SI="comet.native.archive-operation.v1",EI=/^[a-f0-9]{64}$/u,Tw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,CI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function _s(e,t){return e<t?-1:e>t?1:0}function xI(e,t){if(typeof e!="string"||!EI.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ht(e,t){return e===null?null:xI(e,t)}function PI(e,t){let i=Iw.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||Iw.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized Native-relative ref`);return e}function RI(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function AI(e){if(e==null)return null;if(e.schema!=="comet.native.workspace.v3")throw new Error("Native archive workspace schema is invalid");if(e.isolation!=="current"&&e.isolation!=="branch"&&e.isolation!=="worktree")throw new Error("Native archive workspace isolation is invalid");for(let[t,i]of[["change",e.changeBranch],["target",e.targetBranch]])if(i!==null&&(i.length===0||i.trim()!==i||Array.from(i).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})))throw new Error(`Native archive workspace ${t} branch is invalid`);if(e.finish!==null&&e.finish!=="merge"&&e.finish!=="push"&&e.finish!=="pull-request"&&e.finish!=="keep")throw new Error("Native archive workspace finish is invalid");if((e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null||e.finish===null))throw new Error("Native isolated archive workspace requires branches and a finish action");if(e.isolation==="current"&&e.finish!==null)throw new Error("Native current archive workspace cannot have a finish action");return{...e}}function _I(e,t){if(!Tw.test(e.capability))throw new Error(`Native archive spec ${t} capability is invalid`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Native archive spec ${e.capability} operation is invalid`);let i=Ht(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),r=Ht(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=Ht(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&i!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&i===null)throw new Error(`Native archive ${e.operation} ${e.capability} requires a base hash`);if(e.operation==="remove"!=(n===null))throw new Error(`Native archive ${e.operation} ${e.capability} proposed hash is invalid`);return{capability:e.capability,operation:e.operation,expectedBaseHash:i,actualBaseHash:r,proposedHash:n}}function II(e){if(e.result!=="pending"&&e.result!=="pass"&&e.result!=="fail")throw new Error("Native archive verification result is invalid");if(!["missing","invalid","stale","complete","partial"].includes(e.freshness))throw new Error("Native archive verification freshness is invalid");if(!Number.isSafeInteger(e.skippedAcceptanceCount)||e.skippedAcceptanceCount<0)throw new Error("Native archive skipped acceptance count is invalid");let t={result:e.result,freshness:e.freshness,contractHash:Ht(e.contractHash,"Native archive contract hash"),acceptanceHash:Ht(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:Ht(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:Ht(e.reportHash,"Native archive report hash"),envelopeHash:Ht(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:Ht(e.partialAllowanceHash,"Native archive partial allowance hash"),skippedAcceptanceCount:e.skippedAcceptanceCount};if((e.freshness==="complete"||e.freshness==="partial")&&[t.contractHash,t.acceptanceHash,t.implementationScopeHash,t.reportHash,t.envelopeHash].some(i=>i===null))throw new Error("Fresh Native archive evidence requires every bound content hash");if(e.freshness==="partial"&&t.partialAllowanceHash===null||e.freshness==="complete"&&t.partialAllowanceHash!==null)throw new Error("Native archive partial evidence allowance state is invalid");return t}function TI(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(r=>{if(typeof r!="string"||!CI.test(r))throw new Error(`Native archive preflight finding code is invalid: ${String(r)}`);return r}),i=[...new Set(t)].sort(_s);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function jI(e){let t=[];e.phase!=="archive"&&t.push("archive-phase-required"),e.archived&&t.push("change-already-archived"),e.pendingJournal&&t.push("pending-journal"),e.targetExists&&t.push("archive-target-exists"),e.evidence.result!=="pass"&&t.push("verification-not-passed"),e.evidence.freshness==="missing"&&t.push("verification-evidence-missing"),e.evidence.freshness==="invalid"&&t.push("verification-evidence-invalid"),e.evidence.freshness==="stale"&&t.push("verification-evidence-stale"),e.evidence.skippedAcceptanceCount>0&&t.push("verification-acceptance-skipped");for(let i of e.specs)i.actualBaseHash!==i.expectedBaseHash&&t.push("spec-base-conflict");return[...new Set(t)].sort(_s)}function jw(e){if(!Tw.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(_I).sort((l,u)=>_s(l.capability,u.capability));if(new Set(t.map(l=>l.capability)).size!==t.length)throw new Error("Native archive preflight contains duplicate capabilities");let i=t.map(l=>({...l,operationHash:H(SI,l)})),r=II(e.evidence),n=AI(e.workspace),a=[...new Set([...TI(e.findingCodes??[]),...jI({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:r})])].sort(_s),o=RI(e.revision),s=PI(e.targetRef,"Native archive target");if(e.archiveConfirmation!=="automatic"&&e.archiveConfirmation!=="required")throw new Error("Native archive confirmation must be automatic or required");let c={stateSchema:e.stateSchema,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetRef:s,targetExists:e.targetExists,operations:i,evidence:r,workspace:n,findingCodes:a};return{schema:bI,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:r.freshness,operationCount:i.length,operations:i,workspace:n,findingCodes:a,preflightHash:H(kI,c)}}import{createHash as $I}from"node:crypto";import $w from"node:path";var OI="comet.native.conflict-radar.v1",xe=Object.freeze({maxChanges:32,maxSpecsPerChange:64,maxArtifactsPerChange:128,maxTotalSpecs:512,maxTotalArtifacts:1024,maxSignalsPerRelationship:8,maxRelationships:256,maxSerializedBytes:64*1024,maxNameBytes:128,maxCapabilityBytes:128,maxArtifactPathBytes:512}),HI="comet.native.conflict-radar.v1",DI="comet.native.conflict-radar-signals.v1",BI=/^[a-f0-9]{64}$/u,Dw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,LI=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),VI=new Set(["capability","operation","baseHash"]),FI=new Set(["path","kind"]);function Pr(e,t){return e<t?-1:e>t?1:0}function bd(e){return Buffer.byteLength(e,"utf8")}function kd(e,t,i){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${i} must be an object`);let r=e,n=Object.keys(r).filter(a=>!t.has(a));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);return r}function Sd(e,t,i){if(typeof e!="string"||e.length===0||e!==e.trim())throw new Error(`${t} must be a non-empty trimmed string`);if(bd(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function qI(e,t){let i=Sd(e,t,xe.maxArtifactPathBytes),r=$w.posix.normalize(i);if(i.includes("\\")||Array.from(i).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(i)||$w.posix.isAbsolute(r)||i.split("/").includes("..")||r!==i||r==="."||i.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return i}function Bw(e,t){if(typeof e!="string"||!BI.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function MI(e,t){let i=kd(e,VI,t),r=Sd(i.capability,`${t} capability`,xe.maxCapabilityBytes);if(!Dw.test(r))throw new Error(`${t} capability is invalid`);if(i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`${t} operation is invalid`);let n=i.baseHash===null?null:Bw(i.baseHash,`${t} canonical base hash`);if(i.operation==="create"&&n!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(i.operation!=="create"&&n===null)throw new Error(`${t} ${i.operation} operation requires a canonical base hash`);return{capability:r,operation:i.operation,baseHash:n}}function WI(e,t){let i=kd(e,FI,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:qI(i.path,`${t} path`),kind:i.kind}}function zI(e,t){let i=kd(e,LI,`Conflict radar change ${t}`),r=Sd(i.name,`Conflict radar change ${t} name`,xe.maxNameBytes);if(!Dw.test(r))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(i.revision)||i.revision<1)throw new Error(`Conflict radar change ${r} revision must be a positive safe integer`);if(!Array.isArray(i.specs))throw new Error(`Conflict radar change ${r} specs must be an array`);if(i.specs.length>xe.maxSpecsPerChange)throw new Error(`Conflict radar change ${r} exceeds the spec budget`);if(!Array.isArray(i.declaredArtifacts))throw new Error(`Conflict radar change ${r} declared artifacts must be an array`);if(i.declaredArtifacts.length>xe.maxArtifactsPerChange)throw new Error(`Conflict radar change ${r} exceeds the declared artifact budget`);let n=i.specs.map((c,l)=>MI(c,`Conflict radar change ${r} spec ${l}`)).sort((c,l)=>Pr(c.capability,l.capability));if(new Set(n.map(c=>c.capability)).size!==n.length)throw new Error(`Conflict radar change ${r} has duplicate capabilities`);let a=i.declaredArtifacts.map((c,l)=>WI(c,`Conflict radar change ${r} artifact ${l}`)).sort((c,l)=>Pr(c.path,l.path)||Pr(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${r} has duplicate or conflicting artifact paths`);let s=i.workspaceIdentityHash===void 0||i.workspaceIdentityHash===null?null:Bw(i.workspaceIdentityHash,`Conflict radar change ${r} workspace identity hash`);return{name:r,revision:i.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function JI(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>xe.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(zI).sort((n,a)=>Pr(n.name,a.name));if(new Set(t.map(n=>n.name)).size!==t.length)throw new Error("Native conflict radar contains duplicate change names");if(t.reduce((n,a)=>n+a.specs.length,0)>xe.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>xe.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function GI(e,t){let i=e.baseHash!==null&&e.baseHash===t.baseHash;return{kind:"capability",certainty:e.operation==="create"||t.operation==="create"||i?"definite-conflict":"possible-overlap",capability:e.capability,leftOperation:e.operation,rightOperation:t.operation,leftBaseHash:e.baseHash,rightBaseHash:t.baseHash}}function UI(e,t){let i=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),r=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),n=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!i&&!r&&!n?null:{kind:"artifact",certainty:n?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function KI(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function YI(e,t){let i=[],r=$I("sha256").update(`${DI}
174
- [`),n=0,a=!1,o=l=>{n>0&&r.update(","),r.update(Nn(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),i.length<xe.maxSignalsPerRelationship&&i.push(l)},s=new Map(t.specs.map(l=>[l.capability,l]));for(let l of e.specs){let u=s.get(l.capability);u&&o(GI(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=UI(l,u);d&&o(d)}let c=a?"definite-conflict":n>0?"possible-overlap":"disjoint";return r.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:KI(e,t),signalCount:n,signalHash:r.digest("hex"),signals:i,signalsTruncated:i.length!==n}}function Ow(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function XI(e,t){return Ow(e.classification)-Ow(t.classification)||Pr(e.left,t.left)||Pr(e.right,t.right)}function Hw(e,t,i,r){let n={definiteConflict:t.filter(({classification:a})=>a==="definite-conflict").length,possibleOverlap:t.filter(({classification:a})=>a==="possible-overlap").length,disjoint:t.filter(({classification:a})=>a==="disjoint").length};return{schema:OI,workspaceIdentityAdvisoryOnly:!0,changeCount:e.length,relationshipCount:t.length,counts:n,relationships:i,relationshipsTruncated:i.length!==t.length,omittedRelationshipCount:t.length-i.length,radarHash:r}}function Lw(e){let t=JI(e),i=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)i.push(YI(t[s],t[c]));i.sort(XI);let r=i.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=H(HI,{changes:t,relationships:r}),a=i.slice(0,xe.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=Hw(t,i,a,n);for(;a.length>0&&bd(JSON.stringify(o))>xe.maxSerializedBytes;)a=a.slice(0,-1),o=Hw(t,i,a,n);if(bd(JSON.stringify(o))>xe.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as _T}from"node:crypto";import{promises as ct}from"node:fs";import bt from"node:path";import Vw from"node:path";var Fw="comet.native.check-receipt.v1",QI="comet.native.check-receipt.v1",Rr="scoped-text-safety",Ed=1,Pe=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),ZI=/^[a-f0-9]{64}$/u,eT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,tT="comet.native.checker-policy.v1",iT="comet.native.check-input.v1",rT=2048,qw=H(tT,{policy:Rr,version:Ed,limits:Pe,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),nT=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),Mw=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],zw=["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"],aT=new Set(zw);function fi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function pi(e,t,i,r=[]){let n=new Set([...t,...r]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${i} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${i} is missing field(s): ${o.join(", ")}`)}function Dt(e,t){if(typeof e!="string"||!ZI.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Oe(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Jw(e,t){let i=Oe(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function Ww(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(!Number.isFinite(i.getTime())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function oT(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>rT||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a bounded normalized project-relative path`);let i=Vw.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||Vw.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function sT(e){let t=fi(e,"Native check receipt checker");pi(t,["policy","version","hash","limits"],"Native check receipt checker");let i=fi(t.limits,"Native check receipt limits");if(pi(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==Rr||t.version!==Ed||t.hash!==qw||i.maxFiles!==Pe.maxFiles||i.maxFileBytes!==Pe.maxFileBytes||i.maxTotalBytes!==Pe.maxTotalBytes||i.maxIssues!==Pe.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:Rr,version:Ed,hash:qw,limits:{...Pe}}}function cT(e){let t=fi(e,"Native check receipt contract");return pi(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:Dt(t.expectedHash,"Native check expected contract hash"),beforeHash:Dt(t.beforeHash,"Native check before contract hash"),afterHash:Dt(t.afterHash,"Native check after contract hash")}}function lT(e){let t=fi(e,"Native check receipt implementation");return pi(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:Dt(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:Dt(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:Dt(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:Dt(t.afterSnapshotHash,"Native check after snapshot hash")}}function uT(e,t){let i=fi(e,`Native check batch ${t}`);pi(i,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let r={filesSelected:Oe(i.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:Oe(i.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:Oe(i.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:Oe(i.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:Oe(i.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:Oe(i.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(r.filesSelected>Pe.maxFiles||r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.bytesScanned>Pe.maxTotalBytes||r.recordedIssueCount>r.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return r}function dT(e){let t=fi(e,"Native check receipt counts");pi(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let i={filesSelected:Oe(t.filesSelected,"Native check filesSelected"),filesScanned:Oe(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:Oe(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:Oe(t.bytesScanned,"Native check bytesScanned"),issueCount:Oe(t.issueCount,"Native check issueCount"),recordedIssueCount:Oe(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(uT):(()=>{throw new Error("Native check receipt batches must be an array")})()}},r=i.batches;if(r!==void 0){if(r.length===0)throw new Error("Native check receipt batches must not be empty");let n=r.reduce((a,o)=>({filesSelected:a.filesSelected+o.filesSelected,filesScanned:a.filesScanned+o.filesScanned,binaryFilesSkipped:a.binaryFilesSkipped+o.binaryFilesSkipped,bytesScanned:a.bytesScanned+o.bytesScanned,issueCount:a.issueCount+o.issueCount,recordedIssueCount:a.recordedIssueCount+o.recordedIssueCount}),{filesSelected:0,filesScanned:0,binaryFilesSkipped:0,bytesScanned:0,issueCount:0,recordedIssueCount:0});if(JSON.stringify(n)!==JSON.stringify({...i,batches:void 0}))throw new Error("Native check receipt batch totals are inconsistent")}if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>Pe.maxIssues||r===void 0&&(i.filesScanned+i.binaryFilesSkipped>Pe.maxFiles||i.bytesScanned>Pe.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return i}function fT(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||Mw.indexOf(e.kind)-Mw.indexOf(t.kind)}function pT(e){if(!Array.isArray(e)||e.length>Pe.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((r,n)=>{let a=fi(r,`Native check issue ${n}`);if(pi(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!nT.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:oT(a.path,`Native check issue ${n} path`),line:Jw(a.line,`Native check issue ${n} line`),kind:a.kind}}),i=[...t].sort(fT);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function hT(e){if(!Array.isArray(e)||e.some(r=>typeof r!="string"||!aT.has(r)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=zw.filter(r=>t.includes(r));if(new Set(t).size!==t.length||JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function mT(e){return H(iT,e)}function Gw(e){let t=fi(e,"Native check receipt");if(pi(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==Fw)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!eT.test(t.change))throw new Error("Native check receipt change name is invalid");let i=Jw(t.sourceRevision,"Native check source revision"),r=sT(t.checker),n=cT(t.contract),a=lT(t.implementation),o=mT({change:t.change,sourceRevision:i,checkerHash:r.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(Dt(t.inputHash,"Native check input hash")!==o)throw new Error("Native check receipt input hash mismatch");if(t.status!=="passed"&&t.status!=="failed")throw new Error("Native check receipt status is invalid");let s=Ww(t.startedAt,"Native check receipt startedAt"),c=Ww(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=dT(t.counts),u=pT(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=hT(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let f=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==f)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.batches===void 0&&l.filesSelected>Pe.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.batches===void 0&&l.filesSelected>Pe.maxFiles&&!u.some(h=>h.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let p={schema:Fw,change:t.change,sourceRevision:i,checker:r,inputHash:o,status:t.status,startedAt:s,endedAt:c,contract:n,implementation:a,counts:l,issues:u,issuesTruncated:t.issuesTruncated,stale:t.stale,staleReasons:d},v=Dt(t.receiptHash,"Native check receipt content hash");if(H(QI,p)!==v)throw new Error("Native check receipt content hash mismatch");return{...p,receiptHash:v}}var xd="comet.native.verification-receipt.v3",vT=xd,gT="comet.native.declared-artifacts.v1",wT=/^[a-f0-9]{64}$/u,yT=/^acceptance-[a-f0-9]{64}$/u,NT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,bT=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,kT=4096,ST=256,ET=1024;function Ar(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function hi(e,t,i){let r=Object.keys(e).sort(),n=[...t].sort();if(r.length!==n.length||r.some((a,o)=>a!==n[o]))throw new Error(`${i} fields are invalid`)}function Bt(e,t){if(typeof e!="string"||!wT.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function st(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=We(e).trim();if(!i||i.length>kT||i!==e.trim())throw new Error(`${t} is invalid`);return i}function Cd(e,t){let i=st(e,t),r=new Date(i);if(Number.isNaN(r.getTime())||r.toISOString()!==i)throw new Error(`${t} must be a canonical timestamp`);return i}function Qn(e,t,i=st,r=!1,n=ST){if(!Array.isArray(e)||e.length>n||!r&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>i(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function CT(e,t){if(typeof e!="string"||!yT.test(e))throw new Error(`${t} is invalid`);return e}function xT(e){let t=Ar(e,"Native verification receipt bindings");if(hi(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!NT.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:Bt(t.contractHash,"Native verification receipt contract hash"),scopeHash:Bt(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:Bt(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:Bt(t.artifactHash,"Native verification receipt artifact hash")}}function PT(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=bT.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function RT(e,t,i,r){let n=Ar(t,`Native ${e} evidence`);if(e==="automated-check"){if(hi(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=Cd(n.startedAt,"Native automated-check start time"),o=Cd(n.endedAt,"Native automated-check end time");if(Date.parse(o)<Date.parse(a))throw new Error("Native automated-check time range is invalid");if(i==="passed"&&n.exitCode!==0||i==="failed"&&n.exitCode===0||i==="passed"&&(n.timedOut||n.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=Ar(n.worktree,"Native automated-check worktree");if(hi(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=Ar(n.afterFence,"Native automated-check after fence");if(hi(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(i==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:st(n.executable,"Native automated-check executable"),args:Qn(n.args,"Native automated-check arguments",st,!0),cwd:st(n.cwd,"Native automated-check cwd"),exitCode:n.exitCode,signal:n.signal,timedOut:n.timedOut,timeoutMs:n.timeoutMs,startedAt:a,endedAt:o,worktree:{provider:s.provider,root:st(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:Bt(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:Bt(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:Bt(n.outputHash,"Native automated-check output hash"),outputSummary:st(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){hi(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=PT(n.checkReceiptRef);if(Bt(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:Qn(n.subjects,"Native static inspection subjects",st,r==="required-check"),rule:st(n.rule,"Native static inspection rule"),resultSummary:st(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return hi(n,["steps","observations"],"Native manual-evidence evidence"),{steps:Qn(n.steps,"Native manual evidence steps"),observations:Qn(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function AT(e){let t=Ar(e,"Native verification receipt");if(hi(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence"],"Native verification receipt input"),!["automated-check","static-inspection","manual-evidence"].includes(t.kind)||t.role!=="required-check"&&t.role!=="acceptance-evidence"||!["passed","failed","skipped","blocked"].includes(t.status))throw new Error("Native verification receipt kind or status is invalid");let i=t.kind,r=t.role,n=t.status,a=st(t.actor,"Native verification receipt actor"),o=Qn(t.acceptanceIds,"Native receipt acceptance IDs",CT,r==="required-check",ET).sort();if(r==="required-check"&&o.length!==0||r==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(r==="required-check"&&i!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:xd,kind:i,role:r,status:n,bindings:xT(t.bindings),acceptanceIds:o,actor:a,issuedAt:Cd(t.issuedAt,"Native verification receipt issue time"),evidence:RT(i,t.evidence,n,r)};if(r==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==Rr||s.actor!==`native-runtime:${Rr}`))throw new Error("Native required check policy identity is invalid");return s}function Uw(e){let t=Ar(e,"Native verification receipt");if(hi(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==xd)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...r}=t,n=AT(r),a=Bt(t.receiptHash,"Native verification receipt hash");if(H(vT,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function Pd(e){return H(gT,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}var Qw=/^[a-f0-9]{64}$/u,_r=Hi,rM=3*_r;function Rd(e,t){let i=bt.relative(e,t);return i===""||!bt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${bt.sep}`)}function IT(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Is(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return _e(i,r)?q(i,r):q(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Kw(e){let t=await ct.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await ct.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function TT(e,t){let i=bt.resolve(e),r=bt.resolve(t);if(!Rd(i,r))throw new Error("Native evidence path is outside its change");let n=[await Kw(i)],a=i;for(let o of bt.relative(i,r).split(bt.sep).filter(Boolean)){a=bt.join(a,o);let s=await Kw(a);if(!Rd(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function Yw(e){for(let t of e){let i=await ct.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!IT(t,i)||await ct.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function jT(e,t,i={}){let r=await TT(t,bt.dirname(e));await i.afterParentChainCaptured?.();let n=await ct.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await ct.realpath(e);if(!Rd(r[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await ct.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),ct.lstat(e),ct.realpath(e)]);if(await Yw(r),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!Is(s,n)||!Is(s,c))throw new Error("Native evidence document changed while opening");if(s.size>_r)throw new Error(`Native evidence document exceeds ${_r} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let m=_r+1-d,S=await o.read(f,0,Math.min(f.length,m),null);if(S.bytesRead===0)break;if(d+=S.bytesRead,d>_r)throw new Error(`Native evidence document exceeds ${_r} bytes`);u.push(Buffer.from(f.subarray(0,S.bytesRead)))}await i.beforeFinalCheck?.();let[p,v,h]=await Promise.all([o.stat(),ct.lstat(e),ct.realpath(e)]);if(await Yw(r),!v.isFile()||v.isSymbolicLink()||h!==a||!Is(s,p)||!Is(s,v))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function Zw(e,t){if(!Qw.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}async function $T(e,t,i,r,n){if(!Qw.test(i))throw new Error("Native report evidence hash is invalid");let a=await Di({paths:e,name:t,kind:"reports",hash:i,hooks:r,changeDir:n});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==i||typeof o.content!="string"||_T("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==i)throw new Error("Native report evidence does not match its hash");return o.content}function Ir(e,t){let i=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!i||i[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return i[2]}function OT(e,t,i,r,n){let a=Zw(i,r);return n?bt.join(n,...a.split("/")):ri(U(e,t),a)}async function Di(e){let t=OT(e.paths,e.name,e.kind,e.hash,e.changeDir),i=e.changeDir??ue(e.paths,t);return await z(i,t),jT(t,i,e.hooks)}function Xw(e,t){return ys(e,t)}function HT(e,t){let i=Ns(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function DT(e,t,i){let r=ew(e);if(r.change!==t||r.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return r}function BT(e,t,i){let r=ed(e);if(r.change!==t||r.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return r}async function LT(e,t,i,r=!1,n){let a=await Ts(e,t,i.implementationScopeRef,void 0,n);if(r&&await $T(e,t,i.reportHash,void 0,n),a.scopeHash!==i.implementationScopeHash||a.contractHash!==i.contractHash||(a.complete?"complete":"partial")!==i.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(i.partialAllowanceRef===null)return;let o=await ey(e,t,i.partialAllowanceRef,void 0,n);if(o.allowanceHash!==i.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=i.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function Zn(e,t,i,r,n){let a=Ir(i,"scopes"),o=HT(await Di({paths:e,name:t,kind:"scopes",hash:a,hooks:r,changeDir:n}),a),s=Ir(o.baselineProjectionRef,"snapshots"),c=Ir(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([Di({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>Xw(d,s)),Di({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>Xw(d,c))]);return Gg({baseline:l,current:u,scope:o})}async function Ts(e,t,i,r,n){return(await Zn(e,t,i,r,n)).scope}async function ey(e,t,i,r,n){let a=Ir(i,"allowances");return DT(await Di({paths:e,name:t,kind:"allowances",hash:a,hooks:r,changeDir:n}),t,a)}async function ea(e,t,i,r,n){let a=Ir(i,"receipts"),o=Uw(await Di({paths:e,name:t,kind:"receipts",hash:a,hooks:r,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function Tr(e,t,i,r,n){let a=Ir(i,"verifications"),o=BT(await Di({paths:e,name:t,kind:"verifications",hash:a,hooks:r,changeDir:n}),t,a);return await LT(e,t,o,!1,n),o}var VT=4096;async function FT(e,t=xe.maxChanges){try{let i=await xn({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:t});return await i.verify(),i.entries}catch(i){if(i.code==="ENOENT")return[];throw i}}async function ty(e,t){let i=await gt(e,t),[r,n]=await Promise.all([i.implementation_scope?Ts(e,t,i.implementation_scope):null,jt(e,t).catch(()=>null)]);return{name:i.name,revision:i.revision,specs:i.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:r?.declaredArtifacts??[],workspaceIdentityHash:n?.nativeRootId??null}}async function js(e,t,i={}){let n=(await FT(e,VT)).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 ty(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await ty(e,c).catch(d=>{if(i.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=Lw([a,l]).relationships[0];u.classification==="definite-conflict"&&(o+=1),u.classification==="possible-overlap"&&(s+=1)}return{definiteConflictCount:o,possibleOverlapCount:s,findingCodes:[...o>0?["native-change-conflict"]:[],...s>0?["native-change-overlap"]:[]]}}import{execFile as QT}from"node:child_process";import{promisify as ZT}from"node:util";import{constants as Ad,promises as Je}from"node:fs";import jr from"node:path";var MT=/^[a-f0-9]{64}$/u,WT=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,ta=512*1024;function zT(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function $s(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return _e(i,r)?q(i,r):q(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function JT(e,t){let i=jr.resolve(e),r=jr.resolve(t);if(!V(i,r))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=i;for(let o of["",...jr.relative(i,r).split(jr.sep).filter(Boolean)]){o&&(a=jr.join(a,o));let s=await Je.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await Je.realpath(a);if(n.length>0&&!V(n[0].realPath,c))throw new Error("Native check receipt parent resolves outside the Native root");n.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs})}return n}async function ry(e){for(let t of e){let i=await Je.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!zT(t,i)||await Je.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function GT(e){if(!MT.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function UT(e){let t=WT.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function KT(e,t,i){return ri(U(e,t),GT(i))}async function YT(e,t,i){let r=await JT(i,jr.dirname(e)),n=await Je.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(n.size>ta)throw new Error(`Native check receipt exceeds ${ta} bytes`);let[a,o]=await Promise.all([Je.realpath(t),Je.realpath(e)]);if(!V(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":Ad.O_RDONLY|Ad.O_NOFOLLOW|Ad.O_NONBLOCK,c=await Je.open(e,s).catch(l=>{throw l.code==="ELOOP"||l.code==="ENXIO"?new Error("Native check receipt became unsafe while opening"):l});try{let[l,u,d]=await Promise.all([c.stat(),Je.lstat(e),Je.realpath(e)]);if(await ry(r),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!$s(n,l)||!$s(l,u))throw new Error("Native check receipt changed while opening");let f=[],p=0,v=Buffer.allocUnsafe(16*1024);for(;;){let y=ta+1-p,k=await c.read(v,0,Math.min(v.length,y),null);if(k.bytesRead===0)break;if(p+=k.bytesRead,p>ta)throw new Error(`Native check receipt exceeds ${ta} bytes`);f.push(Buffer.from(v.subarray(0,k.bytesRead)))}let[h,m,S]=await Promise.all([c.stat(),Je.lstat(e),Je.realpath(e)]);if(await ry(r),!m.isFile()||m.isSymbolicLink()||S!==o||!V(a,S)||!$s(l,h)||!$s(l,m))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,p).toString("utf8"))}finally{await c.close()}}async function ny(e,t,i){let r=UT(i),n=U(e,t),a=KT(e,t,r),o=ue(e,a);await z(o,a);let s=Gw(await YT(a,n,o));if(s.change!==t||s.receiptHash!==r)throw new Error("Native check receipt ref/hash/change mismatch");return s}var ia=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var YM=64*1024;var XM=3600*1e3;var QM=ZT(QT);var ej=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function ay(e,t){let i=[];for(let r of ej){let n=e.bindings[r],a=t[r];n!==a&&i.push(`${r}: expected ${JSON.stringify(a)}, got ${JSON.stringify(n)}`)}return{ok:i.length===0,mismatches:i}}async function oy(e){if(e.receipt.kind!=="static-inspection")return null;let t=await ny(e.paths,e.state.name,e.receipt.evidence.checkReceiptRef);if(t.receiptHash!==e.receipt.evidence.checkReceiptHash)throw new Error("Native static receipt dependency hash mismatch");return t}var mi=class extends Error{details;constructor(t){let i=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(r=>`${r.ref}${r.acceptanceId?`[${r.acceptanceId}]`:""} -> ${r.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=t}};function tj(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 ij(e){let t=tj(e.bundle.baseline),i=await fu(e.paths,t,{origin:"explicit",now:e.now});return Yu({baseline:t,current:i,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason,externalDrift:e.bundle.authority.externalDrift}).scope.currentProjectionHash}async function cy(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await Zn(e.paths,e.state.name,e.state.implementation_scope),i=await yr({changeDir:me(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),r=await ij({paths:e.paths,bundle:t,now:e.now}),n=[];return i.contract.contractHash!==t.scope.contractHash&&n.push("verification-contract-stale"),r!==t.scope.currentProjectionHash&&n.push("verification-implementation-stale"),{bundle:t,contract:i.contract,contractHash:i.contract.contractHash,acceptanceHash:i.contract.acceptanceHash,findingCodes:n}}async function ly(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await cy(e),i=[...new Set(t.findingCodes)].sort();return{freshness:i.length===0?"fresh":"stale",findingCodes:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"]}}}async function rj(e){let t=await re({root:me(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:km(t.text)}}function nj(e){let{receipt:t,implementationScope:i}=e,r=[],n=Ku({baseline:i.baseline,current:i.current,declaredArtifacts:i.scope.declaredArtifacts}).filter(o=>o.attributedTo.length>0&&o.after!==null),a=n.reduce((o,s)=>o+s.after.size,0);return(t.stale||t.sourceRevision!==e.sourceRevision||t.contract.expectedHash!==e.contractHash||t.contract.beforeHash!==e.contractHash||t.contract.afterHash!==e.contractHash||t.implementation.scopeHash!==i.scope.scopeHash||t.implementation.expectedSnapshotHash!==i.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==i.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==i.scope.currentProjectionHash||t.counts.filesSelected!==n.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==n.length||t.counts.bytesScanned!==a))&&r.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&r.push("verification-receipt-outcome-mismatch"),r}function aj(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:Pd(e.implementationScope.scope.declaredArtifacts)}}async function sy(e){let t=await ea(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let r=ay(t,e.expectedBindings);if(i.push(...r.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&i.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),i.length>0)throw new mi([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:i}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let n=await oy({paths:e.paths,state:e.state,receipt:t});if(n){let a=nj({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 oj(e){let t=aj({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let r of e.requiredReceiptRefs){let n=await sy({...e,ref:r,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof mi)return i.push(...a.details),null;throw a});if(n!==null&&n.kind!=="static-inspection")throw new Error("Native required-check evidence must be a static-inspection receipt")}for(let r of e.trace.entries)if(r.status!=="missing")for(let n of r.evidenceRefs){let a=await sy({...e,result:r.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:r.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof mi)return i.push(...o.details),null;throw o});if(a!==null){if(a.kind!=="automated-check"&&a.kind!=="manual-evidence")throw new Error("Native acceptance evidence must be automated-check or manual-evidence");if(r.status==="failed"&&a.status==="passed")throw new Error("Native failed acceptance evidence must reference a non-passing receipt")}}if(i.length>0)throw new mi(i)}function _d(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function Id(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:_d(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([cy(e),Tr(e.paths,e.state.name,e.state.verification_evidence)]);if(i.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:_d(e.state.verification_result,"stale"),envelope:null};let r=await rj({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),n=[...t.findingCodes];(r.hash!==i.reportHash||r.ref!==i.reportRef)&&n.push("verification-report-stale"),(i.result!==e.state.verification_result||i.implementationScopeRef!==e.state.implementation_scope||i.partialAllowanceRef!==e.state.partial_allowance||i.sourceRevision>=e.state.revision||i.contractHash!==t.bundle.scope.contractHash||i.acceptanceCriteriaHash!==t.acceptanceHash)&&n.push("verification-state-mismatch");try{await oj({paths:e.paths,state:e.state,result:i.result,trace:i.acceptanceTrace,requiredReceiptRefs:i.requiredReceiptRefs,contractHash:i.contractHash,implementationScope:t.bundle,sourceRevision:i.sourceRevision})}catch{n.push("verification-receipt-invalid")}let a=[...new Set(n)].sort(),o=a.length>0?"stale":i.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:i.contractHash,acceptanceHash:i.acceptanceCriteriaHash,implementationScopeHash:i.implementationScopeHash,reportHash:i.reportHash,envelopeHash:i.envelopeHash,partialAllowanceHash:i.partialAllowanceHash,skippedAcceptanceCount:i.acceptanceTrace.skipped},envelope:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:_d(e.state.verification_result,"invalid"),envelope:null}}}function cj(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function dy(e){try{return await sj.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function lj(e,t){try{return(await re({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function uj(e,t,i){let r=as(e,i.capability);if(!V(e.nativeRoot,r))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let n=uy.relative(e.nativeRoot,r).replaceAll("\\","/"),a=await lj(e.nativeRoot,n),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await re({root:me(e,t),ref:i.source})).hash}return{capability:i.capability,operation:i.operation,expectedBaseHash:i.operation==="create"?null:i.base_hash,actualBaseHash:a,proposedHash:o}}async function dj(e,t){return dy(ud(e,t))}async function Td(e){let t=e.now??new Date,i=await gt(e.paths,e.name),r=await jt(e.paths,e.name),n=await Ie(e.paths.projectRoot),a=cj(i.name,t),o=uy.resolve(e.paths.nativeRoot,...a.split("/"));if(!V(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,f,p]=await Promise.all([Promise.all(i.spec_changes.map(v=>uj(e.paths,i.name,v))),Id({paths:e.paths,state:i,now:t}),js(e.paths,i.name),ns(e.paths,i.name),Lv(e.paths,i.name),dj(e.paths,i.name),dy(o)]);return jw({change:i.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:i.schema,revision:i.revision,phase:i.phase,archived:i.archived,pendingJournal:u||d||f,targetRef:a,targetExists:p,specs:s,evidence:c.evidence,workspace:r?.schema==="comet.native.workspace.v3"?{schema:r.schema,isolation:r.isolation,changeBranch:r.changeBranch,targetBranch:r.targetBranch,finish:r.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}async function fj(e,t){let i=U(e,t.name),r=await gr(i);if(!r||!t.run_id||r.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let n=await Xo(i,r.checkpointRef);if(!n||n.runId!==r.runId||n.stateVersion!==r.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await Ii(i,r.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:r.runId}}async function pj(e,t){let i=await fj(e,t);return{committed:i,latest:cw(i),history:sw(i)}}async function fy(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let r=await pj(e,t),n=r.latest;if(!n)return null;let a=r.history.filter(c=>c.kind==="failure"),o=a.length>=i,s=n.disposition==="hard-stop"&&!o?"continue":n.disposition;return{disposition:o?"hard-stop":s,signatureHash:n.signatureHash,overrideRecorded:r.history.some(c=>c.kind==="override"&&c.signatureHash===n.signatureHash),failedAcceptanceIds:[...n.failedAcceptanceIds],failedCheckIds:[...n.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:i,remainingVerifyFailures:Math.max(0,i-a.length)}}var o2=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function mj(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function vj(e){return(await Cg(e))?.change??null}function gj(e,t,i=!1,r){return xs({state:e,archiveReady:t,evidenceRetreat:i}).command}async function wj(e,t){let i=me(e,t.name),r=[...(await Cu(i,t.brief)).findings,...(await zv(e,t)).findings,...await Pg(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await zo(e,t.name);if(n===null)r.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await fv(e,n);a.complete||r.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${a.omittedCount} omitted entries); resolve the omissions before advancing`})}}catch(n){r.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${n.message}`})}if(t.phase==="build")try{let n=await yr({changeDir:i,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==n.contract.contractHash&&r.push({code:"contract-changed-after-approval",message:t.approval===null||t.approved_contract_hash===null||t.approved_contract_hash===void 0?"Native approval is not bound to a contract hash; re-confirm the current contract":"Native contract changed after approval; re-confirm the current contract"})}catch(n){r.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${n.message}`})}try{await ww(e,t.name)&&r.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(n){r.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${n.message}`})}return t.verification_report?r.push(...(await xu(i,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&r.push({code:"verification-report-missing",message:"Native change has no verification report"}),r}async function py(e,t,i){let r=await vj(e)===t,n=await Dl(e,t),a=await _v(e,t),o;try{let w=await Su(e,t);if(w.status==="migration-required"&&w.state)return{name:t,phase:w.state.phase,revision:"revision"in w.state?w.state.revision:null,approval:w.state.approval,verificationResult:w.state.verification_result,specChanges:w.state.spec_changes.length,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["migration-required"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:w.schema,migrationRequired:!0,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message};if(w.status!=="current"||!w.state)return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["runtime-incompatible"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:w.schema,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message??`Native change ${t} is incompatible`};o=w.state}catch(w){return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["change-invalid"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,error:w.message}}if(n.status!=="available"){let w={code:n.status==="missing"?"runtime-missing":"runtime-storage-invalid",message:n.status==="missing"?`Native Runtime is missing; continue ${o.name} to rebuild local execution state`:n.message??"Native Runtime storage is invalid",path:n.path},C=md({paths:e,state:o,findings:[w]}),$=xs({state:o,findings:C});return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:$.command,archiveReady:!1,inspection:{freshness:"stale",codes:[w.code],reasonCount:1,codesTruncated:!1},findingSummary:vd(C),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:$,workspace:a,runtime:n,...i?.details?{findings:C}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:w.message}:{}}}let s=await _w({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await fy(e,o,i?.maxVerifyFailures??5),c&&(c.disposition==="manual-stop"||c.disposition==="hard-stop")){let w=c.disposition==="hard-stop"?"repair-iteration-limit":c.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";l.push({code:w,message:`Native repair is stopped at failure signature: ${c.signatureHash}`})}}catch{l.push({code:"trajectory-invalid",message:"Native repair history could not be reconstructed safely"})}let u;if(i?.details&&(o.phase==="build"||o.phase==="verify"||o.phase==="archive"))try{let w=await yr({changeDir:me(e,o.name),briefRef:o.brief,specChanges:o.spec_changes}),C=new Map;if(o.phase==="build"&&o.verification_result==="fail"&&o.verification_evidence){let pe=await Tr(e,o.name,o.verification_evidence);for(let Q of pe.acceptanceTrace.entries)C.set(Q.acceptanceId,Q.status==="failed"?"failed":Q.status==="missing"?"missing":"satisfied")}let $=ym({criteria:w.contract.acceptance,acceptanceHash:w.contract.acceptanceHash,verificationStatuses:C,failedCheckIds:c?.failedCheckIds??[],...i.acceptanceCursor?{cursor:i.acceptanceCursor}:{}}),T=$.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",$.nextCursor,"--project-root",e.projectRoot]:null;u={...$,...T?{nextPageCommand:mj(T),nextPageArgs:T}:{}}}catch(w){if(i.acceptanceCursor)throw w;u=void 0}let d=[];if(i?.includeConflictFindings!==!1)try{let w=await js(e,o.name,{tolerateInvalidSiblings:!0});d.push(...w.findingCodes.map(C=>({code:C,message:`Native change overlap is visible in the current root: ${C}`})))}catch{d.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let f=[];try{let w=await jt(e,o.name);if(w)if(w.schema==="comet.native.workspace.v3"){let C=await jn({paths:e,identity:w});C.state==="drifted"&&C.code&&f.push({code:C.code,message:C.message??"Native workspace binding is no longer valid"})}else{let C=await es({paths:e,identity:w});f.push(...C.findingCodes.map($=>({code:$,message:`Native workspace advisory changed: ${$} (${C.driftComponents.join(", ")||"no-component"})`})))}}catch{f.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let p=[],v=!1;if(o.phase==="verify"){let w=await ly({paths:e,state:o});v=w.freshness!=="fresh",p.push(...w.findingCodes.map(C=>({code:C,message:`Native Verify implementation scope is not current: ${C}`})))}let h=null,m=[];if(o.phase==="archive")try{h=await Td({paths:e,name:o.name}),m.push(...h.findingCodes.map(w=>({code:w,message:`Native Archive is blocked: ${w}`})))}catch{m.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let S=[...await wj(e,o),...s.findings,...d,...f,...p,...l,...m].filter((w,C,$)=>$.findIndex(T=>T.code===w.code&&T.path===w.path)===C),y=md({paths:e,state:o,findings:S}),k=y.filter(w=>!wr(w.code)),N=o.phase==="archive"&&h?.ready===!0&&k.length===0,E=v||o.phase==="archive"&&(h?.findingCodes??[]).some(w=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(w)),b=y.some(w=>w.code==="trajectory-tail-incomplete"||w.code==="trajectory-invalid"||w.requiredAction==="return-to-bound-working-directory"||w.requiredAction==="repair-workspace-binding"),x=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",g=y.find(w=>w.severity==="error");return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:b||x?null:gj(o,N,E,i?.clarificationMode),archiveReady:N,inspection:s.inspection,findingSummary:vd(y),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:xs({state:o,findings:y,archiveReady:N,evidenceRetreat:E,clarificationMode:i?.clarificationMode}),workspace:a,runtime:n,repair:c,...i?.details?{...u?{acceptancePage:u}:{},findings:y.slice(0,50),inspectionDetails:s.inspectionDetails,checkpointDetails:s.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:As,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:y.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...g?{error:g.message}:{}}}import jj from"node:path";import{promises as hy}from"node:fs";import yj from"node:path";var Nj=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),bj=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),kj=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task"]),Sj=new Set(["status","summary"]);function Os(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Hs(e,t,i){let r=new Set(Object.keys(e)),n=[...t].filter(o=>!r.has(o)),a=[...r].filter(o=>!t.has(o));return n.length===0&&a.length===0?null:`${i} fields must be exact (missing: ${n.join(", ")||"none"}; unexpected: ${a.join(", ")||"none"})`}function Ej(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((i,r)=>i===t[r])}function Bi(e,t,i){return{status:"incompatible",file:e,snapshot:t,message:i}}function Cj(e,t,i,r){let n=Os(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=Hs(n,Nj,"Native Supervisor overlay");if(a)return a;if(r.stateVersion!==1)return"Native Supervisor overlay stateVersion is not 1";if(r.parent!==t.name)return`Native Supervisor overlay parent ${r.parent} does not match ${t.name}`;let o=Os(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=Hs(o,bj,"Native Supervisor integration");if(s)return s;if(r.integration.headCommit!==r.integration.targetCommit)return"Native Supervisor integration headCommit has advanced beyond targetCommit";if(!Array.isArray(n.history)||n.history.length!==0)return"Native Supervisor overlay history is not empty";let c=Os(n.finalVerification,"Native Supervisor finalVerification");if(!c)return"Native Supervisor finalVerification must be an object";let l=Hs(c,Sj,"Native Supervisor finalVerification");if(l)return l;if(r.finalVerification.status!=="pending"||r.finalVerification.summary!==null)return"Native Supervisor final verification already contains progress";if(!Array.isArray(n.children))return"Native Supervisor children must be an array";if(n.children.length!==i.children.length)return"Native Supervisor child count does not match the legacy children contract";for(let[u,d]of n.children.entries()){let f=Os(d,`Native Supervisor child ${u}`);if(!f)return`Native Supervisor child ${u} must be an object`;let p=Hs(f,kj,`Native Supervisor child ${u}`);if(p)return p;let v=i.children[u];if(f.name!==v.name||f.summary!==v.summary||!Ej(f.dependsOn,v.depends_on))return`Native Supervisor child ${v.name} does not match the legacy children contract`;let h=v.depends_on.length===0?"ready":"pending";if(f.status!==h)return`Native Supervisor child ${v.name} has progressed beyond its initial ${h} status`;if(f.baseCommit!==null||f.candidateCommit!==null||f.verifiedCommit!==null||f.integrationCommit!==null||f.verification!==null||f.blocker!==null||f.projectRoot!==null||f.task!==null)return`Native Supervisor child ${v.name} contains execution progress`;if(!Array.isArray(f.checks)||f.checks.length!==0)return`Native Supervisor child ${v.name} contains integration checks`}return null}async function my(e){let t=us(e.paths,e.state.name),i;try{let c=await hy.lstat(t);if(!c.isFile()||c.isSymbolicLink())return Bi(t,"","Native Supervisor overlay is not a regular file");i=await hy.readFile(t,"utf8")}catch(c){return c.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:Bi(t,"",`Native Supervisor overlay cannot be read: ${c.message}`)}let r;try{r=JSON.parse(i)}catch(c){return Bi(t,i,`Native Supervisor overlay is invalid JSON: ${c.message}`)}let n=yj.join(e.paths.changesDir,e.state.name),a;try{a=await ps({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:c})=>c),policy:"advisory"})}catch(c){return Bi(t,i,`Native children contract cannot be validated: ${c.message}`)}if(!a||a.contract.schema!=="comet.native.children.v1")return{status:"compatible",file:t,message:"The current Native children contract is not legacy children.v1",snapshot:i};let o;try{o=await $i(e.paths,e.state.name)}catch(c){return Bi(t,i,`Native Supervisor overlay is invalid: ${c.message}`)}if(!o)return Bi(t,i,"Native Supervisor overlay disappeared during inspection");let s=Cj(r,e.state,a.contract,o);return s?Bi(t,i,s):{status:"repairable-legacy-overlay",file:t,message:"An exact unstarted v2 Supervisor overlay is stale beside a legacy children.v1 contract",snapshot:i}}function Lt(e,t,i){return e.language==="zh-CN"?i:t}function xj(e,t){let i=r=>({required:!1,message:null,suggestedReply:null,agentInstruction:r});if(e.phase==="shape"&&e.status==="await-user"&&e.loop.next_action==="confirm-shape")return e.language==="zh-CN"?{required:!0,message:"Shape 已整理完成。请确认目标、范围、关键决定、验收标准和非目标是否准确;明确确认后才会进入 Build。",suggestedReply:"确认进入 Build",agentInstruction:"先用自然语言简要展示目标、范围、关键决定、验收标准和非目标,再转述 message 并等待用户明确确认。只有用户明确同意当前完整 Shape 时,才执行 commandAlternatives 中的 confirm-shape;补充或修改要求不算确认。不要展示机器状态或提前运行 --confirmed。"}:{required:!0,message:"Shape is ready. Confirm that the target, scope, key decisions, acceptance criteria, and non-goals are accurate; Build starts only after explicit confirmation.",suggestedReply:"Confirm and enter Build",agentInstruction:"First present a concise natural-language summary of the target, scope, key decisions, acceptance criteria, and non-goals. Then relay message and wait for explicit user confirmation. Run confirm-shape from commandAlternatives only when the user explicitly accepts the complete current Shape; additions or corrections are not confirmation. Do not expose machine state or run --confirmed early."};if(t&&e.phase==="shape"&&e.status==="active")return{required:!0,message:Lt(e,"This Supervisor Change has multiple independent children. Choose one coordination mode before confirming Shape: A) Multi-session coordination (recommended), or B) Single-session progression.","当前 Supervisor Change 包含多个可独立执行的 Child。确认 Shape 前请选择推进方式:A)多会话协作(推荐),或 B)单会话推进。"),suggestedReply:Lt(e,"Reply A or B","回复 A 或 B"),agentInstruction:Lt(e,"Relay the two coordination choices and wait for the user decision. After the user chooses, execute the prepare-shape-confirmation commandArgs with the selected --coordination-mode. Do not combine mode selection with final confirmation; confirmation of the complete Shape is a separate await-user step.","转述这两个推进方式并等待用户选择。用户选择后,使用对应的 --coordination-mode 执行 prepare-shape-confirmation 的完整 commandArgs;不要把推进方式选择和最终确认合并执行,完整 Shape 的确认是后续单独的 await-user 步骤。")};if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready"&&e.loop.next_action!=="await-verifier-result")return i(Lt(e,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result")return i(Lt(e,"Wait only while the dispatched Verifier task is still active. If the task did not start, failed, timed out, ended without a response, or was lost, immediately submit verifier-execution-error. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","仅在已派发的独立验收任务仍在运行时等待。如果任务未启动、执行失败、超时、结束后没有返回结果或已经丢失,立即提交 verifier-execution-error;只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。"));if(e.status==="blocked"&&e.blockers.some(({resolution_action:r})=>r==="retry-verifier"))return e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable")return e.language==="zh-CN"?{required:!0,message:"独立验收当前不可用,但你的代码和已经完成的检查都已安全保留。你可以直接重新尝试独立验收,也可以明确接受只有自动检查的结果。",suggestedReply:"重新尝试独立验收",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户选择。用户要求重试时执行 commandAlternatives 中的 retry-verifier;只有用户明确接受降级结果时才执行 confirm-verifier-unavailable。不要把“继续”视为接受降级结果,也不要要求用户处理文件、进程、服务或回调。"}:{required:!0,message:"Independent verification is currently unavailable, but your code and completed checks are safely preserved. You can retry independent verification directly or explicitly accept the automatic-check-only result.",suggestedReply:"Retry independent verification",agentInstruction:"Relay only message and suggestedReply, then wait for the user choice. If the user asks to retry, run retry-verifier from commandAlternatives; run confirm-verifier-unavailable only when the user explicitly accepts the degraded result. Do not treat “Continue” as accepting the degraded result, and do not ask the user to manage files, processes, services, or callbacks."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="resolve-verifier-blocker")return e.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="await-user"){let n=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",a=n?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。",o=n?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return e.language==="zh-CN"?{required:!0,message:a,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:o,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}return i(Lt(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 Pj(e){let t=e.workspace.change_branch??"<change-branch>",i=e.workspace.target_branch??"<target-branch>";return e.language==="zh-CN"?{required:!0,message:`当前 change 位于 ${t},目标分支为 ${i}。请选择一次工作区收尾方式:A) 保留工作区;B) 本地合并;C) 推送分支;D) 推送并创建 PR;E) 暂不归档。选择 A-D 后 Runtime 会先执行完整 dry-run,再给出唯一的 confirmed 命令;选择 E 将保留当前 change 等待稍后继续。`,suggestedReply:"回复 A、B、C、D 或 E",agentInstruction:"只向用户展示五种收尾方式及实际影响,等待用户选择。选择 A-D 时执行对应 commandAlternatives 中包含 --dry-run --finish 的完整命令;选择 E 时停止,不运行任何 Archive 命令。不要直接运行 --confirmed,也不要自行猜测 finish。"}:{required:!0,message:`This change is on ${t} and targets ${i}. Choose one workspace finish: A) keep the workspace; B) merge locally; C) push the branch; D) push and create a PR; or E) defer Archive. For A-D, Runtime will run a complete dry-run first, then return one confirmed command; E keeps the current change for later.`,suggestedReply:"Reply A, B, C, D, or E",agentInstruction:"Show all five finish choices and their actual effects, then wait. For A-D, execute the matching complete commandAlternative containing --dry-run --finish; for E, stop without running an Archive command. Do not run --confirmed directly or guess a finish mode."}}function Rj(e){return[...[{finish:"keep",name:"keep-workspace",description:["保留当前分支和目录;完成归档提交,不合并、不推送、不创建 PR。","Keep the current branch and directory; create the archive commit without merging, pushing, or creating a PR."]},{finish:"merge",name:"merge-locally",description:["完成归档提交,并把 change 分支本地合并到目标分支;不推送、不创建 PR。","Create the archive commit and merge the change branch locally into the target branch without pushing or creating a PR."]},{finish:"push",name:"push-branch",description:["完成归档提交并推送 change 分支;不合并到目标分支、不创建 PR。","Create the archive commit and push the change branch without merging into the target branch or creating a PR."]},{finish:"pull-request",name:"push-pull-request",description:["完成归档提交、推送 change 分支,并以目标分支为基础创建 PR。","Create the archive commit, push the change branch, and create a PR against the target branch."]}].map(({finish:r,name:n,description:a})=>({name:n,stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","archive",e.name,"--dry-run","--finish",r],requiredInputs:[],inputOptions:[],description:Lt(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:Lt(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function gy(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function $r(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function Aj(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function vy(e,t,i){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...i]}}function _j(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function Ij(e){return["comet","native","next",e.change,"--summary","<summary>",...e.coordinationRequired?["--coordination-mode","<coordination-mode>"]:[],"--expected-state-version",String(e.stateVersion),"--expected-action","prepare-shape-confirmation"]}function vi(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:gy({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[$r("summary","--summary"),Aj(e.name,e.flag)]}}function jd(e){return[vi({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),vi({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function wy(e,t,i={}){let r=_j(t)&&e.coordination_mode===void 0,n=xj(e,r),a={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],requiresUserDecision:n.required,userCommunication:n},o=s=>({kind:s,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...a,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:o("none")};if(e.status==="await-user")return e.phase==="shape"&&e.loop.next_action==="confirm-shape"?{...a,disposition:"await-user",action:"confirm-shape",commandArgs:null,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:[$r("summary","--summary")],commandAlternatives:[vi({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:[$r("summary","--summary")],commandAlternatives:[vi({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...jd({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:[$r("summary","--summary")],commandAlternatives:[vi({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),vi({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:[$r("summary","--summary")],commandAlternatives:[vi({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...jd({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:[$r("summary","--summary")],commandAlternatives:jd({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:o("none")};if(e.status==="blocked"){let s=e.blockers.some(({resolution_action:c})=>c==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?gy({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:s?["summary"]:["repair-runtime"],inputOptions:s?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:o(s?"retry-verifier":"none")}}if(e.phase==="shape")return{...a,disposition:r?"await-user":"continue",action:"prepare-shape-confirmation",commandArgs:Ij({change:e.name,stateVersion:e.state_version,coordinationRequired:r}),requiredInputs:["summary",...r?["coordination-choice"]:[]],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},...r?[vy("coordination-mode","--coordination-mode",Sm)]:[]],runnerAction:o("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...a,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:o("none")};if(t.allDone)return{...a,disposition:"continue",action:"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:o("builder-handoff")};let s=t.children.some(({status:l})=>l==="blocked"||l==="needs-reverify"),c=t.children.some(({status:l})=>l==="ready"||l==="active");return{...a,disposition:s&&!c?"blocked":"continue",action:"advance-children",commandArgs:null,requiredInputs:s&&!c?["resolve-child-blocker"]:["ready-children"],inputOptions:[],runnerAction:o("none")}}return{...a,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:o("builder-handoff")}}if(e.phase==="verify"){let s=e.loop.next_action==="await-verifier-result",c=!!e.children_contract_hash,l={id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0};return{...a,userCommunication:!s&&c?{...a.userCommunication,agentInstruction:`${a.userCommunication.agentInstruction} ${Lt(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:a.userCommunication,disposition:"continue",action:s?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[s?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:s?[{kind:"verifier-response",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[l]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:[{id:"<acceptance-id>",result:"<passed|failed|blocked>",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:c?[l]:[]}}],runnerAction:o(s?"await-verifier":"dispatch-verifier")}}if(e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived){let s=i.archiveMode??"archive-ready",l=e.workspace.isolation!=="current"&&e.workspace.finish===null;return s==="blocked"?{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")}:s==="preview"?i.archiveBlockers&&i.archiveBlockers.length>0?{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}:l?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[vy("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...Rj(e)],userCommunication:Pj(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[vi({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")}}function Tj(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function yy(e){let t=e.acceptance.reduce((i,r)=>({...i,[r.result]:i[r.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0});return{schema:"comet.native.state-summary.v1",name:e.name,phase:e.phase,status:e.status,state_version:e.state_version,...e.coordination_mode===void 0?{}:{coordination_mode:e.coordination_mode},loop:e.loop,acceptance:t,unresolved_acceptance_ids:e.acceptance.filter(({result:i})=>i==="failed"||i==="blocked").map(({id:i})=>i),verification_result:e.verification_result,blockers:e.blockers.slice(0,8).map(i=>({owner:i.owner,reason:Tj(i.reason.text),acceptance_ids:i.acceptance_ids,resolution_action:i.resolution_action})),workspace:{isolation:e.workspace.isolation,change_branch:e.workspace.change_branch,target_branch:e.workspace.target_branch,finish:e.workspace.finish},archived:e.archived}}function $j(e,t,i){return`native-details-v2.${e}.${t}.${i.toString(36)}`}function Oj(e,t,i){if(!e)return 0;let r=/^native-details-v2\.(\d+)\.(\d+)\.([0-9a-z]+)$/u.exec(e);if(!r||Number(r[1])!==t||Number(r[2])!==i)throw new Error("Native details cursor is stale or invalid");let n=Number.parseInt(r[3],36);if(!Number.isSafeInteger(n)||n<0)throw new Error("Native details cursor offset is invalid");return n}function Hj(e,t,i){return[...e.acceptance.map(r=>({kind:"acceptance",value:r})),...e.spec_changes.map(r=>({kind:"spec-change",value:r})),...e.builder_handoff?[{kind:"builder-handoff",value:e.builder_handoff}]:[],...e.verification?[{kind:"verification",value:e.verification}]:[],...e.history.map(r=>({kind:"history",value:r})),{kind:"history-overflow",value:e.history_overflow},{kind:"workspace",value:e.workspace},...e.verification_report?[{kind:"verification-report",value:e.verification_report}]:[],...t?[{kind:"supervisor-integration",value:{...t.integration,worktree:"<worktree>",targetCommit:"<redacted>",headCommit:"<redacted>"}},{kind:"supervisor-final-verification",value:t.finalVerification},...t.children.map(r=>({kind:"supervisor-child",value:Lj(r,i)})),...t.history.map(r=>({kind:"supervisor-history",value:Vj(r,i)}))]:[]]}function Dj(e){return e.acceptance.reduce((t,i)=>({...t,[i.result]:t[i.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0})}function Ny(e,t){let i=Ee(e.projectRoot),r=null;return t.workspace.change_branch!==null&&(i.isGitWorktree?i.currentBranch!==t.workspace.change_branch&&(r=`Expected branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}.`):r="The Native change requires a registered Git worktree."),r===null&&t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree&&(r="The Native change requires its linked worktree."),{projectRoot:jj.resolve(e.projectRoot),isolation:t.workspace.isolation,bindingState:r===null?"aligned":"mismatch",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:r}}function Bj(e,t){return[e.projectRoot,t.integration.worktree,...t.children.flatMap(i=>[i.projectRoot,i.task?.projectRoot])].filter(i=>!!i).map(i=>i.replaceAll("/","\\")).sort((i,r)=>r.length-i.length)}function Ds(e,t){return e===null?null:t.reduce((i,r)=>i.replaceAll(r,"<worktree>").replaceAll(r.replaceAll("\\","/"),"<worktree>"),e)}function Lj(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:Ds(e.blocker,t),task:e.task?{...e.task,projectRoot:"<worktree>",baseCommit:"<redacted>",runId:"<redacted>"}:null}}function Vj(e,t){return{...e,runId:e.runId?"<redacted>":null,summary:Ds(e.summary,t)??""}}async function by(e){let t=await Eg(e),i=yy(t.state),r=t.state.status==="active"&&t.state.loop.stage!=="done",n=await Hu({paths:e.paths,state:t.state}),a=await my({paths:e.paths,state:t.state}),o=a.status==="repairable-legacy-overlay"||a.status==="incompatible"?null:await $i(e.paths,e.name),s=o?{...Ny(e.paths,t.state),projectRoot:"."}:Ny(e.paths,t.state),c=wy(t.state,n),l=s.bindingState==="mismatch"?{...c,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["return-to-bound-workspace"],runnerAction:{...c.runnerAction,kind:"none"}}:c,u=o?Bj(e.paths,o):[],d=o?(()=>{let v=o.children.filter(({status:N})=>N==="pending"||N==="ready").length,h=o.children.filter(({status:N})=>N==="active"||N==="verified").length,m=o.children.filter(({status:N})=>N==="integrated"||N==="archived").length,S=o.children.filter(({status:N})=>N==="blocked"||N==="needs-reverify").length,y=o.children.filter(({status:N})=>N==="active"||N==="blocked"||N==="needs-reverify").slice(0,16).map(N=>({name:N.name,summary:N.summary,projectRoot:N.task?.projectRoot??N.projectRoot?"<worktree>":null,reason:Ds(N.blocker,u)})),k=o.children.flatMap(({blocker:N})=>{let E=Ds(N,u);return E?[E]:[]}).slice(0,16);return{targetSpecs:t.state.spec_changes.length,implementationChildren:o.children.length,waiting:v,working:h,integrated:m,blocked:S,active:y,agents:{working:o.children.filter(({task:N})=>N!==null).length,completed:m},risks:k,nextAction:o.finalVerification.status==="passed"?"final-delivery":o.finalVerification.status==="pending"&&m===o.children.length?"parent-verification":v>0?"dispatch-ready-child":S>0?"resolve-blocker":"continue-supervisor"}})():null,f=e.details?(()=>{let v=o?.stateVersion??0,h=Hj(t.state,o,u),m=Oj(e.cursor,t.state.state_version,v),S=h.slice(m,m+32),y=m+S.length<h.length?$j(t.state.state_version,v,m+S.length):null;return{items:S,nextCursor:y,supervisorStateVersion:v}})():null,p=o?{schema:o.schema,parent:o.parent,integration:{branch:o.integration.branch,targetBranch:o.integration.targetBranch},finalVerification:{status:o.finalVerification.status,summary:o.finalVerification.summary},summary:d}:null;return{schema:"comet.native.status.v2",name:t.state.name,phase:t.state.phase,status:t.state.status,stateVersion:t.state.state_version,...t.state.coordination_mode===void 0?{}:{coordinationMode:t.state.coordination_mode},loop:t.state.loop,acceptance:Dj(t.state),unresolvedAcceptanceIds:i.unresolved_acceptance_ids,verificationResult:t.state.verification_result,blockers:o?[]:i.blockers,workspace:s,localExecution:{status:r?t.localStatus:"not-expected",operation:t.localStatus==="available"?t.local?.execution??null:null},...n?{childSummary:n.children.reduce((v,h)=>({...v,[h.status]:(v[h.status]??0)+1}),{total:n.children.length}),readyChildren:n.readyChildren}:{},...p?{supervisor:p}:{},...a.status==="repairable-legacy-overlay"||a.status==="incompatible"?{supervisorOverlay:{status:a.status,message:a.message,repairCommand:a.status==="repairable-legacy-overlay"?`comet native doctor ${e.name} --repair`:null}}:{},continuation:l,...e.details?{details:{stateVersion:t.state.state_version,...o?{supervisorStateVersion:f.supervisorStateVersion}:{},items:f.items,nextCursor:f.nextCursor,nextPageArgs:f.nextCursor?["comet","native","status",t.state.name,"--details","--cursor",f.nextCursor,"--json","--project-root",e.paths.projectRoot]:null}}:{}}}import ra from"path";import{realpathSync as r$}from"fs";var Vt={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function ky(e){return e?e.command?`${Vt.next} ${e.command}`:e.ask_user?`${Vt.next} ${e.ask_user}`:null:null}function Sy(e,t){let i=[e.summary],r=ky(e.next);return r&&i.push(r),e.user_message&&i.push("",Vt.relay,e.user_message),t!==void 0&&i.push("",Vt.details,JSON.stringify(t,null,2)),`${i.join(`
171
+ ${Nn(i)}`;e.update(`${Buffer.byteLength(r,"utf8")}:`),e.update(r)}function m_(e){if(Wn(e)<=Hi)return e;let t=[...e.entries],i=[...e.omitted],r=e.omittedCount,n=e.omissionOverflow?.count??0,a=Hg("sha256");a.update(`${s_}
172
+ `),e.omissionOverflow&&ci(a,"existing-overflow",e.omissionOverflow);let o=(f,p)=>{p||(r+=1),n+=1,ci(a,"omission",f)},s=f=>{r+=1,n+=1,ci(a,"entry",f)},c=()=>{for(let f=i.length-1;f>=0;f-=1){let p=i[f];if(!(p.reason==="git-enumeration-limit"||p.reason==="git-selection-changed"||p.reason==="physical-enumeration-limit"||p.reason==="physical-selection-changed"))return i.splice(f,1),p}return null},l=()=>({...e,complete:r===0,entries:t,omitted:i,omittedCount:r,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:n}}),u=l();for(;Wn(u)>Hi;){if(i.filter(p=>p.reason!=="git-enumeration-limit"&&p.reason!=="git-selection-changed"&&p.reason!=="physical-enumeration-limit"&&p.reason!=="physical-selection-changed").length>0){let p=Math.max(1,Math.ceil(i.length/4));for(let v=0;v<p;v+=1){let h=c();if(h===null)break;o(h,!0)}}else if(t.length>0){let p=Math.max(1,Math.ceil(t.length/4));for(let v of t.splice(-p))s(v)}else throw new Error("Native snapshot projection metadata exceeds its evidence byte budget");u=l()}let d=a.digest("hex");return{...u,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${d}`,hash:d,count:n}}}function zu(e){let t=_i(e),i=t.entries.map((n,a)=>d_(n,`Snapshot entry ${a}`));if(i.sort(p_),new Set(i.map(n=>n.path)).size!==i.length)throw new Error("Snapshot entries must not contain duplicate paths");let r=t.omitted.map((n,a)=>f_(n,`Snapshot omission ${a}`));return r.sort(h_),m_({schema:Dg,origin:t.origin,...t.capture?{capture:t.capture}:{},complete:t.complete,limits:{maxFiles:t.limits.maxFiles,maxFileBytes:t.limits.maxFileBytes,maxTotalBytes:t.limits.maxTotalBytes,maxManifestBytes:t.limits.maxManifestBytes,...t.limits.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},...t.policy?{policy:t.policy}:{},entries:i,omitted:r,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:{ref:t.omissionOverflow.ref,hash:t.omissionOverflow.hash,count:t.omissionOverflow.count}}:{}})}function zn(e){let t=new Map;for(let[i,r]of e.entries()){if(r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${i} kind is invalid`);let n={path:li(r.path,`Declared artifact ${i} path`),kind:r.kind},a=t.get(n.path);if(a&&a.kind!==n.kind)throw new Error(`Declared artifact path has conflicting kinds: ${n.path}`);t.set(n.path,n)}return[...t.values()].sort((i,r)=>ve(i.path,r.path)||ve(i.kind,r.kind))}function Jn(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function _g(e){return e?{hash:e.hash,size:e.size}:null}function Uu(e,t,i){let r=0,n=0;for(;r<e.entries.length||n<t.entries.length;){let a=e.entries[r],o=t.entries[n],s=a===void 0?1:o===void 0?-1:ve(a.path,o.path),c=s<=0?a:void 0,l=s>=0?o:void 0;if(s<=0&&(r+=1),s>=0&&(n+=1),c&&l&&c.hash===l.hash&&c.size===l.size||c&&!l&&!t.complete)continue;let u=c?.path??l?.path;u!==void 0&&i({path:u,kind:c?l?"modified":"removed":"added",before:_g(c),after:_g(l)})}}function Vg(e,t){return{...e,attributedTo:t.filter(i=>Jn(i,e.path))}}function Ku(e){let t=zn(e.declaredArtifacts),i=[];return Uu(e.baseline,e.current,r=>{i.push(Vg(r,t))}),i}function $t(e,t){return{id:`scope:${H(a_,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function v_(e,t){let i=t.omitted.map(r=>$t({kind:"snapshot-omission",source:e,path:r.path,evidence:{reason:r.reason,size:r.size,type:r.type}},`${e} snapshot omitted ${r.path}: ${r.reason}`));return t.complete||i.push($t({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&i.push($t({kind:"snapshot-omission-overflow",source:e,path:null,evidence:{count:t.omissionOverflow.count,hash:t.omissionOverflow.hash,ref:t.omissionOverflow.ref}},`${e} snapshot has ${t.omissionOverflow.count} unlisted omissions`)),i}function Ig(e,t){return v_(e,{...t,omitted:[]}).filter(i=>i.kind!=="snapshot-omission")}function Ju(e,t){return ve(e.kind,t.kind)||ve(e.source,t.source)||u_(e.path,t.path)||ve(e.id,t.id)}function g_(e){return[...new Map(e.map(i=>[i.id,i])).values()].sort(Ju)}function Fg(e){return[...new Set(e.map((t,i)=>li(t,`Git path ${i}`)))].sort(ve)}function Tg(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 w_(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 qg(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=Fg(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:Tg(e.baseCommit,"Native external drift base commit"),targetBranch:w_(e.targetBranch,"Native external drift target branch"),targetCommit:Tg(e.targetCommit,"Native external drift target commit"),paths:t}}function Mg(e){if(typeof e.contractHash!="string"||!Gu.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:zn(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:Fg(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:qg(e.externalDrift)}}}function y_(e,t,i,r,n){let a=[],o=r===void 0?null:new Set(r),s=[],c=[],l=0,u=!1,d=0,f=0;return Uu(e,t,p=>{let v=i.some(h=>Jn(h,p.path));if(d+=1,c.push(p.path),!v&&!n?.has(p.path)&&(f+=1),o?.has(p.path)&&s.push(p.path),!u&&a.length<c_){let h=Vg(p,i),m=Wn(h);l+m<=Hi?(a.push(h),l+=m):u=!0}}),{candidates:a,gitPathsPresentInChanges:s,changePaths:c,totalChanges:d,totalUnattributed:f}}function Wg(e,t){return $t({kind:"scope-detail-overflow",source:"implementation-scope",path:null,evidence:{changeCount:t.changes,hash:e,unattributedCount:t.unattributed,unresolvedCount:t.unresolved}},`Implementation scope summarized ${t.changes} additional change details and ${t.unresolved} unresolved details (${t.unattributed} unattributed); overflow hash ${e}`)}function N_(e){let t=/^Implementation scope summarized ([0-9]+) additional change details and ([0-9]+) unresolved details \(([0-9]+) unattributed\); overflow hash ([a-f0-9]{64})$/u.exec(e.reason);if(!t)throw new Error("Implementation scope detail overflow is invalid");let i={changes:kr(Number(t[1]),"Scope overflow change count"),unresolved:kr(Number(t[2]),"Scope overflow unresolved count"),unattributed:kr(Number(t[3]),"Scope overflow unattributed count")},r=Oi(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(Wg(r,i)))throw new Error("Implementation scope detail overflow is inconsistent");return{...i,hash:r}}function b_(e){let t=Hg("sha256");t.update(`${o_}
173
+ `);let i=0;Uu(e.baseline,e.current,n=>{if(i>=e.detailedChangeCount){ci(t,"change",n);let a=0;for(let o of e.declaredArtifacts)Jn(o,n.path)&&(a+=1,ci(t,"change-attribution",o));ci(t,"change-end",{attributionCount:a}),a===0&&ci(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}i+=1});let r=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)r>=e.detailedOmissionCount&&ci(t,"snapshot-omission",{source:n,...o}),r+=1;return t.digest("hex")}function zg(e,t,i){let{contractHash:r,declaredArtifacts:n,noCodeReason:a}=i,o=y_(e,t,n,i.gitChangedPaths,i.externalDrift?new Set(i.externalDrift.paths):void 0);if(i.externalDrift){let x=new Set(i.externalDrift.paths),g=new Set(o.changePaths),w=i.externalDrift.paths.filter(C=>!g.has(C)||n.some($=>Jn($,C)));if(w.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${w.slice(0,8).join(", ")}`);if(x.size!==i.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=H(qn,e),c=H(qn,t),l=[],u=new Set(i.externalDrift?.paths??[]);for(let[x,g]of[["baseline",e],["current",t]])for(let w of g.omitted){if(l.length>=l_)break;l.push($t({kind:"snapshot-omission",source:x,path:w.path,evidence:{reason:w.reason,size:w.size,type:w.type}},`${x} snapshot omitted ${w.path}: ${w.reason}`))}let d=e.omitted.length+t.omitted.length,f=[...Ig("baseline",e),...Ig("current",t),...o.totalChanges===0&&a===null?[$t({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:s,currentProjectionHash:c}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],p=()=>{if(i.gitChangedPaths===void 0)return;let x=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:i.gitChangedPaths,pathsPresentInSnapshotChanges:i.gitChangedPaths.filter(g=>x.has(g)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(g=>!x.has(g))}},v=x=>{let g=o.candidates.slice(0,x.detailedChangeCount),w=g.filter(Ge=>Ge.attributedTo.length===0&&!u.has(Ge.path)),C=o.totalChanges-g.length,$=o.totalUnattributed-w.length,T=d-x.detailedOmissionCount,pe=$+T,Q=[...w.map(Ge=>$t({kind:"unattributed-change",source:"implementation-scope",path:Ge.path,evidence:{after:Ge.after,before:Ge.before,changeKind:Ge.kind}},`Changed path is not covered by a declared artifact: ${Ge.path}`)),...l.slice(0,x.detailedOmissionCount),...f,...pe>0?[Wg(x.overflowHash,{changes:C,unattributed:$,unresolved:pe})]:[]],G=g_(Q),lt=x.includeGitAdvisory?p():void 0;return{schema:Mu,contractHash:r,baselineProjectionRef:Wu(s),baselineProjectionHash:s,currentProjectionRef:Wu(c),currentProjectionHash:c,complete:G.length===0,declaredArtifacts:n,changes:g,unattributed:w,unresolvedScopes:G,noCodeReason:a,...lt?{gitAdvisory:lt}:{},...i.externalDrift?{externalDrift:i.externalDrift}:{}}},h=o.candidates.length,m=l.length,S=i.gitChangedPaths!==void 0,y="0".repeat(64);for(;;){let x=v({detailedChangeCount:h,detailedOmissionCount:m,includeGitAdvisory:S,overflowHash:y});if(Wn({...x,scopeHash:y})<=Hi)break;if(S){S=!1;continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}if(h>0){h-=Math.max(1,Math.ceil(h/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let N=o.totalChanges>h||d>m?b_({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:h,detailedOmissionCount:m}):y,E=v({detailedChangeCount:h,detailedOmissionCount:m,includeGitAdvisory:S,overflowHash:N}),b={...E,scopeHash:H(Bg,E)};if(Wn(b)>Hi)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return b}function Yu(e){let t=zu(e.baseline),i=zu(e.current),r=Mg(e);return{authority:r,baseline:t,current:i,scope:zg(t,i,r)}}var k_=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"]);function yt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Nt(e,t,i,r){let n=new Set([...t,...i]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${r} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${r} is missing field(s): ${o.join(", ")}`)}function Oi(e,t){if(typeof e!="string"||!Gu.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function jg(e,t,i){let r=Wu(t);if(e!==r)throw new Error(`${i} ref/hash mismatch`);return r}function ys(e,t){let i=yt(e,"Native snapshot projection");if(Nt(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==Dg)throw new Error("Native snapshot projection schema is invalid");let r=_i({schema:"comet.native.content-snapshot.v1",origin:i.origin,...i.capture===void 0?{}:{capture:i.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:i.complete,limits:i.limits,...i.policy===void 0?{}:{policy:i.policy},entries:i.entries,omitted:i.omitted,omittedCount:i.omittedCount,...i.omissionOverflow===void 0?{}:{omissionOverflow:i.omissionOverflow}}),n=zu(r);if(H(qn,i)!==H(qn,n))throw new Error("Native snapshot projection is not canonical");let a=H(qn,n);if(t!==void 0&&Oi(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function Xu(e,t){let i=yt(e,`Declared artifact ${t}`);if(Nt(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:li(i.path,`Declared artifact ${t} path`),kind:i.kind}}function $g(e,t){if(e===null)return null;let i=yt(e,t);return Nt(i,["hash","size"],[],t),{hash:Oi(i.hash,`${t} hash`),size:kr(i.size,`${t} size`)}}function Og(e,t){let i=yt(e,`Implementation change ${t}`);if(Nt(i,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),i.kind!=="added"&&i.kind!=="modified"&&i.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(i.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let r=i.attributedTo.map(Xu),n=zn(r);if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=$g(i.before,`Implementation change ${t} before`),o=$g(i.after,`Implementation change ${t} after`);if(i.kind==="added"&&(a!==null||o===null)||i.kind==="removed"&&(a===null||o!==null)||i.kind==="modified"&&(a===null||o===null||JSON.stringify(a)===JSON.stringify(o)))throw new Error(`Implementation change ${t} before/after state is invalid`);return{path:li(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:r}}function S_(e,t){let i=yt(e,`Unresolved scope ${t}`);Nt(i,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let r=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof i.kind!="string"||!r.has(i.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(i.source!=="baseline"&&i.source!=="current"&&i.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof i.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(i.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(i.path!==null&&typeof i.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof i.reason!="string"||i.reason.length===0||i.reason.trim()!==i.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:i.id,kind:i.kind,source:i.source,path:i.path===null?null:i.kind==="snapshot-omission"?Lg(i.path,`Unresolved scope ${t} path`):li(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function Mn(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of paths`);let i=e.map((n,a)=>li(n,`${t} ${a}`)),r=[...new Set(i)].sort(ve);if(JSON.stringify(i)!==JSON.stringify(r))throw new Error(`${t} must be sorted and unique`);return i}function Jg(e){let t=yt(e,"Native implementation external drift");if(Nt(t,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),t.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let i=Mn(t.paths,"Native external drift paths");return qg({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:i})}function Ns(e){let t=yt(e,"Native implementation scope"),i=[...k_].filter(w=>w!=="gitAdvisory"&&w!=="externalDrift");if(Nt(t,i,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==Mu)throw new Error("Native implementation scope schema is invalid");let r=Oi(t.contractHash,"Implementation scope contractHash"),n=Oi(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=jg(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=Oi(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=jg(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(Xu);if(JSON.stringify(c)!==JSON.stringify(zn(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(Og),u=[...l].sort((w,C)=>ve(w.path,C.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(w=>w.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(w=>`${w.kind}:${w.path}`));if(l.some(w=>w.attributedTo.some(C=>!d.has(`${C.kind}:${C.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(w=>JSON.stringify(w.attributedTo)!==JSON.stringify(c.filter(C=>Jn(C,w.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(Og),p=t.externalDrift===void 0?void 0:Jg(t.externalDrift),v=new Set(p?.paths??[]),h=l.filter(w=>w.attributedTo.length===0&&!v.has(w.path));if(JSON.stringify(f)!==JSON.stringify(h))throw new Error("Implementation scope unattributed changes are inconsistent");let m=t.unresolvedScopes.map(S_),S=m.filter(w=>w.kind==="scope-detail-overflow");if(S.length>1)throw new Error("Implementation scope has multiple detail overflow records");let y=S[0]===void 0?null:N_(S[0]);if(y&&(y.changes+y.unresolved===0||y.unattributed>y.changes||y.unattributed>y.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let k=t.noCodeReason,N=[...h.map(w=>$t({kind:"unattributed-change",source:"implementation-scope",path:w.path,evidence:{after:w.after,before:w.before,changeKind:w.kind}},`Changed path is not covered by a declared artifact: ${w.path}`)),...l.length+(y?.changes??0)===0&&k===null?[$t({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:n,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],E=m.filter(w=>w.kind==="unattributed-change"||w.kind==="missing-no-code-reason");if(JSON.stringify(m)!==JSON.stringify([...m].sort(Ju))||new Set(m.map(w=>w.id)).size!==m.length||JSON.stringify(E)!==JSON.stringify(N.sort(Ju))||t.complete!==(m.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let b;if(t.gitAdvisory!==void 0){let w=yt(t.gitAdvisory,"Implementation scope Git advisory");if(Nt(w,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),w.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let C=Mn(w.changedPaths,"Git changed paths"),$=Mn(w.pathsPresentInSnapshotChanges,"Git present paths"),T=Mn(w.pathsAbsentFromSnapshotChanges,"Git absent paths"),pe=[...$,...T].sort(ve);if(JSON.stringify(pe)!==JSON.stringify(C)||T.some(Q=>l.some(G=>G.path===Q)))throw new Error("Implementation scope Git advisory partition is invalid");b={advisoryOnly:!0,changedPaths:C,pathsPresentInSnapshotChanges:$,pathsAbsentFromSnapshotChanges:T}}let x={schema:Mu,contractHash:r,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:m,noCodeReason:k,...b?{gitAdvisory:b}:{},...p?{externalDrift:p}:{}},g=Oi(t.scopeHash,"Implementation scope scopeHash");if(H(Bg,x)!==g)throw new Error("Implementation scope content hash mismatch");return{...x,scopeHash:g}}function E_(e){let t=yt(e,"Native implementation scope authority");if(Nt(t,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths","externalDrift"],"Native implementation scope authority"),!Array.isArray(t.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let i=t.declaredArtifacts.map(Xu);if(JSON.stringify(i)!==JSON.stringify(zn(i)))throw new Error("Native implementation scope authority declarations must be canonical");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let r;t.gitChangedPaths!==void 0&&(r=Mn(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:Jg(t.externalDrift),a=Mg({contractHash:t.contractHash,declaredArtifacts:i,noCodeReason:t.noCodeReason,...r===void 0?{}:{gitChangedPaths:r},...n===void 0?{}:{externalDrift:n}});if(a.contractHash!==t.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return a}function Gn(e){let t=yt(e,"Native implementation scope bundle");Nt(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=E_(t.authority),r=ys(t.baseline),n=ys(t.current),a=Ns(t.scope),o=zg(r,n,i);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:i,baseline:r,current:n,scope:o}}function Gg(e){let t=Ns(e.scope);return Gn({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 Yg=/^[a-f0-9]{64}$/u;var C_="comet.native.acceptance-trace.v2",x_="comet.native.partial-allowance.v1",P_="comet.native.verification-evidence.v2";function Ot(e,t){if(!Yg.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Xg(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function Qg(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 Qu(e,t,i=2e3){let r=We(e).trim();if(r.length===0||r.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return r}function Un(e,t){let i=Ug.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||Ug.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function R_(e,t,i){let r=Un(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(r))return r;let n=ft(r),a=r.toLowerCase(),o=i?Un(i,"Native root ref").toLowerCase():null;if(n||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${t} is excluded as sensitive (${n??"native-runtime"}): ${r}`);return r}function Zu(e){let t=Un(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 Sr(e,t){return e<t?-1:e>t?1:0}function bs(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ks(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function Zg(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function Kg(e,t,i){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let r=`runtime/evidence/${t}/${i}.json`;if(e!==r)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function A_(e){let t=bs(e,"Native acceptance trace");if(ks(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"||!Yg.test(t.criteriaHash)||!Number.isSafeInteger(t.total)||!Number.isSafeInteger(t.evidenced)||!Number.isSafeInteger(t.skipped)||!Array.isArray(t.entries))throw new Error("Native acceptance trace is invalid");let i=Un(t.nativeRootRef,"Native root ref"),r=t.entries.map((o,s)=>{let c=bs(o,`Native acceptance trace entry ${s}`);if(ks(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=>Zu(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Sr))||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:Un(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Qu(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(r)!==JSON.stringify([...r].sort((o,s)=>Sr(o.acceptanceId,s.acceptanceId)))||new Set(r.map(o=>o.acceptanceId)).size!==r.length||t.total!==r.length||t.evidenced!==r.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==r.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let n={schema:"comet.native.acceptance-trace.v2",nativeRootRef:i,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:r},a=Ot(t.traceHash,"Native acceptance trace hash");if(H(C_,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function ew(e){let t=bs(e,"Native partial allowance");if(ks(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(Sr))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let i={schema:"comet.native.partial-allowance.v1",change:Qg(t.change),scopeHash:Ot(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Qu(t.reason,"Partial allowance reason"),confirmedSummary:Qu(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:Xg(t.sourceRevision),confirmedAt:Zg(t.confirmedAt,"Native partial allowance timestamp")};if(i.reason!==t.reason||i.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let r=Ot(t.allowanceHash,"Native partial allowance hash");if(H(x_,i)!==r)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:r}}function ed(e){let t=bs(e,"Native verification evidence");if(ks(t,["schema","change","sourceRevision","result","freshness","contractHash","acceptanceCriteriaHash","implementationScopeRef","implementationScopeHash","reportRef","reportHash","acceptanceTrace","partialAllowanceRef","partialAllowanceHash","requiredReceiptRefs","receiptRefs","createdAt","envelopeHash"],"Native verification evidence"),t.schema!=="comet.native.verification-evidence.v2"||typeof t.change!="string"||t.result!=="pass"&&t.result!=="fail"||t.freshness!=="complete"&&t.freshness!=="partial"||typeof t.implementationScopeHash!="string"||typeof t.reportRef!="string"||!Array.isArray(t.requiredReceiptRefs)||!Array.isArray(t.receiptRefs))throw new Error("Native verification evidence is invalid");let i=Ot(t.implementationScopeHash,"Native verification implementation scope hash"),r=A_(t.acceptanceTrace),n=Ot(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(r.criteriaHash!==n)throw new Error("Native verification acceptance trace does not match its criteria hash");let a=t.partialAllowanceRef!==null||t.partialAllowanceHash!==null;if(t.partialAllowanceRef===null!=(t.partialAllowanceHash===null)||t.freshness==="complete"&&a||t.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=t.partialAllowanceHash===null?null:Ot(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>Zu(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(Sr)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(r.entries.flatMap(f=>f.evidenceRefs))].sort(Sr);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=t.requiredReceiptRefs.map(f=>Zu(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Sr)))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:Qg(t.change),sourceRevision:Xg(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:Ot(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:Kg(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:R_(t.reportRef,"Native verification report ref"),reportHash:Ot(t.reportHash,"Native verification report hash"),acceptanceTrace:r,partialAllowanceRef:o===null?null:Kg(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:Zg(t.createdAt,"Native verification timestamp")},d=Ot(t.envelopeHash,"Native verification envelope hash");if(H(P_,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}function td(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 tw="repairStagnation",$e={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},I_=/^[a-f0-9]{64}$/u;var T_=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),j_=["data","runId","sequence","timestamp","type"],iw=["disposition","overrideSummaryHash","signatureHash"],$_=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],rw=12;function rd(e,t){return e<t?-1:e>t?1:0}function nw(e,t,i){let r=Object.keys(e).sort(rd);if(r.length!==t.length||r.some((n,a)=>n!==t[a]))throw new Error(`${i} fields are invalid`)}function Ss(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function Kn(e,t){if(typeof e!="string"||!I_.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function O_(e){if(!Array.isArray(e)||e.length>br.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(rd)}function aw(e){if(typeof e!="string"||e.length===0||e.length>$e.maxRunIdCharacters||Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function id(e,t,i,r,n=!1){if(i.nodes+=1,i.nodes>$e.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>$e.maxDataDepth)throw new Error("Native repair trajectory event data exceeds its depth boundary");if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${r} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>$e.maxTextCharacters&&(!n||e.length>$e.maxEventDataCharacters))throw new Error(`${r} contains oversized text`);if(i.characters+=e.length,i.characters>$e.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${r} contains a non-JSON value`);if(i.ancestors.has(e))throw new Error(`${r} contains a cycle`);i.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>$e.maxArrayEntries)throw new Error(`${r} contains an oversized array`);e.forEach((s,c)=>id(s,t+1,i,`${r}[${c}]`));return}let a=Ss(e,r),o=Object.keys(a);if(o.length>$e.maxObjectFields)throw new Error(`${r} contains too many fields`);for(let s of o){if(s.length===0||s.length>$e.maxKeyCharacters)throw new Error(`${r} contains an invalid field name`);if(i.characters+=s.length,i.characters>$e.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");id(a[s],t+1,i,`${r}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function H_(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 D_(e,t,i){let r=Ss(e,`Native repair trajectory event ${t+1}`);if(nw(r,j_,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(r.sequence)||r.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(H_(r.timestamp),typeof r.type!="string"||!T_.has(r.type))throw new Error("Native repair trajectory event type is invalid");if(aw(r.runId)!==i)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let n={nodes:0,characters:0,ancestors:new Set};return id(r.data,0,n,"Native trajectory event data"),Ss(r.data,"Native repair trajectory event data"),{event:r,dataNodes:n.nodes,dataCharacters:n.characters}}function nd(e){let t=Ss(e,"Native repair trajectory projection"),i=Object.keys(t).sort(rd),r=i.length===iw.length&&i.every((l,u)=>l===iw[u]);r||nw(t,$_,"Native repair trajectory projection");let n=Kn(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:Kn(t.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&t.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(r)return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=Kn(t.contractHash,"Native repair trajectory contract hash"),s=O_(t.failedAcceptanceIds),c=Fu(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 B_(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 L_(e,t){let i=t.filter(s=>s.kind==="failure"),r=i.length+1,n=e.maxVerifyFailures??rw;if(r>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=qu({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=r>=n?"hard-stop":a<br.warningAtConsecutiveFailures?"continue":a<br.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function V_(e,t,i){let r=t.filter(a=>a.kind==="failure"),n=i?.maxVerifyFailures??rw;if(r.length>=n)throw new Error("Native repair trajectory cannot override a hard stop");if(i?.disposition!=="manual-stop"||i.signatureHash!==e.signatureHash||r.at(-1)?.signatureHash!==e.signatureHash)throw new Error("Native repair trajectory override does not match the latest manual stop");if(t.some(a=>a.kind==="override"&&a.signatureHash===e.signatureHash))throw new Error("Native repair trajectory signature was already overridden")}function ow(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>$e.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=aw(e.runId);if(!Number.isSafeInteger(e.committedTrajectoryOffset)||e.committedTrajectoryOffset<0||e.committedTrajectoryOffset>e.trajectory.length)throw new Error("Native repair committed trajectory offset is invalid");let i=[],r=null,n=null,a=null,o=0,s=0,c=0;for(let l=0;l<e.committedTrajectoryOffset;l+=1){let u=D_(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>$e.maxTotalDataNodes||c>$e.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,p=Object.hasOwn(f,"repairScopeHash")?Kn(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?Kn(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,tw)){if(r?.contractHash===null&&d.type==="state_transitioned"&&f.previousPhase==="build"&&f.nextPhase==="verify"&&(p!==null&&n!==null&&p!==n||p===null&&(r?.disposition==="manual-stop"||r?.disposition==="hard-stop"))){i.length=0,r=null,n=p,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let v=nd(f[tw]);if(B_(f,v),v.overrideSummaryHash===null)v.contractHash!==null&&a!==null&&v.contractHash!==a&&(i.length=0,o=0),v.contractHash!==null&&(a=v.contractHash),v.contractHash===null&&p!==null&&n!==null&&p!==n&&(i.length=0,o=0),p!==null&&(n=p),L_(v,i),o+=1,i.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:v.signatureHash,...v.contractHash===null?{}:{failedAcceptanceIds:[...v.failedAcceptanceIds],failedCheckIds:[...v.failedCheckIds]}});else{if(r?.contractHash===null&&p!==null&&n!==null&&p!==n)throw new Error("Native repair override cannot cross implementation scope progress");V_(v,i,r);let h=i.at(-1);if(!h||h.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");i.push({kind:"override",revision:d.sequence,iteration:h.iteration,signatureHash:v.signatureHash,summaryHash:v.overrideSummaryHash})}if(r=v,i.length>br.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:r}}function sw(e){return ow(e).history}function cw(e){let t=ow(e).latestProjection;return t?{...t}:null}var Er={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:[]},ad=K("comet-native-runtime:v3:scope-reopen"),F_=[{skillVersion:"3",skillHash:K("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:K("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:K("comet-native-runtime:v1")}];function lw(e){return e.skillVersion===Er.definition.metadata.version&&e.skillHash===ad||F_.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}function uw(e){return K(JSON.stringify({summary:e.summary,returnToBuild:e.returnToBuild??!1,confirmed:e.confirmed??!1,artifacts:[...e.artifacts??[]].sort(),noCodeReason:e.noCodeReason??null,verificationResult:e.verificationResult??null,verificationReport:e.verificationReport??null,allowPartialScopeHash:e.allowPartialScopeHash??null,partialReason:e.partialReason??null,repairOverrideSignature:e.repairOverrideSignature??null,repairOverrideSummary:e.repairOverrideSummary??null}))}var mw=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],G_=new Set(mw),vw=new Set([...mw,"minimum_runtime_version","revision"]),U_=new Set([...vw,"operation"]),K_=512*1024,sd=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),Y_=new Set([...sd,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),cd=class extends Error{constructor(i){super(`Native transition for ${i} requires doctor migration before recovery`);this.change=i;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function ud(e,t){return J_.join(U(e,t),"transition.json")}function Cs(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function dd(e,t){let i=Object.keys(e).find(r=>!t.has(r));if(i)throw new Error(`Native transition journal contains unknown field: ${i}`)}function Es(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function ld(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let i=e,r=Object.keys(i),n=r.find(u=>!Y_.has(u)),a=[...sd].find(u=>!Object.hasOwn(i,u)),o=sd.size+(Object.hasOwn(i,"implementationScopeHash")?1:0)+(Object.hasOwn(i,"repairScopeHash")?1:0)+(Object.hasOwn(i,"repairStagnation")?1:0)+(Object.hasOwn(i,"returnToBuild")?1:0);if(n||a||r.length!==o)throw new Error(`Native transition journal event data keys are invalid${n?`: ${n}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(i.previousPhase)||!["shape","build","verify","archive"].includes(i.nextPhase))throw new Error("Native transition journal event phases are invalid");if(i.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if(i.returnToBuild!==void 0&&typeof i.returnToBuild!="boolean")throw new Error("Native transition journal returnToBuild flag is invalid");if(td(i.summary,"Native transition journal event summary"),We(i.summary)!==i.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(i.artifacts)||i.artifacts.length>128||i.artifacts.some(u=>typeof u!="string"||u.length===0||Buffer.byteLength(u,"utf8")>512))throw new Error("Native transition journal event artifacts are invalid");if(i.noCodeReason!==null&&(td(i.noCodeReason,"Native transition journal event no-code reason"),We(i.noCodeReason)!==i.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(i.verificationResult!==null&&i.verificationResult!=="pass"&&i.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(i,"implementationScopeHash")?i.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||i.previousPhase!=="build"&&i.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(i,"repairStagnation")?nd(i.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(i.previousPhase!=="verify"||i.nextPhase!=="build"||i.verificationResult!=="fail")||!u&&(i.previousPhase!=="build"||i.nextPhase!=="verify"||i.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(i,"repairScopeHash")?i.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||i.previousPhase!=="build"&&i.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:t,summary:i.summary,artifacts:[...i.artifacts],noCodeReason:i.noCodeReason,verificationResult:i.verificationResult,...i.returnToBuild===!0?{returnToBuild:!0}:{},...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function X_(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let i=e,r=Object.keys(i),n=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(r.length===n.size&&r.every(a=>n.has(a))&&i.reason==="spec-rebase")return ld({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return ld(e,t)}function fd(e,t,i=!1){if(e.change!==t)throw new Error("Native transition journal change mismatch");if(typeof e.id!="string"||e.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof e.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(e.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native transition journal timestamp is invalid");let r=i?X_(e.eventData,e.evidenceHash):ld(e.eventData,e.evidenceHash),n=hu(e.nextRun),a=e.previousRun===null?null:hu(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:r}}function dw(e,t,i=!1){if(e.skill!==Er.definition.metadata.name||(i?!lw(e):e.skillVersion!==Er.definition.metadata.version||e.skillHash!==ad)||e.orchestration!==Er.definition.orchestration.mode||e.pendingRef!==qe.pendingRef||e.trajectoryRef!==qe.trajectoryRef||e.contextRef!==qe.contextRef||e.artifactsRef!==qe.artifactsRef||e.checkpointRef!==qe.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function fw(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 pw(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 pd(e,t,i,r=!1,n="advance"){let{previousRun:a,nextRun:o}=i;if(dw(o,"next Run",r||a!==null),pw(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(dw(a,"previous Run",!0),pw(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(!od(fw(a),fw(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function Q_(e,t,i){return K(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function gw(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function hw(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function hd(e,t,i,r,n=!1){let a=i.eventData,o=hw(e),s=hw(t);if(a.previousPhase!==e.phase||a.nextPhase!==t.phase)throw new Error("Native transition journal event phases do not match its states");if(e.archived||t.archived)throw new Error("Native transition journal cannot mutate an archived change");if(r==="runtime-rebuild"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&od(e.spec_changes,t.spec_changes);if(e.phase==="shape"||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||!c||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native Runtime rebuild transition semantics are invalid");return}if(r==="evidence-retreat"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&e.run_id===t.run_id&&od(e.spec_changes,t.spec_changes),l=uw({summary:a.summary,...a.returnToBuild?{returnToBuild:!0}:{}});if(!(e.phase==="archive"&&e.verification_result==="pass"||e.phase==="verify"&&e.verification_result==="pending")||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||i.evidenceHash!==l||!c||o===null||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native transition journal evidence retreat semantics are invalid");return}if(r==="spec-rebase"){let c=Q_(e.name,a.summary,t.spec_changes),l=K(`spec-rebase:${e.name}:${a.summary}`);if(e.phase==="shape"||t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||t.verification_report!==null||!n&&i.evidenceHash!==c||n&&i.evidenceHash!==c&&i.evidenceHash!==l||"implementation_scope"in t&&(t.implementation_scope!==null||t.verification_evidence!==null||t.partial_allowance!==null))throw new Error("Native transition journal spec rebase semantics are invalid");return}if(e.phase==="shape"){if(t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!=="pending"||t.verification_result!=="pending"||e.verification_report!==null||t.verification_report!==null||o!==null&&s!==null&&(o.implementation_scope!==null||o.verification_evidence!==null||o.partial_allowance!==null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null))throw new Error("Native transition journal Shape to Build semantics are invalid");return}if(e.phase==="build"){if(t.phase!=="verify"||a.verificationResult!==null||a.artifacts.length===0&&a.noCodeReason===null||t.verification_result!=="pending"||t.verification_report!==null||o!==null&&s!==null&&(s.implementation_scope===null||s.verification_evidence!==null||s.implementation_scope!==o.implementation_scope&&s.partial_allowance!==null&&s.partial_allowance===o.partial_allowance))throw new Error("Native transition journal Build to Verify semantics are invalid");return}if(e.phase==="verify"){let c=a.verificationResult==="pass"?"archive":"build";if(a.verificationResult!=="pass"&&a.verificationResult!=="fail"||t.phase!==c||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!==a.verificationResult||t.verification_report===null||o!==null&&s!==null&&(o.implementation_scope===null||s.implementation_scope!==o.implementation_scope||s.partial_allowance!==o.partial_allowance||o.verification_evidence!==null||s.verification_evidence===null))throw new Error("Native transition journal Verify outcome semantics are invalid");return}throw new Error("Native transition journal cannot advance from Archive")}function Z_(e,t){let i=Cs(e);if(dd(i,U_),i.schema!==sr)throw new Error(`Expected Native transition schema ${sr}`);let r=Es(i.minimum_runtime_version,"Native transition minimum_runtime_version");if(r>3)throw new Error(`Native transition requires runtime protocol ${r}; current protocol is ${3}`);if(r!==3)throw new Error(`Native transition ${sr} minimum_runtime_version must be ${3}`);let n=Es(i.revision,"Native transition revision");if(n!==1)throw new Error("Native transition journal revision must be 1");if(i.operation!=="advance"&&i.operation!=="spec-rebase"&&i.operation!=="evidence-retreat"&&i.operation!=="runtime-rebuild")throw new Error("Native transition journal operation is invalid");let a=fd(i,t),o=ni(i.previousState),s=ni(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(hd(o,s,a,i.operation),pd(o,s,a,!1,i.operation),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:sr,minimum_runtime_version:3,revision:n,operation:i.operation,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function eI(e,t){let i=Cs(e);if(dd(i,G_),i.schema!==Cn)throw new Error(`Expected Native transition schema ${Cn}`);let r=fd(i,t,!0),n=lr(i.previousState),a=lr(i.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return hd(n,a,r,gw(n,a,r.eventData),!0),pd(n,a,r,!0),{schema:Cn,id:r.id,change:t,evidenceHash:r.evidenceHash,createdAt:r.createdAt,previousState:n,nextState:a,previousRun:r.previousRun,nextRun:r.nextRun,eventData:r.eventData}}function tI(e,t){let i=Cs(e);if(dd(i,vw),i.schema!==cr)throw new Error(`Expected Native transition schema ${cr}`);if(Es(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${cr} minimum_runtime_version must be 2`);let n=Es(i.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=fd(i,t,!0),o=ur(i.previousState),s=ur(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(hd(o,s,a,gw(o,s,a.eventData),!0),pd(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:cr,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 iI(e,t){let i=Cs(e);if(i.schema===sr)return{status:"current",journal:Z_(i,t)};if(i.schema===Cn)return{status:"migration-required",journal:eI(i,t)};if(i.schema===cr)return{status:"migration-required",journal:tI(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function rI(e,t){let i=ud(e,t),r=ue(e,i);await z(r,i);try{let n=await mt({root:r,file:i,maxBytes:K_,label:`Native transition journal ${t}`});return iI(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function ww(e,t){let i=await rI(e,t);if(!i)return null;if(i.status==="migration-required")throw new cd(t);return i.journal}var nI=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function aI(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function oI(e){return e?e.map(aI).join(" "):null}function sI(e){if(e===null)return null;let t=e.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/gu);return!t||t[0]!=="comet"?null:t.map(i=>{if(i.startsWith('"')&&i.endsWith('"'))try{return JSON.parse(i)}catch{return i.slice(1,-1)}return i.startsWith("'")&&i.endsWith("'")?i.slice(1,-1):i})}function ze(e,t,i,r={}){return{input:e,flags:t,required:r.required??!0,placeholder:i,...r.choices?{choices:r.choices}:{},...r.repeatable?{repeatable:!0}:{},...r.alternativeGroup?{alternativeGroup:r.alternativeGroup}:{}}}function cI(e){return e.map(t=>ze(t,[],null))}function lI(e){let t=["comet","native","next",e.name,"--summary","<summary>"],i=[ze("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),i.push(ze("shared-understanding-confirmation",["--confirmed"],null)),{commandArgs:t,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:i};if(e.phase==="build"){t.push("--artifact","<project-relative-path>"),i.push(ze("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),ze("artifact-or-no-code-reason",["--no-code-reason"],"<reason>",{alternativeGroup:"build-evidence"}));let r=["summary","artifact-or-no-code-reason"];return e.approval!=="confirmed"&&(t.push("--confirmed"),r.push("shared-understanding-confirmation"),i.push(ze("shared-understanding-confirmation",["--confirmed"],null))),{commandArgs:t,requiredInputs:r,inputOptions:i}}return e.phase==="verify"?(t.push("--result","<pass|fail>","--report","<change-relative-path>"),i.push(ze("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),ze("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:i}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function ge(e,t){let i=t.commandArgs===void 0?sI(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?oI(i??null):t.command,commandArgs:i??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??cI(t.requiredInputs??[])}}function xs(e){let i=(e.findings??[]).filter(d=>!wr(d.code)),r=i.find(d=>d.requiresUserDecision),n=i.find(d=>d.repairCommand!==null||nI.test(d.code)),a=i.find(d=>d.code==="repair-iteration-limit"||d.code==="repair-override-exhausted"),o=i.find(d=>d.code==="repair-stagnation-stop"),s=i.find(d=>d.requiredAction==="return-to-bound-working-directory"||d.requiredAction==="repair-workspace-binding"),c=i.find(d=>d.code==="runtime-missing"),l=[...new Set(i.map(d=>d.requiredAction))].sort();if(e.done)return ge(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return ge(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[ze("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(r)return ge(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return ge(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return ge(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return ge(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[ze("summary",["--summary"],"<summary>")]});if(n)return ge(e.state,{disposition:"blocked",action:"repair",command:n.repairCommand,requiredInputs:l});if(e.evidenceRetreat){let d=["comet","native","next",e.state.name,"--summary","<summary>"];return ge(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[ze("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return ge(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(i.length>0)return e.state.phase==="archive"?ge(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?ge(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):ge(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:l});if(e.state.phase==="archive"){if(e.archiveReady&&e.archivePreflightHash){if(!/^[a-f0-9]{64}$/u.test(e.archivePreflightHash))throw new Error("Native Archive continuation preflight must be a SHA-256 hash");let d=["comet","native","archive",e.state.name,"--expect-preflight",e.archivePreflightHash];return e.archiveConfirmation==="required"?(d.push("--confirmed"),ge(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[ze("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):ge(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return ge(e.state,{disposition:e.archiveReady?"continue":"blocked",action:e.archiveReady?"archive":"none",commandArgs:e.archiveReady?["comet","native","archive",e.state.name,"--dry-run"]:null,requiredInputs:e.archiveReady?[]:["archive-readiness"]})}let u=lI(e.state);return ge(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import Yn from"path";var yw=8,uI={"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 dI(e){let t=uI[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"}:wr(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 fI(e,t,i){if(!i.path)return null;let r;if(Yn.isAbsolute(i.path)?r=Yn.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?r=Yn.resolve(me(e,t.name),...i.path.split(/[\\/]/u)):r=Yn.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!V(e.projectRoot,r))return null;let n=Yn.relative(e.projectRoot,r).replaceAll("\\","/");return n===""?".":n}function pI(e,t,i){return e==="next"?`comet native next ${t.name} --summary "<summary>"${i==="contract-changed-after-approval"||i==="shape-confirmation-required"||i==="approval-confirmation-required"?" --confirmed":""}`:e==="status"?`comet native status ${t.name} --details`:null}function md(e){return e.findings.map(t=>{let i=dI(t.code);return{code:t.code,message:t.message,severity:i.severity,path:fI(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:pI(i.retry,e.state,t.code),repairCommand:i.repair==="doctor"?`comet native doctor ${e.state.name} --repair${t.code.startsWith("transition-")?" --strategy continue":""}`:null,requiresUserDecision:t.code==="brief-blocking-question"||t.code==="shape-confirmation-required"||t.code==="approval-confirmation-required"||t.code==="contract-changed-after-approval"||t.code==="verification-scope-partial"||t.code==="repair-iteration-limit"||t.code==="repair-override-exhausted"}}).sort((t,i)=>{let r={error:0,warning:1,info:2};return r[t.severity]-r[i.severity]||t.code.localeCompare(i.code)||(t.path??"").localeCompare(i.path??"")||t.message.localeCompare(i.message)})}function vd(e){let t=[...new Set(e.map(i=>i.code))];return{total:e.length,errors:e.filter(i=>i.severity==="error").length,warnings:e.filter(i=>i.severity==="warning").length,info:e.filter(i=>i.severity==="info").length,requiresUserDecision:e.some(i=>i.requiresUserDecision),codes:t.slice(0,yw),truncated:t.length>yw}}import Cr from"path";var di={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},xr=/^[a-f0-9]{64}$/u;function Ps(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Rs(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function ui(e,t,i=2e3){if(typeof e!="string"||e.length===0||e.length>i)throw new Error(`${t} must be a non-empty string of at most ${i} characters`);return e}function Nw(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function gd(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function hI(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||Cr.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=Cr.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function bw(e,t){return Cr.join(U(e,t),"checkpoints","progress.json")}function Xn(e,t){return Cr.join(U(e,t),"checkpoint-journal.json")}function kw(e,t,i){if(!xr.test(i))throw new Error("Native checkpoint manifest hash is invalid");return Cr.join(U(e,t),"checkpoints","manifests",`${i}.json`)}function mI(e){if(!xr.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function wd(e,t,i){let r=await mt({root:e,file:t,maxBytes:di.maxDocumentBytes,label:i});return JSON.parse(r.bytes.toString("utf8"))}function vI(e,t){let i=Ps(e,`checkpoint manifest artifact ${t}`);Rs(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let r=hI(ui(i.path,`checkpoint artifact ${t} path`,4096)),n=ft(r);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${r}`);if(typeof i.hash!="string"||!xr.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:r,hash:i.hash,size:gd(i.size,`checkpoint artifact ${t} size`)}}function yd(e,t){let i=Ps(e,"Native checkpoint manifest");if(Rs(i,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),i.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(i.change!==t)throw new Error("Native checkpoint manifest change mismatch");if(!Array.isArray(i.artifacts))throw new Error("Native checkpoint manifest artifacts must be an array");if(i.artifacts.length>di.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let r=i.artifacts.map(vI),n=[...r].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(r)!==JSON.stringify(n))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(r.map(o=>o.path)).size!==r.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=gd(i.totalBytes,"checkpoint manifest totalBytes");if(r.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");if(a>di.maxTotalBytes)throw new Error("Native checkpoint manifest totalBytes exceeds its budget");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:r,totalBytes:a}}function Sw(e){return K(JSON.stringify(yd(e,e.change)))}function Ew(e,t){let i=Ps(e,"Native progress checkpoint");if(Rs(i,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),i.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(i.change!==t)throw new Error("Native checkpoint change mismatch");let r=i.phase;if(r!=="shape"&&r!=="build"&&r!=="verify"&&r!=="archive")throw new Error("Native checkpoint phase is invalid");let n=Nw(i.previousRevision,"Native checkpoint previousRevision"),a=Nw(i.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=ui(i.manifestHash,"Native checkpoint manifestHash",64);if(!xr.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=mI(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=ui(i.inputHash,"Native checkpoint inputHash",64);if(!xr.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=ui(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=gd(i.artifactCount,"Native checkpoint artifactCount");if(u>di.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=ui(i.summary,"Native checkpoint summary"),f=ui(i.nextAction,"Native checkpoint nextAction");if(We(d)!==d||We(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:ui(i.id,"Native checkpoint id",128),change:t,phase:r,previousRevision:n,stateRevision:a,summary:d,nextAction:f,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function gI(e,t){let i=Ps(e,"Native checkpoint journal");if(Rs(i,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),i.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(i.change!==t)throw new Error("Native checkpoint journal change mismatch");let r=ni(i.previousState),n=ni(i.nextState),a=Ew(i.checkpoint,t),o=yd(i.manifest,t),s=ui(i.inputHash,"Native checkpoint journal inputHash",64),c=K(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!xr.test(s)||s!==a.inputHash||s!==c||i.id!==a.id||i.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(r.name!==t||n.name!==t||n.revision!==r.revision+1||a.previousRevision!==r.revision||a.stateRevision!==n.revision||a.phase!==n.phase||a.manifestHash!==Sw(o)||a.artifactCount!==o.artifacts.length)throw new Error("Native checkpoint journal state mismatch");return{schema:"comet.native.checkpoint-journal.v1",id:a.id,change:t,inputHash:s,createdAt:a.createdAt,previousState:r,nextState:n,checkpoint:a,manifest:o}}async function wI(e,t,i){let r=Cr.resolve(e.projectRoot,...t.split("/"));if(!V(e.projectRoot,r)||V(e.nativeRoot,r)||V(e.runtimeDir,r))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=El(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await mt({root:e.projectRoot,file:r,maxBytes:di.maxFileBytes,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot,e.runtimeDir],hooks:{afterParentChainCaptured:()=>i?.afterParentChainCaptured?.(t),afterOpen:()=>i?.afterOpen?.(t),beforeRead:()=>i?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function yI(e,t){let i=bw(e,t),r=ue(e,i);await z(r,i);try{return Ew(await wd(r,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function NI(e,t,i){let r=kw(e,t,i),n=ue(e,r);await z(n,r);let a=await wd(n,r,"Native checkpoint manifest"),o=yd(a,t);if(Cw(e,o),Sw(o)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function Nd(e,t){let i=Xn(e,t),r=ue(e,i);await z(r,i);try{let n=gI(await wd(r,i,"Native checkpoint journal"),t);return Cw(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}function Cw(e,t){for(let i of t.artifacts){let r=El(e,i.path);if(r)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${r}): ${i.path}`)}}async function xw(e){let t;try{t=await yI(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:bw(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let i=[],r=[];t.stateRevision!==e.stateRevision&&i.push("state-revision-changed");let n=null;try{n=await NI(e.paths,e.name,t.manifestHash);let a=K(JSON.stringify({summary:t.summary,nextAction:t.nextAction,artifacts:n.artifacts}));if(t.inputHash!==a||t.artifactCount!==n.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");for(let o of n.artifacts)try{let s=await wI(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&i.push(`artifact-changed:${o.path}`)}catch{i.push(`artifact-unavailable:${o.path}`)}}catch(a){i.push("checkpoint-manifest-invalid"),r.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:kw(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:i.length===0?"fresh":"stale",reasons:i,findings:r}}var Pw=240,Rw=8,As=50;function Aw(e){let t=Array.from(e);return t.length<=Pw?e:`${t.slice(0,Pw-1).join("")}…`}function bI(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function kI(e){let t=[...new Set(e.map(bI))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,Rw),reasonCount:e.length,codesTruncated:t.length>Rw};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,As),reasonsTruncated:e.length>As}}}async function _w(e){let t=null;try{let s=await Nd(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:Xn(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:Xn(e.paths,e.state.name)}}let i=await xw({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),r=t?[t.code,...i.reasons]:i.reasons,n=kI(r);if(!i.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:di.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:Aw(i.checkpoint.summary),nextAction:Aw(i.checkpoint.nextAction),artifactCount:i.checkpoint.artifactCount},o=i.manifest?{...a,summary:i.checkpoint.summary,nextAction:i.checkpoint.nextAction,manifestHash:i.checkpoint.manifestHash,manifestRef:i.checkpoint.manifestRef,artifacts:i.manifest.artifacts,totalBytes:i.manifest.totalBytes}:null;return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:di.maxArtifacts}}import{promises as lj}from"node:fs";import uy from"node:path";import Iw from"node:path";var SI="comet.native.archive-preflight.v1",EI="comet.native.archive-preflight.v1",CI="comet.native.archive-operation.v1",xI=/^[a-f0-9]{64}$/u,Tw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,PI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function _s(e,t){return e<t?-1:e>t?1:0}function RI(e,t){if(typeof e!="string"||!xI.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ht(e,t){return e===null?null:RI(e,t)}function AI(e,t){let i=Iw.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||Iw.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized Native-relative ref`);return e}function _I(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function II(e){if(e==null)return null;if(e.schema!=="comet.native.workspace.v3")throw new Error("Native archive workspace schema is invalid");if(e.isolation!=="current"&&e.isolation!=="branch"&&e.isolation!=="worktree")throw new Error("Native archive workspace isolation is invalid");for(let[t,i]of[["change",e.changeBranch],["target",e.targetBranch]])if(i!==null&&(i.length===0||i.trim()!==i||Array.from(i).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})))throw new Error(`Native archive workspace ${t} branch is invalid`);if(e.finish!==null&&e.finish!=="merge"&&e.finish!=="push"&&e.finish!=="pull-request"&&e.finish!=="keep")throw new Error("Native archive workspace finish is invalid");if((e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null||e.finish===null))throw new Error("Native isolated archive workspace requires branches and a finish action");if(e.isolation==="current"&&e.finish!==null)throw new Error("Native current archive workspace cannot have a finish action");return{...e}}function TI(e,t){if(!Tw.test(e.capability))throw new Error(`Native archive spec ${t} capability is invalid`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Native archive spec ${e.capability} operation is invalid`);let i=Ht(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),r=Ht(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=Ht(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&i!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&i===null)throw new Error(`Native archive ${e.operation} ${e.capability} requires a base hash`);if(e.operation==="remove"!=(n===null))throw new Error(`Native archive ${e.operation} ${e.capability} proposed hash is invalid`);return{capability:e.capability,operation:e.operation,expectedBaseHash:i,actualBaseHash:r,proposedHash:n}}function jI(e){if(e.result!=="pending"&&e.result!=="pass"&&e.result!=="fail")throw new Error("Native archive verification result is invalid");if(!["missing","invalid","stale","complete","partial"].includes(e.freshness))throw new Error("Native archive verification freshness is invalid");if(!Number.isSafeInteger(e.skippedAcceptanceCount)||e.skippedAcceptanceCount<0)throw new Error("Native archive skipped acceptance count is invalid");let t={result:e.result,freshness:e.freshness,contractHash:Ht(e.contractHash,"Native archive contract hash"),acceptanceHash:Ht(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:Ht(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:Ht(e.reportHash,"Native archive report hash"),envelopeHash:Ht(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:Ht(e.partialAllowanceHash,"Native archive partial allowance hash"),skippedAcceptanceCount:e.skippedAcceptanceCount};if((e.freshness==="complete"||e.freshness==="partial")&&[t.contractHash,t.acceptanceHash,t.implementationScopeHash,t.reportHash,t.envelopeHash].some(i=>i===null))throw new Error("Fresh Native archive evidence requires every bound content hash");if(e.freshness==="partial"&&t.partialAllowanceHash===null||e.freshness==="complete"&&t.partialAllowanceHash!==null)throw new Error("Native archive partial evidence allowance state is invalid");return t}function $I(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(r=>{if(typeof r!="string"||!PI.test(r))throw new Error(`Native archive preflight finding code is invalid: ${String(r)}`);return r}),i=[...new Set(t)].sort(_s);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function OI(e){let t=[];e.phase!=="archive"&&t.push("archive-phase-required"),e.archived&&t.push("change-already-archived"),e.pendingJournal&&t.push("pending-journal"),e.targetExists&&t.push("archive-target-exists"),e.evidence.result!=="pass"&&t.push("verification-not-passed"),e.evidence.freshness==="missing"&&t.push("verification-evidence-missing"),e.evidence.freshness==="invalid"&&t.push("verification-evidence-invalid"),e.evidence.freshness==="stale"&&t.push("verification-evidence-stale"),e.evidence.skippedAcceptanceCount>0&&t.push("verification-acceptance-skipped");for(let i of e.specs)i.actualBaseHash!==i.expectedBaseHash&&t.push("spec-base-conflict");return[...new Set(t)].sort(_s)}function jw(e){if(!Tw.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(TI).sort((l,u)=>_s(l.capability,u.capability));if(new Set(t.map(l=>l.capability)).size!==t.length)throw new Error("Native archive preflight contains duplicate capabilities");let i=t.map(l=>({...l,operationHash:H(CI,l)})),r=jI(e.evidence),n=II(e.workspace),a=[...new Set([...$I(e.findingCodes??[]),...OI({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:r})])].sort(_s),o=_I(e.revision),s=AI(e.targetRef,"Native archive target");if(e.archiveConfirmation!=="automatic"&&e.archiveConfirmation!=="required")throw new Error("Native archive confirmation must be automatic or required");let c={stateSchema:e.stateSchema,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetRef:s,targetExists:e.targetExists,operations:i,evidence:r,workspace:n,findingCodes:a};return{schema:SI,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:r.freshness,operationCount:i.length,operations:i,workspace:n,findingCodes:a,preflightHash:H(EI,c)}}import{createHash as HI}from"node:crypto";import $w from"node:path";var DI="comet.native.conflict-radar.v1",xe=Object.freeze({maxChanges:32,maxSpecsPerChange:64,maxArtifactsPerChange:128,maxTotalSpecs:512,maxTotalArtifacts:1024,maxSignalsPerRelationship:8,maxRelationships:256,maxSerializedBytes:64*1024,maxNameBytes:128,maxCapabilityBytes:128,maxArtifactPathBytes:512}),BI="comet.native.conflict-radar.v1",LI="comet.native.conflict-radar-signals.v1",VI=/^[a-f0-9]{64}$/u,Dw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,FI=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),qI=new Set(["capability","operation","baseHash"]),MI=new Set(["path","kind"]);function Pr(e,t){return e<t?-1:e>t?1:0}function bd(e){return Buffer.byteLength(e,"utf8")}function kd(e,t,i){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${i} must be an object`);let r=e,n=Object.keys(r).filter(a=>!t.has(a));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);return r}function Sd(e,t,i){if(typeof e!="string"||e.length===0||e!==e.trim())throw new Error(`${t} must be a non-empty trimmed string`);if(bd(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function WI(e,t){let i=Sd(e,t,xe.maxArtifactPathBytes),r=$w.posix.normalize(i);if(i.includes("\\")||Array.from(i).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(i)||$w.posix.isAbsolute(r)||i.split("/").includes("..")||r!==i||r==="."||i.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return i}function Bw(e,t){if(typeof e!="string"||!VI.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function zI(e,t){let i=kd(e,qI,t),r=Sd(i.capability,`${t} capability`,xe.maxCapabilityBytes);if(!Dw.test(r))throw new Error(`${t} capability is invalid`);if(i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`${t} operation is invalid`);let n=i.baseHash===null?null:Bw(i.baseHash,`${t} canonical base hash`);if(i.operation==="create"&&n!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(i.operation!=="create"&&n===null)throw new Error(`${t} ${i.operation} operation requires a canonical base hash`);return{capability:r,operation:i.operation,baseHash:n}}function JI(e,t){let i=kd(e,MI,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:WI(i.path,`${t} path`),kind:i.kind}}function GI(e,t){let i=kd(e,FI,`Conflict radar change ${t}`),r=Sd(i.name,`Conflict radar change ${t} name`,xe.maxNameBytes);if(!Dw.test(r))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(i.revision)||i.revision<1)throw new Error(`Conflict radar change ${r} revision must be a positive safe integer`);if(!Array.isArray(i.specs))throw new Error(`Conflict radar change ${r} specs must be an array`);if(i.specs.length>xe.maxSpecsPerChange)throw new Error(`Conflict radar change ${r} exceeds the spec budget`);if(!Array.isArray(i.declaredArtifacts))throw new Error(`Conflict radar change ${r} declared artifacts must be an array`);if(i.declaredArtifacts.length>xe.maxArtifactsPerChange)throw new Error(`Conflict radar change ${r} exceeds the declared artifact budget`);let n=i.specs.map((c,l)=>zI(c,`Conflict radar change ${r} spec ${l}`)).sort((c,l)=>Pr(c.capability,l.capability));if(new Set(n.map(c=>c.capability)).size!==n.length)throw new Error(`Conflict radar change ${r} has duplicate capabilities`);let a=i.declaredArtifacts.map((c,l)=>JI(c,`Conflict radar change ${r} artifact ${l}`)).sort((c,l)=>Pr(c.path,l.path)||Pr(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${r} has duplicate or conflicting artifact paths`);let s=i.workspaceIdentityHash===void 0||i.workspaceIdentityHash===null?null:Bw(i.workspaceIdentityHash,`Conflict radar change ${r} workspace identity hash`);return{name:r,revision:i.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function UI(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>xe.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(GI).sort((n,a)=>Pr(n.name,a.name));if(new Set(t.map(n=>n.name)).size!==t.length)throw new Error("Native conflict radar contains duplicate change names");if(t.reduce((n,a)=>n+a.specs.length,0)>xe.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>xe.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function KI(e,t){let i=e.baseHash!==null&&e.baseHash===t.baseHash;return{kind:"capability",certainty:e.operation==="create"||t.operation==="create"||i?"definite-conflict":"possible-overlap",capability:e.capability,leftOperation:e.operation,rightOperation:t.operation,leftBaseHash:e.baseHash,rightBaseHash:t.baseHash}}function YI(e,t){let i=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),r=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),n=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!i&&!r&&!n?null:{kind:"artifact",certainty:n?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function XI(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function QI(e,t){let i=[],r=HI("sha256").update(`${LI}
174
+ [`),n=0,a=!1,o=l=>{n>0&&r.update(","),r.update(Nn(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),i.length<xe.maxSignalsPerRelationship&&i.push(l)},s=new Map(t.specs.map(l=>[l.capability,l]));for(let l of e.specs){let u=s.get(l.capability);u&&o(KI(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=YI(l,u);d&&o(d)}let c=a?"definite-conflict":n>0?"possible-overlap":"disjoint";return r.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:XI(e,t),signalCount:n,signalHash:r.digest("hex"),signals:i,signalsTruncated:i.length!==n}}function Ow(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function ZI(e,t){return Ow(e.classification)-Ow(t.classification)||Pr(e.left,t.left)||Pr(e.right,t.right)}function Hw(e,t,i,r){let n={definiteConflict:t.filter(({classification:a})=>a==="definite-conflict").length,possibleOverlap:t.filter(({classification:a})=>a==="possible-overlap").length,disjoint:t.filter(({classification:a})=>a==="disjoint").length};return{schema:DI,workspaceIdentityAdvisoryOnly:!0,changeCount:e.length,relationshipCount:t.length,counts:n,relationships:i,relationshipsTruncated:i.length!==t.length,omittedRelationshipCount:t.length-i.length,radarHash:r}}function Lw(e){let t=UI(e),i=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)i.push(QI(t[s],t[c]));i.sort(ZI);let r=i.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=H(BI,{changes:t,relationships:r}),a=i.slice(0,xe.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=Hw(t,i,a,n);for(;a.length>0&&bd(JSON.stringify(o))>xe.maxSerializedBytes;)a=a.slice(0,-1),o=Hw(t,i,a,n);if(bd(JSON.stringify(o))>xe.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as TT}from"node:crypto";import{promises as ct}from"node:fs";import bt from"node:path";import Vw from"node:path";var Fw="comet.native.check-receipt.v1",eT="comet.native.check-receipt.v1",Rr="scoped-text-safety",Ed=1,Pe=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),tT=/^[a-f0-9]{64}$/u,iT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,rT="comet.native.checker-policy.v1",nT="comet.native.check-input.v1",aT=2048,qw=H(rT,{policy:Rr,version:Ed,limits:Pe,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),oT=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),Mw=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],zw=["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"],sT=new Set(zw);function fi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function pi(e,t,i,r=[]){let n=new Set([...t,...r]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${i} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${i} is missing field(s): ${o.join(", ")}`)}function Dt(e,t){if(typeof e!="string"||!tT.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Oe(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Jw(e,t){let i=Oe(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function Ww(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(!Number.isFinite(i.getTime())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function cT(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>aT||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a bounded normalized project-relative path`);let i=Vw.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||Vw.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function lT(e){let t=fi(e,"Native check receipt checker");pi(t,["policy","version","hash","limits"],"Native check receipt checker");let i=fi(t.limits,"Native check receipt limits");if(pi(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==Rr||t.version!==Ed||t.hash!==qw||i.maxFiles!==Pe.maxFiles||i.maxFileBytes!==Pe.maxFileBytes||i.maxTotalBytes!==Pe.maxTotalBytes||i.maxIssues!==Pe.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:Rr,version:Ed,hash:qw,limits:{...Pe}}}function uT(e){let t=fi(e,"Native check receipt contract");return pi(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:Dt(t.expectedHash,"Native check expected contract hash"),beforeHash:Dt(t.beforeHash,"Native check before contract hash"),afterHash:Dt(t.afterHash,"Native check after contract hash")}}function dT(e){let t=fi(e,"Native check receipt implementation");return pi(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:Dt(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:Dt(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:Dt(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:Dt(t.afterSnapshotHash,"Native check after snapshot hash")}}function fT(e,t){let i=fi(e,`Native check batch ${t}`);pi(i,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let r={filesSelected:Oe(i.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:Oe(i.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:Oe(i.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:Oe(i.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:Oe(i.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:Oe(i.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(r.filesSelected>Pe.maxFiles||r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.bytesScanned>Pe.maxTotalBytes||r.recordedIssueCount>r.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return r}function pT(e){let t=fi(e,"Native check receipt counts");pi(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let i={filesSelected:Oe(t.filesSelected,"Native check filesSelected"),filesScanned:Oe(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:Oe(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:Oe(t.bytesScanned,"Native check bytesScanned"),issueCount:Oe(t.issueCount,"Native check issueCount"),recordedIssueCount:Oe(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(fT):(()=>{throw new Error("Native check receipt batches must be an array")})()}},r=i.batches;if(r!==void 0){if(r.length===0)throw new Error("Native check receipt batches must not be empty");let n=r.reduce((a,o)=>({filesSelected:a.filesSelected+o.filesSelected,filesScanned:a.filesScanned+o.filesScanned,binaryFilesSkipped:a.binaryFilesSkipped+o.binaryFilesSkipped,bytesScanned:a.bytesScanned+o.bytesScanned,issueCount:a.issueCount+o.issueCount,recordedIssueCount:a.recordedIssueCount+o.recordedIssueCount}),{filesSelected:0,filesScanned:0,binaryFilesSkipped:0,bytesScanned:0,issueCount:0,recordedIssueCount:0});if(JSON.stringify(n)!==JSON.stringify({...i,batches:void 0}))throw new Error("Native check receipt batch totals are inconsistent")}if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>Pe.maxIssues||r===void 0&&(i.filesScanned+i.binaryFilesSkipped>Pe.maxFiles||i.bytesScanned>Pe.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return i}function hT(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||Mw.indexOf(e.kind)-Mw.indexOf(t.kind)}function mT(e){if(!Array.isArray(e)||e.length>Pe.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((r,n)=>{let a=fi(r,`Native check issue ${n}`);if(pi(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!oT.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:cT(a.path,`Native check issue ${n} path`),line:Jw(a.line,`Native check issue ${n} line`),kind:a.kind}}),i=[...t].sort(hT);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function vT(e){if(!Array.isArray(e)||e.some(r=>typeof r!="string"||!sT.has(r)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=zw.filter(r=>t.includes(r));if(new Set(t).size!==t.length||JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function gT(e){return H(nT,e)}function Gw(e){let t=fi(e,"Native check receipt");if(pi(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==Fw)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!iT.test(t.change))throw new Error("Native check receipt change name is invalid");let i=Jw(t.sourceRevision,"Native check source revision"),r=lT(t.checker),n=uT(t.contract),a=dT(t.implementation),o=gT({change:t.change,sourceRevision:i,checkerHash:r.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(Dt(t.inputHash,"Native check input hash")!==o)throw new Error("Native check receipt input hash mismatch");if(t.status!=="passed"&&t.status!=="failed")throw new Error("Native check receipt status is invalid");let s=Ww(t.startedAt,"Native check receipt startedAt"),c=Ww(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=pT(t.counts),u=mT(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=vT(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let f=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==f)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.batches===void 0&&l.filesSelected>Pe.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.batches===void 0&&l.filesSelected>Pe.maxFiles&&!u.some(h=>h.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let p={schema:Fw,change:t.change,sourceRevision:i,checker:r,inputHash:o,status:t.status,startedAt:s,endedAt:c,contract:n,implementation:a,counts:l,issues:u,issuesTruncated:t.issuesTruncated,stale:t.stale,staleReasons:d},v=Dt(t.receiptHash,"Native check receipt content hash");if(H(eT,p)!==v)throw new Error("Native check receipt content hash mismatch");return{...p,receiptHash:v}}var xd="comet.native.verification-receipt.v3",wT=xd,yT="comet.native.declared-artifacts.v1",NT=/^[a-f0-9]{64}$/u,bT=/^acceptance-[a-f0-9]{64}$/u,kT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ST=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,ET=4096,CT=256,xT=1024;function Ar(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function hi(e,t,i){let r=Object.keys(e).sort(),n=[...t].sort();if(r.length!==n.length||r.some((a,o)=>a!==n[o]))throw new Error(`${i} fields are invalid`)}function Bt(e,t){if(typeof e!="string"||!NT.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function st(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=We(e).trim();if(!i||i.length>ET||i!==e.trim())throw new Error(`${t} is invalid`);return i}function Cd(e,t){let i=st(e,t),r=new Date(i);if(Number.isNaN(r.getTime())||r.toISOString()!==i)throw new Error(`${t} must be a canonical timestamp`);return i}function Qn(e,t,i=st,r=!1,n=CT){if(!Array.isArray(e)||e.length>n||!r&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>i(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function PT(e,t){if(typeof e!="string"||!bT.test(e))throw new Error(`${t} is invalid`);return e}function RT(e){let t=Ar(e,"Native verification receipt bindings");if(hi(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!kT.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:Bt(t.contractHash,"Native verification receipt contract hash"),scopeHash:Bt(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:Bt(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:Bt(t.artifactHash,"Native verification receipt artifact hash")}}function AT(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=ST.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function _T(e,t,i,r){let n=Ar(t,`Native ${e} evidence`);if(e==="automated-check"){if(hi(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=Cd(n.startedAt,"Native automated-check start time"),o=Cd(n.endedAt,"Native automated-check end time");if(Date.parse(o)<Date.parse(a))throw new Error("Native automated-check time range is invalid");if(i==="passed"&&n.exitCode!==0||i==="failed"&&n.exitCode===0||i==="passed"&&(n.timedOut||n.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=Ar(n.worktree,"Native automated-check worktree");if(hi(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=Ar(n.afterFence,"Native automated-check after fence");if(hi(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(i==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:st(n.executable,"Native automated-check executable"),args:Qn(n.args,"Native automated-check arguments",st,!0),cwd:st(n.cwd,"Native automated-check cwd"),exitCode:n.exitCode,signal:n.signal,timedOut:n.timedOut,timeoutMs:n.timeoutMs,startedAt:a,endedAt:o,worktree:{provider:s.provider,root:st(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:Bt(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:Bt(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:Bt(n.outputHash,"Native automated-check output hash"),outputSummary:st(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){hi(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=AT(n.checkReceiptRef);if(Bt(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:Qn(n.subjects,"Native static inspection subjects",st,r==="required-check"),rule:st(n.rule,"Native static inspection rule"),resultSummary:st(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return hi(n,["steps","observations"],"Native manual-evidence evidence"),{steps:Qn(n.steps,"Native manual evidence steps"),observations:Qn(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function IT(e){let t=Ar(e,"Native verification receipt");if(hi(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence"],"Native verification receipt input"),!["automated-check","static-inspection","manual-evidence"].includes(t.kind)||t.role!=="required-check"&&t.role!=="acceptance-evidence"||!["passed","failed","skipped","blocked"].includes(t.status))throw new Error("Native verification receipt kind or status is invalid");let i=t.kind,r=t.role,n=t.status,a=st(t.actor,"Native verification receipt actor"),o=Qn(t.acceptanceIds,"Native receipt acceptance IDs",PT,r==="required-check",xT).sort();if(r==="required-check"&&o.length!==0||r==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(r==="required-check"&&i!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:xd,kind:i,role:r,status:n,bindings:RT(t.bindings),acceptanceIds:o,actor:a,issuedAt:Cd(t.issuedAt,"Native verification receipt issue time"),evidence:_T(i,t.evidence,n,r)};if(r==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==Rr||s.actor!==`native-runtime:${Rr}`))throw new Error("Native required check policy identity is invalid");return s}function Uw(e){let t=Ar(e,"Native verification receipt");if(hi(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==xd)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...r}=t,n=IT(r),a=Bt(t.receiptHash,"Native verification receipt hash");if(H(wT,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function Pd(e){return H(yT,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}var Qw=/^[a-f0-9]{64}$/u,_r=Hi,nM=3*_r;function Rd(e,t){let i=bt.relative(e,t);return i===""||!bt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${bt.sep}`)}function jT(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Is(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return _e(i,r)?q(i,r):q(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Kw(e){let t=await ct.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await ct.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function $T(e,t){let i=bt.resolve(e),r=bt.resolve(t);if(!Rd(i,r))throw new Error("Native evidence path is outside its change");let n=[await Kw(i)],a=i;for(let o of bt.relative(i,r).split(bt.sep).filter(Boolean)){a=bt.join(a,o);let s=await Kw(a);if(!Rd(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function Yw(e){for(let t of e){let i=await ct.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!jT(t,i)||await ct.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function OT(e,t,i={}){let r=await $T(t,bt.dirname(e));await i.afterParentChainCaptured?.();let n=await ct.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await ct.realpath(e);if(!Rd(r[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await ct.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),ct.lstat(e),ct.realpath(e)]);if(await Yw(r),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!Is(s,n)||!Is(s,c))throw new Error("Native evidence document changed while opening");if(s.size>_r)throw new Error(`Native evidence document exceeds ${_r} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let m=_r+1-d,S=await o.read(f,0,Math.min(f.length,m),null);if(S.bytesRead===0)break;if(d+=S.bytesRead,d>_r)throw new Error(`Native evidence document exceeds ${_r} bytes`);u.push(Buffer.from(f.subarray(0,S.bytesRead)))}await i.beforeFinalCheck?.();let[p,v,h]=await Promise.all([o.stat(),ct.lstat(e),ct.realpath(e)]);if(await Yw(r),!v.isFile()||v.isSymbolicLink()||h!==a||!Is(s,p)||!Is(s,v))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function Zw(e,t){if(!Qw.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}async function HT(e,t,i,r,n){if(!Qw.test(i))throw new Error("Native report evidence hash is invalid");let a=await Di({paths:e,name:t,kind:"reports",hash:i,hooks:r,changeDir:n});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==i||typeof o.content!="string"||TT("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==i)throw new Error("Native report evidence does not match its hash");return o.content}function Ir(e,t){let i=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!i||i[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return i[2]}function DT(e,t,i,r,n){let a=Zw(i,r);return n?bt.join(n,...a.split("/")):ri(U(e,t),a)}async function Di(e){let t=DT(e.paths,e.name,e.kind,e.hash,e.changeDir),i=e.changeDir??ue(e.paths,t);return await z(i,t),OT(t,i,e.hooks)}function Xw(e,t){return ys(e,t)}function BT(e,t){let i=Ns(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function LT(e,t,i){let r=ew(e);if(r.change!==t||r.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return r}function VT(e,t,i){let r=ed(e);if(r.change!==t||r.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return r}async function FT(e,t,i,r=!1,n){let a=await Ts(e,t,i.implementationScopeRef,void 0,n);if(r&&await HT(e,t,i.reportHash,void 0,n),a.scopeHash!==i.implementationScopeHash||a.contractHash!==i.contractHash||(a.complete?"complete":"partial")!==i.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(i.partialAllowanceRef===null)return;let o=await ey(e,t,i.partialAllowanceRef,void 0,n);if(o.allowanceHash!==i.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=i.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function Zn(e,t,i,r,n){let a=Ir(i,"scopes"),o=BT(await Di({paths:e,name:t,kind:"scopes",hash:a,hooks:r,changeDir:n}),a),s=Ir(o.baselineProjectionRef,"snapshots"),c=Ir(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([Di({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>Xw(d,s)),Di({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>Xw(d,c))]);return Gg({baseline:l,current:u,scope:o})}async function Ts(e,t,i,r,n){return(await Zn(e,t,i,r,n)).scope}async function ey(e,t,i,r,n){let a=Ir(i,"allowances");return LT(await Di({paths:e,name:t,kind:"allowances",hash:a,hooks:r,changeDir:n}),t,a)}async function ea(e,t,i,r,n){let a=Ir(i,"receipts"),o=Uw(await Di({paths:e,name:t,kind:"receipts",hash:a,hooks:r,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function Tr(e,t,i,r,n){let a=Ir(i,"verifications"),o=VT(await Di({paths:e,name:t,kind:"verifications",hash:a,hooks:r,changeDir:n}),t,a);return await FT(e,t,o,!1,n),o}var qT=4096;async function MT(e,t=xe.maxChanges){try{let i=await xn({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:t});return await i.verify(),i.entries}catch(i){if(i.code==="ENOENT")return[];throw i}}async function ty(e,t){let i=await gt(e,t),[r,n]=await Promise.all([i.implementation_scope?Ts(e,t,i.implementation_scope):null,jt(e,t).catch(()=>null)]);return{name:i.name,revision:i.revision,specs:i.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:r?.declaredArtifacts??[],workspaceIdentityHash:n?.nativeRootId??null}}async function js(e,t,i={}){let n=(await MT(e,qT)).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 ty(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await ty(e,c).catch(d=>{if(i.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=Lw([a,l]).relationships[0];u.classification==="definite-conflict"&&(o+=1),u.classification==="possible-overlap"&&(s+=1)}return{definiteConflictCount:o,possibleOverlapCount:s,findingCodes:[...o>0?["native-change-conflict"]:[],...s>0?["native-change-overlap"]:[]]}}import{execFile as ej}from"node:child_process";import{promisify as tj}from"node:util";import{constants as Ad,promises as Je}from"node:fs";import jr from"node:path";var zT=/^[a-f0-9]{64}$/u,JT=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,ta=512*1024;function GT(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function $s(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return _e(i,r)?q(i,r):q(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function UT(e,t){let i=jr.resolve(e),r=jr.resolve(t);if(!V(i,r))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=i;for(let o of["",...jr.relative(i,r).split(jr.sep).filter(Boolean)]){o&&(a=jr.join(a,o));let s=await Je.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await Je.realpath(a);if(n.length>0&&!V(n[0].realPath,c))throw new Error("Native check receipt parent resolves outside the Native root");n.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs})}return n}async function ry(e){for(let t of e){let i=await Je.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!GT(t,i)||await Je.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function KT(e){if(!zT.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function YT(e){let t=JT.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function XT(e,t,i){return ri(U(e,t),KT(i))}async function QT(e,t,i){let r=await UT(i,jr.dirname(e)),n=await Je.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(n.size>ta)throw new Error(`Native check receipt exceeds ${ta} bytes`);let[a,o]=await Promise.all([Je.realpath(t),Je.realpath(e)]);if(!V(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":Ad.O_RDONLY|Ad.O_NOFOLLOW|Ad.O_NONBLOCK,c=await Je.open(e,s).catch(l=>{throw l.code==="ELOOP"||l.code==="ENXIO"?new Error("Native check receipt became unsafe while opening"):l});try{let[l,u,d]=await Promise.all([c.stat(),Je.lstat(e),Je.realpath(e)]);if(await ry(r),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!$s(n,l)||!$s(l,u))throw new Error("Native check receipt changed while opening");let f=[],p=0,v=Buffer.allocUnsafe(16*1024);for(;;){let y=ta+1-p,k=await c.read(v,0,Math.min(v.length,y),null);if(k.bytesRead===0)break;if(p+=k.bytesRead,p>ta)throw new Error(`Native check receipt exceeds ${ta} bytes`);f.push(Buffer.from(v.subarray(0,k.bytesRead)))}let[h,m,S]=await Promise.all([c.stat(),Je.lstat(e),Je.realpath(e)]);if(await ry(r),!m.isFile()||m.isSymbolicLink()||S!==o||!V(a,S)||!$s(l,h)||!$s(l,m))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,p).toString("utf8"))}finally{await c.close()}}async function ny(e,t,i){let r=YT(i),n=U(e,t),a=XT(e,t,r),o=ue(e,a);await z(o,a);let s=Gw(await QT(a,n,o));if(s.change!==t||s.receiptHash!==r)throw new Error("Native check receipt ref/hash/change mismatch");return s}var ia=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var XM=64*1024;var QM=3600*1e3;var ZM=tj(ej);var ij=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function ay(e,t){let i=[];for(let r of ij){let n=e.bindings[r],a=t[r];n!==a&&i.push(`${r}: expected ${JSON.stringify(a)}, got ${JSON.stringify(n)}`)}return{ok:i.length===0,mismatches:i}}async function oy(e){if(e.receipt.kind!=="static-inspection")return null;let t=await ny(e.paths,e.state.name,e.receipt.evidence.checkReceiptRef);if(t.receiptHash!==e.receipt.evidence.checkReceiptHash)throw new Error("Native static receipt dependency hash mismatch");return t}var mi=class extends Error{details;constructor(t){let i=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(r=>`${r.ref}${r.acceptanceId?`[${r.acceptanceId}]`:""} -> ${r.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=t}};function rj(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 nj(e){let t=rj(e.bundle.baseline),i=await fu(e.paths,t,{origin:"explicit",now:e.now});return Yu({baseline:t,current:i,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason,externalDrift:e.bundle.authority.externalDrift}).scope.currentProjectionHash}async function cy(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await Zn(e.paths,e.state.name,e.state.implementation_scope),i=await yr({changeDir:me(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),r=await nj({paths:e.paths,bundle:t,now:e.now}),n=[];return i.contract.contractHash!==t.scope.contractHash&&n.push("verification-contract-stale"),r!==t.scope.currentProjectionHash&&n.push("verification-implementation-stale"),{bundle:t,contract:i.contract,contractHash:i.contract.contractHash,acceptanceHash:i.contract.acceptanceHash,findingCodes:n}}async function ly(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await cy(e),i=[...new Set(t.findingCodes)].sort();return{freshness:i.length===0?"fresh":"stale",findingCodes:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"]}}}async function aj(e){let t=await re({root:me(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:km(t.text)}}function oj(e){let{receipt:t,implementationScope:i}=e,r=[],n=Ku({baseline:i.baseline,current:i.current,declaredArtifacts:i.scope.declaredArtifacts}).filter(o=>o.attributedTo.length>0&&o.after!==null),a=n.reduce((o,s)=>o+s.after.size,0);return(t.stale||t.sourceRevision!==e.sourceRevision||t.contract.expectedHash!==e.contractHash||t.contract.beforeHash!==e.contractHash||t.contract.afterHash!==e.contractHash||t.implementation.scopeHash!==i.scope.scopeHash||t.implementation.expectedSnapshotHash!==i.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==i.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==i.scope.currentProjectionHash||t.counts.filesSelected!==n.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==n.length||t.counts.bytesScanned!==a))&&r.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&r.push("verification-receipt-outcome-mismatch"),r}function sj(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:Pd(e.implementationScope.scope.declaredArtifacts)}}async function sy(e){let t=await ea(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let r=ay(t,e.expectedBindings);if(i.push(...r.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&i.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),i.length>0)throw new mi([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:i}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let n=await oy({paths:e.paths,state:e.state,receipt:t});if(n){let a=oj({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 cj(e){let t=sj({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let r of e.requiredReceiptRefs){let n=await sy({...e,ref:r,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof mi)return i.push(...a.details),null;throw a});if(n!==null&&n.kind!=="static-inspection")throw new Error("Native required-check evidence must be a static-inspection receipt")}for(let r of e.trace.entries)if(r.status!=="missing")for(let n of r.evidenceRefs){let a=await sy({...e,result:r.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:r.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof mi)return i.push(...o.details),null;throw o});if(a!==null){if(a.kind!=="automated-check"&&a.kind!=="manual-evidence")throw new Error("Native acceptance evidence must be automated-check or manual-evidence");if(r.status==="failed"&&a.status==="passed")throw new Error("Native failed acceptance evidence must reference a non-passing receipt")}}if(i.length>0)throw new mi(i)}function _d(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function Id(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:_d(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([cy(e),Tr(e.paths,e.state.name,e.state.verification_evidence)]);if(i.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:_d(e.state.verification_result,"stale"),envelope:null};let r=await aj({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),n=[...t.findingCodes];(r.hash!==i.reportHash||r.ref!==i.reportRef)&&n.push("verification-report-stale"),(i.result!==e.state.verification_result||i.implementationScopeRef!==e.state.implementation_scope||i.partialAllowanceRef!==e.state.partial_allowance||i.sourceRevision>=e.state.revision||i.contractHash!==t.bundle.scope.contractHash||i.acceptanceCriteriaHash!==t.acceptanceHash)&&n.push("verification-state-mismatch");try{await cj({paths:e.paths,state:e.state,result:i.result,trace:i.acceptanceTrace,requiredReceiptRefs:i.requiredReceiptRefs,contractHash:i.contractHash,implementationScope:t.bundle,sourceRevision:i.sourceRevision})}catch{n.push("verification-receipt-invalid")}let a=[...new Set(n)].sort(),o=a.length>0?"stale":i.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:i.contractHash,acceptanceHash:i.acceptanceCriteriaHash,implementationScopeHash:i.implementationScopeHash,reportHash:i.reportHash,envelopeHash:i.envelopeHash,partialAllowanceHash:i.partialAllowanceHash,skippedAcceptanceCount:i.acceptanceTrace.skipped},envelope:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:_d(e.state.verification_result,"invalid"),envelope:null}}}function uj(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function dy(e){try{return await lj.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function dj(e,t){try{return(await re({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function fj(e,t,i){let r=as(e,i.capability);if(!V(e.nativeRoot,r))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let n=uy.relative(e.nativeRoot,r).replaceAll("\\","/"),a=await dj(e.nativeRoot,n),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await re({root:me(e,t),ref:i.source})).hash}return{capability:i.capability,operation:i.operation,expectedBaseHash:i.operation==="create"?null:i.base_hash,actualBaseHash:a,proposedHash:o}}async function pj(e,t){return dy(ud(e,t))}async function Td(e){let t=e.now??new Date,i=await gt(e.paths,e.name),r=await jt(e.paths,e.name),n=await Ie(e.paths.projectRoot),a=uj(i.name,t),o=uy.resolve(e.paths.nativeRoot,...a.split("/"));if(!V(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,f,p]=await Promise.all([Promise.all(i.spec_changes.map(v=>fj(e.paths,i.name,v))),Id({paths:e.paths,state:i,now:t}),js(e.paths,i.name),ns(e.paths,i.name),Lv(e.paths,i.name),pj(e.paths,i.name),dy(o)]);return jw({change:i.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:i.schema,revision:i.revision,phase:i.phase,archived:i.archived,pendingJournal:u||d||f,targetRef:a,targetExists:p,specs:s,evidence:c.evidence,workspace:r?.schema==="comet.native.workspace.v3"?{schema:r.schema,isolation:r.isolation,changeBranch:r.changeBranch,targetBranch:r.targetBranch,finish:r.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}async function hj(e,t){let i=U(e,t.name),r=await gr(i);if(!r||!t.run_id||r.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let n=await Xo(i,r.checkpointRef);if(!n||n.runId!==r.runId||n.stateVersion!==r.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await Ii(i,r.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:r.runId}}async function mj(e,t){let i=await hj(e,t);return{committed:i,latest:cw(i),history:sw(i)}}async function fy(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let r=await mj(e,t),n=r.latest;if(!n)return null;let a=r.history.filter(c=>c.kind==="failure"),o=a.length>=i,s=n.disposition==="hard-stop"&&!o?"continue":n.disposition;return{disposition:o?"hard-stop":s,signatureHash:n.signatureHash,overrideRecorded:r.history.some(c=>c.kind==="override"&&c.signatureHash===n.signatureHash),failedAcceptanceIds:[...n.failedAcceptanceIds],failedCheckIds:[...n.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:i,remainingVerifyFailures:Math.max(0,i-a.length)}}var s2=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function gj(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function wj(e){return(await Cg(e))?.change??null}function yj(e,t,i=!1,r){return xs({state:e,archiveReady:t,evidenceRetreat:i}).command}async function Nj(e,t){let i=me(e,t.name),r=[...(await Cu(i,t.brief)).findings,...(await zv(e,t)).findings,...await Pg(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await zo(e,t.name);if(n===null)r.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await fv(e,n);a.complete||r.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${a.omittedCount} omitted entries); resolve the omissions before advancing`})}}catch(n){r.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${n.message}`})}if(t.phase==="build")try{let n=await yr({changeDir:i,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==n.contract.contractHash&&r.push({code:"contract-changed-after-approval",message:t.approval===null||t.approved_contract_hash===null||t.approved_contract_hash===void 0?"Native approval is not bound to a contract hash; re-confirm the current contract":"Native contract changed after approval; re-confirm the current contract"})}catch(n){r.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${n.message}`})}try{await ww(e,t.name)&&r.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(n){r.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${n.message}`})}return t.verification_report?r.push(...(await xu(i,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&r.push({code:"verification-report-missing",message:"Native change has no verification report"}),r}async function py(e,t,i){let r=await wj(e)===t,n=await Dl(e,t),a=await _v(e,t),o;try{let w=await Su(e,t);if(w.status==="migration-required"&&w.state)return{name:t,phase:w.state.phase,revision:"revision"in w.state?w.state.revision:null,approval:w.state.approval,verificationResult:w.state.verification_result,specChanges:w.state.spec_changes.length,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["migration-required"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:w.schema,migrationRequired:!0,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message};if(w.status!=="current"||!w.state)return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["runtime-incompatible"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:w.schema,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message??`Native change ${t} is incompatible`};o=w.state}catch(w){return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["change-invalid"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,error:w.message}}if(n.status!=="available"){let w={code:n.status==="missing"?"runtime-missing":"runtime-storage-invalid",message:n.status==="missing"?`Native Runtime is missing; continue ${o.name} to rebuild local execution state`:n.message??"Native Runtime storage is invalid",path:n.path},C=md({paths:e,state:o,findings:[w]}),$=xs({state:o,findings:C});return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:$.command,archiveReady:!1,inspection:{freshness:"stale",codes:[w.code],reasonCount:1,codesTruncated:!1},findingSummary:vd(C),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:$,workspace:a,runtime:n,...i?.details?{findings:C}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:w.message}:{}}}let s=await _w({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await fy(e,o,i?.maxVerifyFailures??5),c&&(c.disposition==="manual-stop"||c.disposition==="hard-stop")){let w=c.disposition==="hard-stop"?"repair-iteration-limit":c.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";l.push({code:w,message:`Native repair is stopped at failure signature: ${c.signatureHash}`})}}catch{l.push({code:"trajectory-invalid",message:"Native repair history could not be reconstructed safely"})}let u;if(i?.details&&(o.phase==="build"||o.phase==="verify"||o.phase==="archive"))try{let w=await yr({changeDir:me(e,o.name),briefRef:o.brief,specChanges:o.spec_changes}),C=new Map;if(o.phase==="build"&&o.verification_result==="fail"&&o.verification_evidence){let pe=await Tr(e,o.name,o.verification_evidence);for(let Q of pe.acceptanceTrace.entries)C.set(Q.acceptanceId,Q.status==="failed"?"failed":Q.status==="missing"?"missing":"satisfied")}let $=ym({criteria:w.contract.acceptance,acceptanceHash:w.contract.acceptanceHash,verificationStatuses:C,failedCheckIds:c?.failedCheckIds??[],...i.acceptanceCursor?{cursor:i.acceptanceCursor}:{}}),T=$.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",$.nextCursor,"--project-root",e.projectRoot]:null;u={...$,...T?{nextPageCommand:gj(T),nextPageArgs:T}:{}}}catch(w){if(i.acceptanceCursor)throw w;u=void 0}let d=[];if(i?.includeConflictFindings!==!1)try{let w=await js(e,o.name,{tolerateInvalidSiblings:!0});d.push(...w.findingCodes.map(C=>({code:C,message:`Native change overlap is visible in the current root: ${C}`})))}catch{d.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let f=[];try{let w=await jt(e,o.name);if(w)if(w.schema==="comet.native.workspace.v3"){let C=await jn({paths:e,identity:w});C.state==="drifted"&&C.code&&f.push({code:C.code,message:C.message??"Native workspace binding is no longer valid"})}else{let C=await es({paths:e,identity:w});f.push(...C.findingCodes.map($=>({code:$,message:`Native workspace advisory changed: ${$} (${C.driftComponents.join(", ")||"no-component"})`})))}}catch{f.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let p=[],v=!1;if(o.phase==="verify"){let w=await ly({paths:e,state:o});v=w.freshness!=="fresh",p.push(...w.findingCodes.map(C=>({code:C,message:`Native Verify implementation scope is not current: ${C}`})))}let h=null,m=[];if(o.phase==="archive")try{h=await Td({paths:e,name:o.name}),m.push(...h.findingCodes.map(w=>({code:w,message:`Native Archive is blocked: ${w}`})))}catch{m.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let S=[...await Nj(e,o),...s.findings,...d,...f,...p,...l,...m].filter((w,C,$)=>$.findIndex(T=>T.code===w.code&&T.path===w.path)===C),y=md({paths:e,state:o,findings:S}),k=y.filter(w=>!wr(w.code)),N=o.phase==="archive"&&h?.ready===!0&&k.length===0,E=v||o.phase==="archive"&&(h?.findingCodes??[]).some(w=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(w)),b=y.some(w=>w.code==="trajectory-tail-incomplete"||w.code==="trajectory-invalid"||w.requiredAction==="return-to-bound-working-directory"||w.requiredAction==="repair-workspace-binding"),x=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",g=y.find(w=>w.severity==="error");return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:b||x?null:yj(o,N,E,i?.clarificationMode),archiveReady:N,inspection:s.inspection,findingSummary:vd(y),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:xs({state:o,findings:y,archiveReady:N,evidenceRetreat:E,clarificationMode:i?.clarificationMode}),workspace:a,runtime:n,repair:c,...i?.details?{...u?{acceptancePage:u}:{},findings:y.slice(0,50),inspectionDetails:s.inspectionDetails,checkpointDetails:s.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:As,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:y.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...g?{error:g.message}:{}}}import $j from"node:path";import{promises as hy}from"node:fs";import bj from"node:path";var kj=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),Sj=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),Ej=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task"]),Cj=new Set(["status","summary"]);function Os(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Hs(e,t,i){let r=new Set(Object.keys(e)),n=[...t].filter(o=>!r.has(o)),a=[...r].filter(o=>!t.has(o));return n.length===0&&a.length===0?null:`${i} fields must be exact (missing: ${n.join(", ")||"none"}; unexpected: ${a.join(", ")||"none"})`}function xj(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((i,r)=>i===t[r])}function Bi(e,t,i){return{status:"incompatible",file:e,snapshot:t,message:i}}function Pj(e,t,i,r){let n=Os(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=Hs(n,kj,"Native Supervisor overlay");if(a)return a;if(r.stateVersion!==1)return"Native Supervisor overlay stateVersion is not 1";if(r.parent!==t.name)return`Native Supervisor overlay parent ${r.parent} does not match ${t.name}`;let o=Os(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=Hs(o,Sj,"Native Supervisor integration");if(s)return s;if(r.integration.headCommit!==r.integration.targetCommit)return"Native Supervisor integration headCommit has advanced beyond targetCommit";if(!Array.isArray(n.history)||n.history.length!==0)return"Native Supervisor overlay history is not empty";let c=Os(n.finalVerification,"Native Supervisor finalVerification");if(!c)return"Native Supervisor finalVerification must be an object";let l=Hs(c,Cj,"Native Supervisor finalVerification");if(l)return l;if(r.finalVerification.status!=="pending"||r.finalVerification.summary!==null)return"Native Supervisor final verification already contains progress";if(!Array.isArray(n.children))return"Native Supervisor children must be an array";if(n.children.length!==i.children.length)return"Native Supervisor child count does not match the legacy children contract";for(let[u,d]of n.children.entries()){let f=Os(d,`Native Supervisor child ${u}`);if(!f)return`Native Supervisor child ${u} must be an object`;let p=Hs(f,Ej,`Native Supervisor child ${u}`);if(p)return p;let v=i.children[u];if(f.name!==v.name||f.summary!==v.summary||!xj(f.dependsOn,v.depends_on))return`Native Supervisor child ${v.name} does not match the legacy children contract`;let h=v.depends_on.length===0?"ready":"pending";if(f.status!==h)return`Native Supervisor child ${v.name} has progressed beyond its initial ${h} status`;if(f.baseCommit!==null||f.candidateCommit!==null||f.verifiedCommit!==null||f.integrationCommit!==null||f.verification!==null||f.blocker!==null||f.projectRoot!==null||f.task!==null)return`Native Supervisor child ${v.name} contains execution progress`;if(!Array.isArray(f.checks)||f.checks.length!==0)return`Native Supervisor child ${v.name} contains integration checks`}return null}async function my(e){let t=us(e.paths,e.state.name),i;try{let c=await hy.lstat(t);if(!c.isFile()||c.isSymbolicLink())return Bi(t,"","Native Supervisor overlay is not a regular file");i=await hy.readFile(t,"utf8")}catch(c){return c.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:Bi(t,"",`Native Supervisor overlay cannot be read: ${c.message}`)}let r;try{r=JSON.parse(i)}catch(c){return Bi(t,i,`Native Supervisor overlay is invalid JSON: ${c.message}`)}let n=bj.join(e.paths.changesDir,e.state.name),a;try{a=await ps({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:c})=>c),policy:"advisory"})}catch(c){return Bi(t,i,`Native children contract cannot be validated: ${c.message}`)}if(!a||a.contract.schema!=="comet.native.children.v1")return{status:"compatible",file:t,message:"The current Native children contract is not legacy children.v1",snapshot:i};let o;try{o=await $i(e.paths,e.state.name)}catch(c){return Bi(t,i,`Native Supervisor overlay is invalid: ${c.message}`)}if(!o)return Bi(t,i,"Native Supervisor overlay disappeared during inspection");let s=Pj(r,e.state,a.contract,o);return s?Bi(t,i,s):{status:"repairable-legacy-overlay",file:t,message:"An exact unstarted v2 Supervisor overlay is stale beside a legacy children.v1 contract",snapshot:i}}function Lt(e,t,i){return e.language==="zh-CN"?i:t}function Rj(e,t){let i=r=>({required:!1,message:null,suggestedReply:null,agentInstruction:r});if(e.phase==="shape"&&e.status==="await-user"&&e.loop.next_action==="confirm-shape")return e.language==="zh-CN"?{required:!0,message:"Shape 已整理完成。请确认目标、范围、关键决定、验收标准和非目标是否准确;明确确认后才会进入 Build。",suggestedReply:"确认进入 Build",agentInstruction:"先用自然语言简要展示目标、范围、关键决定、验收标准和非目标,再转述 message 并等待用户明确确认。只有用户明确同意当前完整 Shape 时,才执行 commandAlternatives 中的 confirm-shape;补充或修改要求不算确认。不要展示机器状态或提前运行 --confirmed。"}:{required:!0,message:"Shape is ready. Confirm that the target, scope, key decisions, acceptance criteria, and non-goals are accurate; Build starts only after explicit confirmation.",suggestedReply:"Confirm and enter Build",agentInstruction:"First present a concise natural-language summary of the target, scope, key decisions, acceptance criteria, and non-goals. Then relay message and wait for explicit user confirmation. Run confirm-shape from commandAlternatives only when the user explicitly accepts the complete current Shape; additions or corrections are not confirmation. Do not expose machine state or run --confirmed early."};if(t&&e.phase==="shape"&&e.status==="active")return{required:!0,message:Lt(e,"This Supervisor Change has multiple independent children. Choose one coordination mode before confirming Shape: A) Multi-session coordination (recommended), or B) Single-session progression.","当前 Supervisor Change 包含多个可独立执行的 Child。确认 Shape 前请选择推进方式:A)多会话协作(推荐),或 B)单会话推进。"),suggestedReply:Lt(e,"Reply A or B","回复 A 或 B"),agentInstruction:Lt(e,"Relay the two coordination choices and wait for the user decision. After the user chooses, execute the prepare-shape-confirmation commandArgs with the selected --coordination-mode. Do not combine mode selection with final confirmation; confirmation of the complete Shape is a separate await-user step.","转述这两个推进方式并等待用户选择。用户选择后,使用对应的 --coordination-mode 执行 prepare-shape-confirmation 的完整 commandArgs;不要把推进方式选择和最终确认合并执行,完整 Shape 的确认是后续单独的 await-user 步骤。")};if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready"&&e.loop.next_action!=="await-verifier-result")return i(Lt(e,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result")return i(Lt(e,"Wait only while the dispatched Verifier task is still active. If the task did not start, failed, timed out, ended without a response, or was lost, immediately submit verifier-execution-error. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","仅在已派发的独立验收任务仍在运行时等待。如果任务未启动、执行失败、超时、结束后没有返回结果或已经丢失,立即提交 verifier-execution-error;只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。"));if(e.status==="blocked"&&e.blockers.some(({resolution_action:r})=>r==="retry-verifier"))return e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable")return e.language==="zh-CN"?{required:!0,message:"独立验收当前不可用,但你的代码和已经完成的检查都已安全保留。你可以直接重新尝试独立验收,也可以明确接受只有自动检查的结果。",suggestedReply:"重新尝试独立验收",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户选择。用户要求重试时执行 commandAlternatives 中的 retry-verifier;只有用户明确接受降级结果时才执行 confirm-verifier-unavailable。不要把“继续”视为接受降级结果,也不要要求用户处理文件、进程、服务或回调。"}:{required:!0,message:"Independent verification is currently unavailable, but your code and completed checks are safely preserved. You can retry independent verification directly or explicitly accept the automatic-check-only result.",suggestedReply:"Retry independent verification",agentInstruction:"Relay only message and suggestedReply, then wait for the user choice. If the user asks to retry, run retry-verifier from commandAlternatives; run confirm-verifier-unavailable only when the user explicitly accepts the degraded result. Do not treat “Continue” as accepting the degraded result, and do not ask the user to manage files, processes, services, or callbacks."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="resolve-verifier-blocker")return e.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="await-user"){let n=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",a=n?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。",o=n?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return e.language==="zh-CN"?{required:!0,message:a,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:o,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}return i(Lt(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 Aj(e){let t=e.workspace.change_branch??"<change-branch>",i=e.workspace.target_branch??"<target-branch>";return e.language==="zh-CN"?{required:!0,message:`当前 change 位于 ${t},目标分支为 ${i}。请选择一次工作区收尾方式:A) 保留工作区;B) 本地合并;C) 推送分支;D) 推送并创建 PR;E) 暂不归档。选择 A-D 后 Runtime 会先执行完整 dry-run,再给出唯一的 confirmed 命令;选择 E 将保留当前 change 等待稍后继续。`,suggestedReply:"回复 A、B、C、D 或 E",agentInstruction:"只向用户展示五种收尾方式及实际影响,等待用户选择。选择 A-D 时执行对应 commandAlternatives 中包含 --dry-run --finish 的完整命令;选择 E 时停止,不运行任何 Archive 命令。不要直接运行 --confirmed,也不要自行猜测 finish。"}:{required:!0,message:`This change is on ${t} and targets ${i}. Choose one workspace finish: A) keep the workspace; B) merge locally; C) push the branch; D) push and create a PR; or E) defer Archive. For A-D, Runtime will run a complete dry-run first, then return one confirmed command; E keeps the current change for later.`,suggestedReply:"Reply A, B, C, D, or E",agentInstruction:"Show all five finish choices and their actual effects, then wait. For A-D, execute the matching complete commandAlternative containing --dry-run --finish; for E, stop without running an Archive command. Do not run --confirmed directly or guess a finish mode."}}function _j(e){return[...[{finish:"keep",name:"keep-workspace",description:["保留当前分支和目录;完成归档提交,不合并、不推送、不创建 PR。","Keep the current branch and directory; create the archive commit without merging, pushing, or creating a PR."]},{finish:"merge",name:"merge-locally",description:["完成归档提交,并把 change 分支本地合并到目标分支;不推送、不创建 PR。","Create the archive commit and merge the change branch locally into the target branch without pushing or creating a PR."]},{finish:"push",name:"push-branch",description:["完成归档提交并推送 change 分支;不合并到目标分支、不创建 PR。","Create the archive commit and push the change branch without merging into the target branch or creating a PR."]},{finish:"pull-request",name:"push-pull-request",description:["完成归档提交、推送 change 分支,并以目标分支为基础创建 PR。","Create the archive commit, push the change branch, and create a PR against the target branch."]}].map(({finish:r,name:n,description:a})=>({name:n,stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","archive",e.name,"--dry-run","--finish",r],requiredInputs:[],inputOptions:[],description:Lt(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:Lt(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function gy(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function $r(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function Ij(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function vy(e,t,i){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...i]}}function Tj(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function jj(e){return["comet","native","next",e.change,"--summary","<summary>",...e.coordinationRequired?["--coordination-mode","<coordination-mode>"]:[],"--expected-state-version",String(e.stateVersion),"--expected-action","prepare-shape-confirmation"]}function vi(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:gy({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[$r("summary","--summary"),Ij(e.name,e.flag)]}}function jd(e){return[vi({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),vi({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function wy(e,t,i={}){let r=Tj(t)&&e.coordination_mode===void 0,n=Rj(e,r),a={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],requiresUserDecision:n.required,userCommunication:n},o=s=>({kind:s,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...a,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:o("none")};if(e.status==="await-user")return e.phase==="shape"&&e.loop.next_action==="confirm-shape"?{...a,disposition:"await-user",action:"confirm-shape",commandArgs:null,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:[$r("summary","--summary")],commandAlternatives:[vi({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:[$r("summary","--summary")],commandAlternatives:[vi({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...jd({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:[$r("summary","--summary")],commandAlternatives:[vi({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),vi({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:[$r("summary","--summary")],commandAlternatives:[vi({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...jd({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:[$r("summary","--summary")],commandAlternatives:jd({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:o("none")};if(e.status==="blocked"){let s=e.blockers.some(({resolution_action:c})=>c==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?gy({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:s?["summary"]:["repair-runtime"],inputOptions:s?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:o(s?"retry-verifier":"none")}}if(e.phase==="shape")return{...a,disposition:r?"await-user":"continue",action:"prepare-shape-confirmation",commandArgs:jj({change:e.name,stateVersion:e.state_version,coordinationRequired:r}),requiredInputs:["summary",...r?["coordination-choice"]:[]],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},...r?[vy("coordination-mode","--coordination-mode",Sm)]:[]],runnerAction:o("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...a,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:o("none")};if(t.allDone)return{...a,disposition:"continue",action:"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:o("builder-handoff")};let s=t.children.some(({status:l})=>l==="blocked"||l==="needs-reverify"),c=t.children.some(({status:l})=>l==="ready"||l==="active");return{...a,disposition:s&&!c?"blocked":"continue",action:"advance-children",commandArgs:null,requiredInputs:s&&!c?["resolve-child-blocker"]:["ready-children"],inputOptions:[],runnerAction:o("none")}}return{...a,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:o("builder-handoff")}}if(e.phase==="verify"){let s=e.loop.next_action==="await-verifier-result",c=!!e.children_contract_hash,l={id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0};return{...a,userCommunication:!s&&c?{...a.userCommunication,agentInstruction:`${a.userCommunication.agentInstruction} ${Lt(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:a.userCommunication,disposition:"continue",action:s?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[s?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:s?[{kind:"verifier-response",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[l]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:[{id:"<acceptance-id>",result:"<passed|failed|blocked>",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:c?[l]:[]}}],runnerAction:o(s?"await-verifier":"dispatch-verifier")}}if(e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived){let s=i.archiveMode??"archive-ready",l=e.workspace.isolation!=="current"&&e.workspace.finish===null;return s==="blocked"?{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")}:s==="preview"?i.archiveBlockers&&i.archiveBlockers.length>0?{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}:l?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[vy("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[..._j(e)],userCommunication:Aj(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[vi({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 yy from"node:path";function Ny(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function by(e,t){let i=e.acceptance.reduce((r,n)=>({...r,[n.result]:r[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:i,unresolved_acceptance_ids:e.acceptance.filter(({result:r})=>r==="failed"||r==="blocked").map(({id:r})=>r),verification_result:e.verification_result,blockers:e.blockers.slice(0,8).map(r=>({owner:r.owner,reason:Ny(r.reason.text),acceptance_ids:r.acceptance_ids,resolution_action:r.resolution_action})),workspace:{isolation:e.workspace.isolation,change_branch:e.workspace.change_branch,target_branch:e.workspace.target_branch,finish:e.workspace.finish},learning:{failureResolved:e.verification_result==="pass"&&e.history.some(r=>r.outcome==="fail"&&r.goal_cycle===e.loop.goal_cycle),...e.verification?{summary:Ny(e.verification.summary.text)}:{},artifactRefs:t?["brief.md",...e.verification_report?[e.verification_report]:[],...e.spec_changes.map(r=>r.source).filter(r=>r!==null)].slice(0,16).map(r=>yy.relative(t.projectRoot,yy.join(t.changesDir,e.name,r)).replaceAll("\\","/")):[]},archived:e.archived}}function Oj(e,t,i){return`native-details-v2.${e}.${t}.${i.toString(36)}`}function Hj(e,t,i){if(!e)return 0;let r=/^native-details-v2\.(\d+)\.(\d+)\.([0-9a-z]+)$/u.exec(e);if(!r||Number(r[1])!==t||Number(r[2])!==i)throw new Error("Native details cursor is stale or invalid");let n=Number.parseInt(r[3],36);if(!Number.isSafeInteger(n)||n<0)throw new Error("Native details cursor offset is invalid");return n}function Dj(e,t,i){return[...e.acceptance.map(r=>({kind:"acceptance",value:r})),...e.spec_changes.map(r=>({kind:"spec-change",value:r})),...e.builder_handoff?[{kind:"builder-handoff",value:e.builder_handoff}]:[],...e.verification?[{kind:"verification",value:e.verification}]:[],...e.history.map(r=>({kind:"history",value:r})),{kind:"history-overflow",value:e.history_overflow},{kind:"workspace",value:e.workspace},...e.verification_report?[{kind:"verification-report",value:e.verification_report}]:[],...t?[{kind:"supervisor-integration",value:{...t.integration,worktree:"<worktree>",targetCommit:"<redacted>",headCommit:"<redacted>"}},{kind:"supervisor-final-verification",value:t.finalVerification},...t.children.map(r=>({kind:"supervisor-child",value:Vj(r,i)})),...t.history.map(r=>({kind:"supervisor-history",value:Fj(r,i)}))]:[]]}function Bj(e){return e.acceptance.reduce((t,i)=>({...t,[i.result]:t[i.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0})}function ky(e,t){let i=Ee(e.projectRoot),r=null;return t.workspace.change_branch!==null&&(i.isGitWorktree?i.currentBranch!==t.workspace.change_branch&&(r=`Expected branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}.`):r="The Native change requires a registered Git worktree."),r===null&&t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree&&(r="The Native change requires its linked worktree."),{projectRoot:$j.resolve(e.projectRoot),isolation:t.workspace.isolation,bindingState:r===null?"aligned":"mismatch",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:r}}function Lj(e,t){return[e.projectRoot,t.integration.worktree,...t.children.flatMap(i=>[i.projectRoot,i.task?.projectRoot])].filter(i=>!!i).map(i=>i.replaceAll("/","\\")).sort((i,r)=>r.length-i.length)}function Ds(e,t){return e===null?null:t.reduce((i,r)=>i.replaceAll(r,"<worktree>").replaceAll(r.replaceAll("\\","/"),"<worktree>"),e)}function Vj(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:Ds(e.blocker,t),task:e.task?{...e.task,projectRoot:"<worktree>",baseCommit:"<redacted>",runId:"<redacted>"}:null}}function Fj(e,t){return{...e,runId:e.runId?"<redacted>":null,summary:Ds(e.summary,t)??""}}async function Sy(e){let t=await Eg(e),i=by(t.state),r=t.state.status==="active"&&t.state.loop.stage!=="done",n=await Hu({paths:e.paths,state:t.state}),a=await my({paths:e.paths,state:t.state}),o=a.status==="repairable-legacy-overlay"||a.status==="incompatible"?null:await $i(e.paths,e.name),s=o?{...ky(e.paths,t.state),projectRoot:"."}:ky(e.paths,t.state),c=wy(t.state,n),l=s.bindingState==="mismatch"?{...c,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["return-to-bound-workspace"],runnerAction:{...c.runnerAction,kind:"none"}}:c,u=o?Lj(e.paths,o):[],d=o?(()=>{let v=o.children.filter(({status:N})=>N==="pending"||N==="ready").length,h=o.children.filter(({status:N})=>N==="active"||N==="verified").length,m=o.children.filter(({status:N})=>N==="integrated"||N==="archived").length,S=o.children.filter(({status:N})=>N==="blocked"||N==="needs-reverify").length,y=o.children.filter(({status:N})=>N==="active"||N==="blocked"||N==="needs-reverify").slice(0,16).map(N=>({name:N.name,summary:N.summary,projectRoot:N.task?.projectRoot??N.projectRoot?"<worktree>":null,reason:Ds(N.blocker,u)})),k=o.children.flatMap(({blocker:N})=>{let E=Ds(N,u);return E?[E]:[]}).slice(0,16);return{targetSpecs:t.state.spec_changes.length,implementationChildren:o.children.length,waiting:v,working:h,integrated:m,blocked:S,active:y,agents:{working:o.children.filter(({task:N})=>N!==null).length,completed:m},risks:k,nextAction:o.finalVerification.status==="passed"?"final-delivery":o.finalVerification.status==="pending"&&m===o.children.length?"parent-verification":v>0?"dispatch-ready-child":S>0?"resolve-blocker":"continue-supervisor"}})():null,f=e.details?(()=>{let v=o?.stateVersion??0,h=Dj(t.state,o,u),m=Hj(e.cursor,t.state.state_version,v),S=h.slice(m,m+32),y=m+S.length<h.length?Oj(t.state.state_version,v,m+S.length):null;return{items:S,nextCursor:y,supervisorStateVersion:v}})():null,p=o?{schema:o.schema,parent:o.parent,integration:{branch:o.integration.branch,targetBranch:o.integration.targetBranch},finalVerification:{status:o.finalVerification.status,summary:o.finalVerification.summary},summary:d}:null;return{schema:"comet.native.status.v2",name:t.state.name,phase:t.state.phase,status:t.state.status,stateVersion:t.state.state_version,...t.state.coordination_mode===void 0?{}:{coordinationMode:t.state.coordination_mode},loop:t.state.loop,acceptance:Bj(t.state),unresolvedAcceptanceIds:i.unresolved_acceptance_ids,verificationResult:t.state.verification_result,blockers:o?[]:i.blockers,workspace:s,localExecution:{status:r?t.localStatus:"not-expected",operation:t.localStatus==="available"?t.local?.execution??null:null},...n?{childSummary:n.children.reduce((v,h)=>({...v,[h.status]:(v[h.status]??0)+1}),{total:n.children.length}),readyChildren:n.readyChildren}:{},...p?{supervisor:p}:{},...a.status==="repairable-legacy-overlay"||a.status==="incompatible"?{supervisorOverlay:{status:a.status,message:a.message,repairCommand:a.status==="repairable-legacy-overlay"?`comet native doctor ${e.name} --repair`:null}}:{},continuation:l,...e.details?{details:{stateVersion:t.state.state_version,...o?{supervisorStateVersion:f.supervisorStateVersion}:{},items:f.items,nextCursor:f.nextCursor,nextPageArgs:f.nextCursor?["comet","native","status",t.state.name,"--details","--cursor",f.nextCursor,"--json","--project-root",e.paths.projectRoot]:null}}:{}}}import ra from"path";import{realpathSync as n$}from"fs";var Vt={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function Ey(e){return e?e.command?`${Vt.next} ${e.command}`:e.ask_user?`${Vt.next} ${e.ask_user}`:null:null}function Cy(e,t){let i=[e.summary],r=Ey(e.next);return r&&i.push(r),e.user_message&&i.push("",Vt.relay,e.user_message),t!==void 0&&i.push("",Vt.details,JSON.stringify(t,null,2)),`${i.join(`
175
175
  `)}
176
- `}function Ey(e,t,i){let r=[e.summary],n=ky(e.next);return n&&r.push(n),e.user_message&&r.push("",Vt.relay,e.user_message),r.push("",`${Vt.detail} ${t}`),i!==void 0&&r.push("",Vt.details,JSON.stringify(i,null,2)),r.join(`
177
- `)}var B2={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var G2=16*1024*1024,U2=256*1024,K2=16*1024;var tz=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var Fz=16*1024*1024,Bs=class extends Error{constructor(i,r,n,a){super(`Canonical spec conflict for ${i}: expected ${r??"(missing)"}, actual ${n??"(missing)"}`);this.capability=i;this.expectedHash=r;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},Ls=class extends Error{constructor(i,r=i.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${i.findingCodes.join(", ")}`){super(r);this.preflight=i;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};function L(e,t,i){return e==="zh-CN"?i:t}var $d={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function Cy(e,t){return typeof e=="string"&&$d[e]?L(t,$d[e].en,$d[e].zh):typeof e=="string"?e:""}function Od(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 Mj(e){let t={total:e.length,passed:0,failed:0,blocked:0,pending:0};for(let i of e){if(!i||typeof i!="object")return null;let r=i.result;if(r!=="passed"&&r!=="failed"&&r!=="blocked"&&r!=="pending")return null;t[r]+=1}return t}function xy(e,t){let i=[];e.failed>0&&i.push(L(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&i.push(L(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&i.push(L(t,`${e.pending} pending`,`${e.pending} 项待验`));let r=L(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return i.length>0?`${r} (${i.join(", ")})`:r}function Py(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.change!="string"||t.disposition!=="continue"&&t.disposition!=="await-user"&&t.disposition!=="blocked"&&t.disposition!=="done"||t.commandArgs!==null&&t.commandArgs!==void 0&&!Array.isArray(t.commandArgs))return!1;let i=t.userCommunication;return!!(i&&typeof i=="object"&&typeof i.required=="boolean"&&(i.message===null||typeof i.message=="string")&&typeof i.agentInstruction=="string")}function Hd(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function Wj(e,t,i){return e==="done"?L(i,"complete","已完成"):e==="await-user"?L(i,"waiting for a user decision","等待用户决定"):e==="blocked"?L(i,"paused: needs attention","已暂停,需要处理"):t?L(i,"waiting for a user decision","等待用户决定"):L(i,"ready to continue","可继续推进")}function zj(e,t,i){let r=Hd(e),n=[];i&&n.push(i);let a=L(r,`Change ${e.change}`,`需求 ${e.change}`),o=Cy(e.phase,r),s=Wj(e.disposition,e.userCommunication.required,r);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(xy(t,r));let c=e.userCommunication,l=Ry(e,r);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function Ry(e,t){let i=e.userCommunication;if(e.disposition==="await-user"&&i.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:L(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function Jj(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function Gj(e,t){let i=typeof e.name=="string"?e.name:"(unnamed)",r=Cy(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=Od(e.acceptance)?`${L(t,", ",",")}${xy(e.acceptance,t)}`:"";return` ${i} · ${r||String(e.phase??"?")} · ${n}${a}`}function Uj(e){for(let t of e){let i=t.continuation;if(i?.userCommunication&&typeof i.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(i.userCommunication.agentInstruction))return"zh-CN"}return"en"}function Kj(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 Yj(e){if(e.healthy){let r=e.repaired?L("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):L("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=Xj(e.continuation);return n?{summary:r,next:n}:{summary:r}}let i=Array.isArray(e.findings)?e.findings.length:0;return{summary:L("en",i>0?`Diagnostics found ${i} problem${i===1?"":"s"} that need attention before this change can continue.`:"Diagnostics found problems that need attention before this change can continue.",i>0?`诊断发现 ${i} 个需要处理的问题,处理后该需求才能继续。`:"诊断发现需要处理的问题,处理后该需求才能继续。"),next:{ask_user:L("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function Xj(e){return Py(e)?Ry(e,Hd(e)):void 0}function Ay(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(Kj(t))return Yj(t);if(Jj(t)){let r=Uj(t.items);return{summary:[t.total===t.items.length?L(r,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):L(r,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>Gj(a,r))].join(`
178
- `)}}let i=t.continuation;if(Py(i))return zj(i,Qj(t),Zj(t,Hd(i)));if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let r=t.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in t;return{summary:L(r,n?`Comet Native artifacts live under ${t.artifactRoot} (state root: ${t.nativeRoot}).`:`Initialized Comet Native at ${t.nativeRoot} (artifacts: ${t.artifactRoot}).`,n?`Comet Native 产物位于 ${t.artifactRoot}(状态根目录:${t.nativeRoot})。`:`Comet Native 已初始化于 ${t.nativeRoot}(产物目录:${t.artifactRoot})。`)}}}function Qj(e){if(Od(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let i=t;if(Od(i.acceptance))return i.acceptance;if(Array.isArray(i.acceptance))return Mj(i.acceptance)}return null}function Zj(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return L(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let i=e.migration;return i&&typeof i=="object"&&i.completed===!0?L(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function _y(e){let i=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){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 i.change=="string"?{next:{command:`comet native status ${i.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}}var Iy=["--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."],Bd=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",subcommands:["init Initialize Native project configuration.","root show Inspect the configured artifact root.","root move <artifact-root> Move the configured artifact root.","new <change-name> Create a change and prepare its workspace.","spec remove Record a complete capability removal intent.","show <change-name> Read formal artifacts and portable state.","status [<change-name>] Discover stable boundaries and Runner actions.","select <change-name> Select a change in its bound workspace.","next <change-name> Confirm or recover a stable workflow boundary.","archive <change-name> Preview and execute Archive plus workspace finish.","check <change-name> Run the read-only Native verification check.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state."],options:Iy,output:"A human summary plus a NEXT step by default (RELAY TO USER blocks carry user decisions); use --json for the structured envelope, --verbose to append the raw machine projection.",examples:["comet native status --json","comet native status my-change --details --json","comet native next --help"]},init:{usage:"comet native init [--root <artifact-root>] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--root <artifact-root> Project-relative artifact root; defaults to docs.","--language en|zh-CN Language for newly generated Native artifacts."],output:"The resolved project configuration and Native paths.",examples:["comet native init --root docs --language zh-CN"]},root:{usage:"comet native root <show|move> [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move <artifact-root> Move Native artifacts and update project configuration."],output:"The current root projection or the completed move result.",examples:["comet native root show","comet native root move artifacts/native"]},"root show":{usage:"comet native root show",purpose:"Print the configured Native artifact root and resolved paths.",output:"The configured artifact root and resolved Native paths."},"root move":{usage:"comet native root move <artifact-root>",purpose:"Transactionally move Native artifacts and update project configuration.",output:"The source, destination, and committed root-move transaction result.",examples:["comet native root move artifacts/native"]},new:{usage:"comet native new <change-name> [--language en|zh-CN] [--isolation current|branch|worktree] [--change-branch <branch>] [--target-branch <branch>] [--worktree-path <path>]",purpose:"Create a portable Native change and prepare the requested branch or linked worktree.",options:["--language en|zh-CN Artifact language; defaults to project configuration.","--isolation <kind> current, branch, or worktree; defaults to current.","--change-branch <branch> Change branch; defaults to comet/<change-name>.","--target-branch <branch> Local base branch; defaults to the current branch.","--worktree-path <path> Worktree directory; defaults to .worktrees/<change-name>."],output:"The portable state, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN","comet native new session-timeout --isolation branch --target-branch main","comet native new session-timeout --isolation worktree --target-branch main"]},spec:{usage:"comet native spec remove <change-name> <capability>",purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove <change-name> <capability> Record a capability removal."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove <change-name> <capability>",purpose:"Record removal of a capability in the complete target specification.",output:"The updated portable state and continuation with the next Runner action."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"The portable state, brief, complete proposed Specs, and continuation; legacy state is reported as migration-required."},status:{usage:"comet native status [<change-name>] [--cursor <token>] [--details]",purpose:"Discover portable stable boundaries, parent child readiness, or the exact next Runner action.",options:["--cursor <token> Continue a status-list page, or a named details/history page.","--details Include one fixed-size page of acceptance, Spec, handoff, verification, history, workspace, and report details."],output:"A compact v2 status page or one compact Loop projection with local execution availability. Use --details and --cursor to read fixed-size detail pages; parent changes expose childSummary and readyChildren.",examples:["comet native status --json","comet native status session-timeout --details --json"]},select:{usage:"comet native select <change-name>",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next <change-name> --summary <text> [--coordination-mode multi-session|single-session] [--max-parallel <n>] [--expected-state-version <n>] [--expected-action <action>]
176
+ `}function xy(e,t,i){let r=[e.summary],n=Ey(e.next);return n&&r.push(n),e.user_message&&r.push("",Vt.relay,e.user_message),r.push("",`${Vt.detail} ${t}`),i!==void 0&&r.push("",Vt.details,JSON.stringify(i,null,2)),r.join(`
177
+ `)}var V2={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var K2=16*1024*1024,Y2=256*1024,X2=16*1024;var rz=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var Mz=16*1024*1024,Bs=class extends Error{constructor(i,r,n,a){super(`Canonical spec conflict for ${i}: expected ${r??"(missing)"}, actual ${n??"(missing)"}`);this.capability=i;this.expectedHash=r;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},Ls=class extends Error{constructor(i,r=i.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${i.findingCodes.join(", ")}`){super(r);this.preflight=i;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};function L(e,t,i){return e==="zh-CN"?i:t}var $d={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function Py(e,t){return typeof e=="string"&&$d[e]?L(t,$d[e].en,$d[e].zh):typeof e=="string"?e:""}function Od(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 Wj(e){let t={total:e.length,passed:0,failed:0,blocked:0,pending:0};for(let i of e){if(!i||typeof i!="object")return null;let r=i.result;if(r!=="passed"&&r!=="failed"&&r!=="blocked"&&r!=="pending")return null;t[r]+=1}return t}function Ry(e,t){let i=[];e.failed>0&&i.push(L(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&i.push(L(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&i.push(L(t,`${e.pending} pending`,`${e.pending} 项待验`));let r=L(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return i.length>0?`${r} (${i.join(", ")})`:r}function Ay(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.change!="string"||t.disposition!=="continue"&&t.disposition!=="await-user"&&t.disposition!=="blocked"&&t.disposition!=="done"||t.commandArgs!==null&&t.commandArgs!==void 0&&!Array.isArray(t.commandArgs))return!1;let i=t.userCommunication;return!!(i&&typeof i=="object"&&typeof i.required=="boolean"&&(i.message===null||typeof i.message=="string")&&typeof i.agentInstruction=="string")}function Hd(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function zj(e,t,i){return e==="done"?L(i,"complete","已完成"):e==="await-user"?L(i,"waiting for a user decision","等待用户决定"):e==="blocked"?L(i,"paused: needs attention","已暂停,需要处理"):t?L(i,"waiting for a user decision","等待用户决定"):L(i,"ready to continue","可继续推进")}function Jj(e,t,i){let r=Hd(e),n=[];i&&n.push(i);let a=L(r,`Change ${e.change}`,`需求 ${e.change}`),o=Py(e.phase,r),s=zj(e.disposition,e.userCommunication.required,r);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(Ry(t,r));let c=e.userCommunication,l=_y(e,r);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function _y(e,t){let i=e.userCommunication;if(e.disposition==="await-user"&&i.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:L(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function Gj(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function Uj(e,t){let i=typeof e.name=="string"?e.name:"(unnamed)",r=Py(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=Od(e.acceptance)?`${L(t,", ",",")}${Ry(e.acceptance,t)}`:"";return` ${i} · ${r||String(e.phase??"?")} · ${n}${a}`}function Kj(e){for(let t of e){let i=t.continuation;if(i?.userCommunication&&typeof i.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(i.userCommunication.agentInstruction))return"zh-CN"}return"en"}function Yj(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 Xj(e){if(e.healthy){let r=e.repaired?L("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):L("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=Qj(e.continuation);return n?{summary:r,next:n}:{summary:r}}let i=Array.isArray(e.findings)?e.findings.length:0;return{summary:L("en",i>0?`Diagnostics found ${i} problem${i===1?"":"s"} that need attention before this change can continue.`:"Diagnostics found problems that need attention before this change can continue.",i>0?`诊断发现 ${i} 个需要处理的问题,处理后该需求才能继续。`:"诊断发现需要处理的问题,处理后该需求才能继续。"),next:{ask_user:L("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function Qj(e){return Ay(e)?_y(e,Hd(e)):void 0}function Iy(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(Yj(t))return Xj(t);if(Gj(t)){let r=Kj(t.items);return{summary:[t.total===t.items.length?L(r,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):L(r,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>Uj(a,r))].join(`
178
+ `)}}let i=t.continuation;if(Ay(i))return Jj(i,Zj(t),e$(t,Hd(i)));if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let r=t.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in t;return{summary:L(r,n?`Comet Native artifacts live under ${t.artifactRoot} (state root: ${t.nativeRoot}).`:`Initialized Comet Native at ${t.nativeRoot} (artifacts: ${t.artifactRoot}).`,n?`Comet Native 产物位于 ${t.artifactRoot}(状态根目录:${t.nativeRoot})。`:`Comet Native 已初始化于 ${t.nativeRoot}(产物目录:${t.artifactRoot})。`)}}}function Zj(e){if(Od(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let i=t;if(Od(i.acceptance))return i.acceptance;if(Array.isArray(i.acceptance))return Wj(i.acceptance)}return null}function e$(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return L(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let i=e.migration;return i&&typeof i=="object"&&i.completed===!0?L(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function Ty(e){let i=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){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 i.change=="string"?{next:{command:`comet native status ${i.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}}var jy=["--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."],Bd=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",subcommands:["init Initialize Native project configuration.","root show Inspect the configured artifact root.","root move <artifact-root> Move the configured artifact root.","new <change-name> Create a change and prepare its workspace.","spec remove Record a complete capability removal intent.","show <change-name> Read formal artifacts and portable state.","status [<change-name>] Discover stable boundaries and Runner actions.","select <change-name> Select a change in its bound workspace.","next <change-name> Confirm or recover a stable workflow boundary.","archive <change-name> Preview and execute Archive plus workspace finish.","check <change-name> Run the read-only Native verification check.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state."],options:jy,output:"A human summary plus a NEXT step by default (RELAY TO USER blocks carry user decisions); use --json for the structured envelope, --verbose to append the raw machine projection.",examples:["comet native status --json","comet native status my-change --details --json","comet native next --help"]},init:{usage:"comet native init [--root <artifact-root>] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--root <artifact-root> Project-relative artifact root; defaults to docs.","--language en|zh-CN Language for newly generated Native artifacts."],output:"The resolved project configuration and Native paths.",examples:["comet native init --root docs --language zh-CN"]},root:{usage:"comet native root <show|move> [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move <artifact-root> Move Native artifacts and update project configuration."],output:"The current root projection or the completed move result.",examples:["comet native root show","comet native root move artifacts/native"]},"root show":{usage:"comet native root show",purpose:"Print the configured Native artifact root and resolved paths.",output:"The configured artifact root and resolved Native paths."},"root move":{usage:"comet native root move <artifact-root>",purpose:"Transactionally move Native artifacts and update project configuration.",output:"The source, destination, and committed root-move transaction result.",examples:["comet native root move artifacts/native"]},new:{usage:"comet native new <change-name> [--language en|zh-CN] [--isolation current|branch|worktree] [--change-branch <branch>] [--target-branch <branch>] [--worktree-path <path>]",purpose:"Create a portable Native change and prepare the requested branch or linked worktree.",options:["--language en|zh-CN Artifact language; defaults to project configuration.","--isolation <kind> current, branch, or worktree; defaults to current.","--change-branch <branch> Change branch; defaults to comet/<change-name>.","--target-branch <branch> Local base branch; defaults to the current branch.","--worktree-path <path> Worktree directory; defaults to .worktrees/<change-name>."],output:"The portable state, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN","comet native new session-timeout --isolation branch --target-branch main","comet native new session-timeout --isolation worktree --target-branch main"]},spec:{usage:"comet native spec remove <change-name> <capability>",purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove <change-name> <capability> Record a capability removal."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove <change-name> <capability>",purpose:"Record removal of a capability in the complete target specification.",output:"The updated portable state and continuation with the next Runner action."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"The portable state, brief, complete proposed Specs, and continuation; legacy state is reported as migration-required."},status:{usage:"comet native status [<change-name>] [--cursor <token>] [--details]",purpose:"Discover portable stable boundaries, parent child readiness, or the exact next Runner action.",options:["--cursor <token> Continue a status-list page, or a named details/history page.","--details Include one fixed-size page of acceptance, Spec, handoff, verification, history, workspace, and report details."],output:"A compact v2 status page or one compact Loop projection with local execution availability. Use --details and --cursor to read fixed-size detail pages; parent changes expose childSummary and readyChildren.",examples:["comet native status --json","comet native status session-timeout --details --json"]},select:{usage:"comet native select <change-name>",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next <change-name> --summary <text> [--coordination-mode multi-session|single-session] [--max-parallel <n>] [--expected-state-version <n>] [--expected-action <action>]
179
179
  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>]
180
180
  comet native next <change-name> --runner-input <json-file>`,purpose:"Confirm or recover an Agent boundary, advance parent child changes, handle Supervisor task operations, or use one skill-coordinated JSON bridge for Builder handoff, check-plan dispatch, and Verifier response/error.",options:["--summary <text> Required transition or recovery summary.","--confirmed Confirm the persisted Shape boundary with both expected guards, or confirm an explicitly degraded verifier-unavailable fallback before Archive.","--coordination-mode multi-session|single-session Select how a multi-child Supervisor proceeds while preparing its Shape confirmation; final Shape confirmation is a later, separate step.","--accept-result Accept the current skill-coordinated Verify result and make it archive-ready.","--revise-implementation Keep confirmed requirements unchanged and return Verify to Build for implementation revision.","--revise-requirements Return Verify or Archive to Shape when user-visible goals or acceptance criteria must change.","--retry-verifier Retry a failed or unavailable Verifier when the continuation allows it.","--resolve-verifier-blocker Resolve a semantic Verifier blocker without changing the candidate, then dispatch a new attempt.","--max-parallel <n> Supervisor task concurrency cap; defaults to 2, use 1 for serial fallback.","--expected-state-version <n> Continuation-issued guard that rejects stale public transition decisions.","--expected-action <action> Continuation-issued guard that binds the public transition decision to its intended action.","--runner-input <file> Skill-coordinated JSON: builder-handoff, dispatch-verifier, verifier-response, verifier-execution-error, or verifier-unavailable. Identity/provider/execution/candidate fields are rejected."," builder-handoff fields: kind, summary, addressed_acceptance_ids, checks, known_limits, review. review fields: status=passed, summary, reviewer_execution_ref from a separate read-only review."," dispatch-verifier fields: kind, checks (an explicitly resolved plan; [] is allowed)."," verifier-response fields: kind, response (request-checks or final-result)."," verifier-execution-error fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch."," verifier-unavailable fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch; accepted only after the explicit Runtime check plan completed and passed."," Supervisor task fields: supervisor-builder-result (child, runId, candidateCommit), supervisor-builder-failure (child, runId, reason), supervisor-verifier-result (child, runId, verdict, verification data), supervisor-reconnect (child, runId), supervisor-cancel (child, runId, reason), or supervisor-integrate (child, checks)."],output:'A compact portable state summary, explicit skill-coordinated label, Runtime-owned check results, scoped verifierDispatch, bounded request-check response, continuation.runnerAction, machine-readable continuation.inputOptions, and continuation.userCommunication with a user-ready message and Agent relay guidance. Read acceptance text and other long fields from paged status --details output. Human-readable verification statuses include "Host independently verified", "Checks completed, but your confirmation is required", "Full verification was unavailable; only automatic checks completed", and "You accepted the incomplete verification result". This generic bridge is not trusted identity attestation: a passing result waits for explicit user confirmation before Archive.',examples:['comet native next session-timeout --summary "Shape confirmed" --confirmed --expected-state-version <n> --expected-action confirm-shape','comet native next session-timeout --summary "Current result accepted" --accept-result','comet native next session-timeout --summary "Implementation needs revision" --revise-implementation','comet native next session-timeout --summary "Acceptance criteria changed" --revise-requirements','comet native next session-timeout --summary "Retry verifier infrastructure" --retry-verifier','comet native next session-timeout --summary "Retry semantic verification" --resolve-verifier-blocker',"comet native next session-timeout --runner-input <temporary-json-file>"]},archive:{usage:`comet native archive <change-name> --dry-run [--finish merge|push|pull-request|keep]
181
181
  comet native archive <change-name> [--confirmed] [--serial-first <current-change>]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Run the complete read-only Archive and workspace-finish readiness check; it persists only an explicit --finish choice.","--finish <action> Persist merge, push, pull-request, or keep for an isolated workspace.","--serial-first <current-change> During execution only, confirm that this change archives before detected capability peers; the value must equal <change-name>.","--confirmed Confirm Archive when project policy requires it."],output:"Readiness, every blocker, and the exact next continuation, or the completed Archive transaction and workspace finish result. Execute the returned confirmed command only after ready is true; Archive does not repeat verification."},doctor:{usage:"comet native doctor [<change-name>] [--repair]",purpose:"Inspect portable state, migrate a legacy active change, or rebuild its local execution overlay.",options:["--repair Apply deterministic migration or rebuild from the portable stable boundary."],output:"Health, migration or recovery details, and the continuation with the next Runner action."}});function Dd(e,t){return`${e}:
182
182
  ${t.map(i=>` ${i}`).join(`
183
- `)}`}function e$(e){let t=e.filter(r=>r!=="--help");if(t.length===0)return"";let i=t.slice(0,2).join(" ");return Bd[i]||t.length>1&&Bd[t[0]]?.subcommands?i:t[0]}function t$(e=[]){let t=e$(e),i=Bd[t];if(!i)throw new Error(`Unknown Native help topic: ${t}`);let r=[`Usage: ${i.usage}`,"",i.purpose];i.subcommands&&r.push("",Dd("Commands",i.subcommands));let n=t===""?i.options:[...i.options??[],...Iy];return n&&n.length>0&&r.push("",Dd("Options",n)),r.push("",`Output:
183
+ `)}`}function t$(e){let t=e.filter(r=>r!=="--help");if(t.length===0)return"";let i=t.slice(0,2).join(" ");return Bd[i]||t.length>1&&Bd[t[0]]?.subcommands?i:t[0]}function i$(e=[]){let t=t$(e),i=Bd[t];if(!i)throw new Error(`Unknown Native help topic: ${t}`);let r=[`Usage: ${i.usage}`,"",i.purpose];i.subcommands&&r.push("",Dd("Commands",i.subcommands));let n=t===""?i.options:[...i.options??[],...jy];return n&&n.length>0&&r.push("",Dd("Options",n)),r.push("",`Output:
184
184
  ${i.output}`),i.examples&&r.push("",Dd("Examples",i.examples)),t===""&&r.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${r.join(`
185
185
  `)}
186
- `}}var i$=t$().usage;var oJ=10*1024*1024,gi=class extends Error{};function Vd(e,t){let i=e.flatMap((r,n)=>r===t?[n]:[]);if(i.length>1)throw new gi(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function jy(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new gi(`${t} may only be provided once`);if(i.length===0)return;let r=i[0],n=e[r+1];if(n===void 0||n.startsWith("--"))throw new gi(`${t} requires a value`);return e.splice(r,2),n}function $y(e){if(e.length>0)throw new gi(`Unexpected argument: ${e[0]}`)}function Oy(e,t){let i=e.shift();if(!i||i.startsWith("--"))throw new gi(`${t} is required`);return i}function Ld(e,t){let i=ra.normalize(Ty(e)),r=ra.normalize(Ty(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function Ty(e){let t=ra.resolve(e);try{return r$.native(t)}catch{return t}}function n$(e){let t=ra.resolve(e),i=Ee(process.cwd());if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return t;let r=Ee(t);return!r.isGitWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null||!Ld(i.primaryWorktreeRoot,r.primaryWorktreeRoot)||Ld(i.currentWorktreeRoot,r.currentWorktreeRoot)?t:Ld(process.cwd(),i.currentWorktreeRoot)?ra.resolve(process.cwd()):i.currentWorktreeRoot}async function Hy(e){return e?n$(e):ko(process.cwd())}async function Dy(e){let t=await em({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function By(e){return JSON.stringify(e,null,2)+`
187
- `}function Ly(e,t,i){return{command:e,exitCode:0,data:t,text:i??By(t)}}function a$(e,t){if(t instanceof gi)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Bs)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 Ls)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof is)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 $n)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 ls)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof rs)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 mi)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof ia)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let i=t.code;if(i&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(i))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let r=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:r?73:65,error:{code:r?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function Vy(e,t){let i=a$(e,t),r=i.error;if(!r)return i;let n=_y({code:r.code,message:r.message,data:i.data});return n?{...i,envelope:n}:i}function Fy(e,t,i=!1){let r=e.envelope??Ay(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...r===void 0?{}:{summary:r.summary,...r.next===void 0?{}:{next:r.next},...r.user_message===void 0?{}:{user_message:r.user_message}},...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
188
- `}:e.error?{exitCode:e.exitCode,stderr:r?Ey(r,e.error.message,i?e.data:void 0):e.error.message}:r?{exitCode:e.exitCode,stdout:Sy(r,i?e.data:void 0)}:i&&e.text!==void 0&&e.data!==void 0&&e.text!==By(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
186
+ `}}var r$=i$().usage;var cJ=10*1024*1024,gi=class extends Error{};function Vd(e,t){let i=e.flatMap((r,n)=>r===t?[n]:[]);if(i.length>1)throw new gi(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function Oy(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new gi(`${t} may only be provided once`);if(i.length===0)return;let r=i[0],n=e[r+1];if(n===void 0||n.startsWith("--"))throw new gi(`${t} requires a value`);return e.splice(r,2),n}function Hy(e){if(e.length>0)throw new gi(`Unexpected argument: ${e[0]}`)}function Dy(e,t){let i=e.shift();if(!i||i.startsWith("--"))throw new gi(`${t} is required`);return i}function Ld(e,t){let i=ra.normalize($y(e)),r=ra.normalize($y(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function $y(e){let t=ra.resolve(e);try{return n$.native(t)}catch{return t}}function a$(e){let t=ra.resolve(e),i=Ee(process.cwd());if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return t;let r=Ee(t);return!r.isGitWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null||!Ld(i.primaryWorktreeRoot,r.primaryWorktreeRoot)||Ld(i.currentWorktreeRoot,r.currentWorktreeRoot)?t:Ld(process.cwd(),i.currentWorktreeRoot)?ra.resolve(process.cwd()):i.currentWorktreeRoot}async function By(e){return e?a$(e):ko(process.cwd())}async function Ly(e){let t=await em({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function Vy(e){return JSON.stringify(e,null,2)+`
187
+ `}function Fy(e,t,i){return{command:e,exitCode:0,data:t,text:i??Vy(t)}}function o$(e,t){if(t instanceof gi)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Bs)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 Ls)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof is)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 $n)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 ls)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof rs)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 mi)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof ia)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let i=t.code;if(i&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(i))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let r=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:r?73:65,error:{code:r?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function qy(e,t){let i=o$(e,t),r=i.error;if(!r)return i;let n=Ty({code:r.code,message:r.message,data:i.data});return n?{...i,envelope:n}:i}function My(e,t,i=!1){let r=e.envelope??Iy(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...r===void 0?{}:{summary:r.summary,...r.next===void 0?{}:{next:r.next},...r.user_message===void 0?{}:{user_message:r.user_message}},...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
188
+ `}:e.error?{exitCode:e.exitCode,stderr:r?xy(r,e.error.message,i?e.data:void 0):e.error.message}:r?{exitCode:e.exitCode,stdout:Cy(r,i?e.data:void 0)}:i&&e.text!==void 0&&e.data!==void 0&&e.text!==Vy(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
189
189
  ${Vt.details}
190
190
  ${JSON.stringify(e.data,null,2)}
191
- `}:{exitCode:e.exitCode,stdout:e.text}}async function qy(e,t){let i=Oy(e,"change name");$y(e);let{config:r,paths:n}=await Dy(t);await xg(n,i);let a=await ws(n,i)?await by({paths:n,name:i}):await py(n,i,{clarificationMode:r.native.clarification_mode,maxVerifyFailures:r.native.max_verify_failures});return Ly("select",{selected:i,continuation:a.continuation},`Selected Native change ${i}
192
- `)}async function My(e,t,i=process.argv.slice(2)){let r=i.indexOf("--"),n=r<0?[...i]:i.slice(0,r),a=r<0?[]:i.slice(r),o=n.includes("--json"),s=n.includes("--verbose"),c,l;try{Vd(n,"--json"),Vd(n,"--verbose"),c=jy(n,"--project-root");let d=[...n,...a],f=await Hy(c);l=await t(d,f)}catch(d){l=Vy(e,d)}let u=Fy(l,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
191
+ `}:{exitCode:e.exitCode,stdout:e.text}}async function Wy(e,t){let i=Dy(e,"change name");Hy(e);let{config:r,paths:n}=await Ly(t);await xg(n,i);let a=await ws(n,i)?await Sy({paths:n,name:i}):await py(n,i,{clarificationMode:r.native.clarification_mode,maxVerifyFailures:r.native.max_verify_failures});return Fy("select",{selected:i,continuation:a.continuation},`Selected Native change ${i}
192
+ `)}async function zy(e,t,i=process.argv.slice(2)){let r=i.indexOf("--"),n=r<0?[...i]:i.slice(0,r),a=r<0?[]:i.slice(r),o=n.includes("--json"),s=n.includes("--verbose"),c,l;try{Vd(n,"--json"),Vd(n,"--verbose"),c=Oy(n,"--project-root");let d=[...n,...a],f=await By(c);l=await t(d,f)}catch(d){l=qy(e,d)}let u=My(l,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
193
193
  `)?"":`
194
- `)),u.exitCode}process.exitCode=await My("select",qy);
194
+ `)),u.exitCode}process.exitCode=await zy("select",Wy);