@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 lv=Object.create;var Yl=Object.defineProperty;var uv=Object.getOwnPropertyDescriptor;var dv=Object.getOwnPropertyNames;var fv=Object.getPrototypeOf,pv=Object.prototype.hasOwnProperty;var mn=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var S=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var hv=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of dv(t))!pv.call(e,n)&&n!==r&&Yl(e,n,{get:()=>t[n],enumerable:!(i=uv(t,n))||i.enumerable});return e};var Kr=(e,t,r)=>(r=e!=null?lv(fv(e)):{},hv(t||!e||!e.__esModule?Yl(r,"default",{value:e,enumerable:!0}):r,e));var A=S(se=>{"use strict";var jo=Symbol.for("yaml.alias"),Xl=Symbol.for("yaml.document"),vn=Symbol.for("yaml.map"),Ql=Symbol.for("yaml.pair"),$o=Symbol.for("yaml.scalar"),gn=Symbol.for("yaml.seq"),ct=Symbol.for("yaml.node.type"),mv=e=>!!e&&typeof e=="object"&&e[ct]===jo,vv=e=>!!e&&typeof e=="object"&&e[ct]===Xl,gv=e=>!!e&&typeof e=="object"&&e[ct]===vn,wv=e=>!!e&&typeof e=="object"&&e[ct]===Ql,Zl=e=>!!e&&typeof e=="object"&&e[ct]===$o,yv=e=>!!e&&typeof e=="object"&&e[ct]===gn;function eu(e){if(e&&typeof e=="object")switch(e[ct]){case vn:case gn:return!0}return!1}function Nv(e){if(e&&typeof e=="object")switch(e[ct]){case jo:case vn:case $o:case gn:return!0}return!1}var bv=e=>(Zl(e)||eu(e))&&!!e.anchor;se.ALIAS=jo;se.DOC=Xl;se.MAP=vn;se.NODE_TYPE=ct;se.PAIR=Ql;se.SCALAR=$o;se.SEQ=gn;se.hasAnchor=bv;se.isAlias=mv;se.isCollection=eu;se.isDocument=vv;se.isMap=gv;se.isNode=Nv;se.isPair=wv;se.isScalar=Zl;se.isSeq=yv});var Yr=S(Oo=>{"use strict";var K=A(),ge=Symbol("break visit"),tu=Symbol("skip children"),Ge=Symbol("remove node");function wn(e,t){let r=ru(t);K.isDocument(e)?dr(null,e.contents,r,Object.freeze([e]))===Ge&&(e.contents=null):dr(null,e,r,Object.freeze([]))}wn.BREAK=ge;wn.SKIP=tu;wn.REMOVE=Ge;function dr(e,t,r,i){let n=iu(e,t,r,i);if(K.isNode(n)||K.isPair(n))return nu(e,i,n),dr(e,n,r,i);if(typeof n!="symbol"){if(K.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=dr(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===ge)return ge;o===Ge&&(t.items.splice(a,1),a-=1)}}}else if(K.isPair(t)){i=Object.freeze(i.concat(t));let a=dr("key",t.key,r,i);if(a===ge)return ge;a===Ge&&(t.key=null);let o=dr("value",t.value,r,i);if(o===ge)return ge;o===Ge&&(t.value=null)}}return n}async function yn(e,t){let r=ru(t);K.isDocument(e)?await fr(null,e.contents,r,Object.freeze([e]))===Ge&&(e.contents=null):await fr(null,e,r,Object.freeze([]))}yn.BREAK=ge;yn.SKIP=tu;yn.REMOVE=Ge;async function fr(e,t,r,i){let n=await iu(e,t,r,i);if(K.isNode(n)||K.isPair(n))return nu(e,i,n),fr(e,n,r,i);if(typeof n!="symbol"){if(K.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await fr(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===ge)return ge;o===Ge&&(t.items.splice(a,1),a-=1)}}}else if(K.isPair(t)){i=Object.freeze(i.concat(t));let a=await fr("key",t.key,r,i);if(a===ge)return ge;a===Ge&&(t.key=null);let o=await fr("value",t.value,r,i);if(o===ge)return ge;o===Ge&&(t.value=null)}}return n}function ru(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 iu(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(K.isMap(t))return r.Map?.(e,t,i);if(K.isSeq(t))return r.Seq?.(e,t,i);if(K.isPair(t))return r.Pair?.(e,t,i);if(K.isScalar(t))return r.Scalar?.(e,t,i);if(K.isAlias(t))return r.Alias?.(e,t,i)}function nu(e,t,r){let i=t[t.length-1];if(K.isCollection(i))i.items[e]=r;else if(K.isPair(i))e==="key"?i.key=r:i.value=r;else if(K.isDocument(i))i.contents=r;else{let n=K.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}Oo.visit=wn;Oo.visitAsync=yn});var Ho=S(ou=>{"use strict";var au=A(),kv=Yr(),Sv={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Ev=e=>e.replace(/[!,[\]{}]/g,t=>Sv[t]),Xr=class e{constructor(t,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,r)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,r){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let i=t.trim().split(/[ \t]+/),n=i.shift();switch(n){case"%TAG":{if(i.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[a,o]=i;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;let[a]=i;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return r(6,`Unsupported YAML version ${a}`,o),!1}}default:return r(0,`Unknown directive ${n}`,!0),!1}}tagName(t,r){if(t==="!")return"!";if(t[0]!=="!")return r(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}let[,i,n]=t.match(/^(.*!)([^!]*)$/s);n||r(`The ${t} tag has no suffix`);let a=this.tags[i];if(a)try{return a+decodeURIComponent(n)}catch(o){return r(String(o)),null}return i==="!"?t:(r(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[r,i]of Object.entries(this.tags))if(t.startsWith(i))return r+Ev(t.substring(i.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),n;if(t&&i.length>0&&au.isNode(t.contents)){let a={};kv.visit(t.contents,(o,s)=>{au.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of i)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&r.push(`%TAG ${a} ${o}`);return r.join(`
5
- `)}};Xr.defaultYaml={explicit:!1,version:"1.2"};Xr.defaultTags={"!!":"tag:yaml.org,2002:"};ou.Directives=Xr});var Nn=S(Qr=>{"use strict";var su=A(),xv=Yr();function Cv(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(r)}return!0}function cu(e){let t=new Set;return xv.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function lu(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function Pv(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=cu(e));let o=lu(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(su.isScalar(o.node)||su.isCollection(o.node)))o.node.anchor=o.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=a,s}}},sourceObjects:i}}Qr.anchorIsValid=Cv;Qr.anchorNames=cu;Qr.createNodeAnchors=Pv;Qr.findNewAnchor=lu});var Do=S(uu=>{"use strict";function Zr(e,t,r,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let n=0,a=i.length;n<a;++n){let o=i[n],s=Zr(e,i,String(n),o);s===void 0?delete i[n]:s!==o&&(i[n]=s)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let a=i.get(n),o=Zr(e,i,n,a);o===void 0?i.delete(n):o!==a&&i.set(n,o)}else if(i instanceof Set)for(let n of Array.from(i)){let a=Zr(e,i,n,n);a===void 0?i.delete(n):a!==n&&(i.delete(n),i.add(a))}else for(let[n,a]of Object.entries(i)){let o=Zr(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}uu.applyReviver=Zr});var kt=S(fu=>{"use strict";var Rv=A();function du(e,t,r){if(Array.isArray(e))return e.map((i,n)=>du(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!Rv.hasAnchor(e))return e.toJSON(t,r);let i={aliasCount:0,count:1,res:void 0};r.anchors.set(e,i),r.onCreate=a=>{i.res=a,delete r.onCreate};let n=e.toJSON(t,r);return r.onCreate&&r.onCreate(n),n}return typeof e=="bigint"&&!r?.keep?Number(e):e}fu.toJS=du});var bn=S(hu=>{"use strict";var Av=Do(),pu=A(),_v=kt(),Bo=class{constructor(t){Object.defineProperty(this,pu.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:r,maxAliasCount:i,onAnchor:n,reviver:a}={}){if(!pu.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},s=_v.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?Av.applyReviver(a,{"":s},"",s):s}};hu.NodeBase=Bo});var ei=S(mu=>{"use strict";var Iv=Nn(),Tv=Yr(),pr=A(),jv=bn(),$v=kt(),Lo=class extends jv.NodeBase{constructor(t){super(pr.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,r){if(r?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;r?.aliasResolveCache?i=r.aliasResolveCache:(i=[],Tv.visit(t,{Node:(a,o)=>{(pr.isAlias(o)||pr.hasAnchor(o))&&i.push(o)}}),r&&(r.aliasResolveCache=i));let n;for(let a of i){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,r){if(!r)return{source:this.source};let{anchors:i,doc:n,maxAliasCount:a}=r,o=this.resolve(n,r);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=i.get(o);if(s||($v.toJS(o,null,r),s=i.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=kn(n,o,i)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,r,i){let n=`*${this.source}`;if(t){if(Iv.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 kn(e,t,r){if(pr.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(pr.isCollection(t)){let i=0;for(let n of t.items){let a=kn(e,n,r);a>i&&(i=a)}return i}else if(pr.isPair(t)){let i=kn(e,t.key,r),n=kn(e,t.value,r);return Math.max(i,n)}return 1}mu.Alias=Lo});var G=S(Vo=>{"use strict";var Ov=A(),Hv=bn(),Dv=kt(),Bv=e=>!e||typeof e!="function"&&typeof e!="object",St=class extends Hv.NodeBase{constructor(t){super(Ov.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:Dv.toJS(this.value,t,r)}toString(){return String(this.value)}};St.BLOCK_FOLDED="BLOCK_FOLDED";St.BLOCK_LITERAL="BLOCK_LITERAL";St.PLAIN="PLAIN";St.QUOTE_DOUBLE="QUOTE_DOUBLE";St.QUOTE_SINGLE="QUOTE_SINGLE";Vo.Scalar=St;Vo.isScalarValue=Bv});var ti=S(gu=>{"use strict";var Lv=ei(),Gt=A(),vu=G(),Vv="tag:yaml.org,2002:";function Mv(e,t,r){if(t){let i=r.filter(a=>a.tag===t),n=i.find(a=>!a.format)??i[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return r.find(i=>i.identify?.(e)&&!i.format)}function Fv(e,t,r){if(Gt.isDocument(e)&&(e=e.contents),Gt.isNode(e))return e;if(Gt.isPair(e)){let u=r.schema[Gt.MAP].createNode?.(r.schema,null,r);return u.items.push(e),u}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:i,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=r,c;if(i&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new Lv.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=Vv+t.slice(2));let l=Mv(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let u=new vu.Scalar(e);return c&&(c.node=u),u}l=e instanceof Map?o[Gt.MAP]:Symbol.iterator in Object(e)?o[Gt.SEQ]:o[Gt.MAP]}a&&(a(l),delete r.onTagObj);let f=l?.createNode?l.createNode(r.schema,e,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,e,r):new vu.Scalar(e);return t?f.tag=t:l.default||(f.tag=l.tag),c&&(c.node=f),f}gu.createNode=Fv});var En=S(Sn=>{"use strict";var qv=ti(),Ue=A(),Wv=bn();function Mo(e,t,r){let i=r;for(let n=t.length-1;n>=0;--n){let a=t[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=i,i=o}else i=new Map([[a,i]])}return qv.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var wu=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Fo=class extends Wv.NodeBase{constructor(t,r){super(t),Object.defineProperty(this,"schema",{value:r,configurable:!0,enumerable:!1,writable:!0})}clone(t){let r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(r.schema=t),r.items=r.items.map(i=>Ue.isNode(i)||Ue.isPair(i)?i.clone(t):i),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(wu(t))this.add(r);else{let[i,...n]=t,a=this.get(i,!0);if(Ue.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,Mo(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}deleteIn(t){let[r,...i]=t;if(i.length===0)return this.delete(r);let n=this.get(r,!0);if(Ue.isCollection(n))return n.deleteIn(i);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}getIn(t,r){let[i,...n]=t,a=this.get(i,!0);return n.length===0?!r&&Ue.isScalar(a)?a.value:a:Ue.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!Ue.isPair(r))return!1;let i=r.value;return i==null||t&&Ue.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(t){let[r,...i]=t;if(i.length===0)return this.has(r);let n=this.get(r,!0);return Ue.isCollection(n)?n.hasIn(i):!1}setIn(t,r){let[i,...n]=t;if(n.length===0)this.set(i,r);else{let a=this.get(i,!0);if(Ue.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,Mo(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};Sn.Collection=Fo;Sn.collectionFromPath=Mo;Sn.isEmptyPath=wu});var ri=S(xn=>{"use strict";var zv=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function qo(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Jv=(e,t,r)=>e.endsWith(`
4
+ var dv=Object.create;var Yl=Object.defineProperty;var fv=Object.getOwnPropertyDescriptor;var pv=Object.getOwnPropertyNames;var hv=Object.getPrototypeOf,mv=Object.prototype.hasOwnProperty;var mn=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var S=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var vv=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of pv(t))!mv.call(e,n)&&n!==r&&Yl(e,n,{get:()=>t[n],enumerable:!(i=fv(t,n))||i.enumerable});return e};var Kr=(e,t,r)=>(r=e!=null?dv(hv(e)):{},vv(t||!e||!e.__esModule?Yl(r,"default",{value:e,enumerable:!0}):r,e));var A=S(se=>{"use strict";var jo=Symbol.for("yaml.alias"),Xl=Symbol.for("yaml.document"),vn=Symbol.for("yaml.map"),Ql=Symbol.for("yaml.pair"),$o=Symbol.for("yaml.scalar"),gn=Symbol.for("yaml.seq"),ct=Symbol.for("yaml.node.type"),gv=e=>!!e&&typeof e=="object"&&e[ct]===jo,wv=e=>!!e&&typeof e=="object"&&e[ct]===Xl,yv=e=>!!e&&typeof e=="object"&&e[ct]===vn,Nv=e=>!!e&&typeof e=="object"&&e[ct]===Ql,Zl=e=>!!e&&typeof e=="object"&&e[ct]===$o,bv=e=>!!e&&typeof e=="object"&&e[ct]===gn;function eu(e){if(e&&typeof e=="object")switch(e[ct]){case vn:case gn:return!0}return!1}function kv(e){if(e&&typeof e=="object")switch(e[ct]){case jo:case vn:case $o:case gn:return!0}return!1}var Sv=e=>(Zl(e)||eu(e))&&!!e.anchor;se.ALIAS=jo;se.DOC=Xl;se.MAP=vn;se.NODE_TYPE=ct;se.PAIR=Ql;se.SCALAR=$o;se.SEQ=gn;se.hasAnchor=Sv;se.isAlias=gv;se.isCollection=eu;se.isDocument=wv;se.isMap=yv;se.isNode=kv;se.isPair=Nv;se.isScalar=Zl;se.isSeq=bv});var Yr=S(Oo=>{"use strict";var K=A(),ge=Symbol("break visit"),tu=Symbol("skip children"),Ge=Symbol("remove node");function wn(e,t){let r=ru(t);K.isDocument(e)?dr(null,e.contents,r,Object.freeze([e]))===Ge&&(e.contents=null):dr(null,e,r,Object.freeze([]))}wn.BREAK=ge;wn.SKIP=tu;wn.REMOVE=Ge;function dr(e,t,r,i){let n=iu(e,t,r,i);if(K.isNode(n)||K.isPair(n))return nu(e,i,n),dr(e,n,r,i);if(typeof n!="symbol"){if(K.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=dr(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===ge)return ge;o===Ge&&(t.items.splice(a,1),a-=1)}}}else if(K.isPair(t)){i=Object.freeze(i.concat(t));let a=dr("key",t.key,r,i);if(a===ge)return ge;a===Ge&&(t.key=null);let o=dr("value",t.value,r,i);if(o===ge)return ge;o===Ge&&(t.value=null)}}return n}async function yn(e,t){let r=ru(t);K.isDocument(e)?await fr(null,e.contents,r,Object.freeze([e]))===Ge&&(e.contents=null):await fr(null,e,r,Object.freeze([]))}yn.BREAK=ge;yn.SKIP=tu;yn.REMOVE=Ge;async function fr(e,t,r,i){let n=await iu(e,t,r,i);if(K.isNode(n)||K.isPair(n))return nu(e,i,n),fr(e,n,r,i);if(typeof n!="symbol"){if(K.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await fr(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===ge)return ge;o===Ge&&(t.items.splice(a,1),a-=1)}}}else if(K.isPair(t)){i=Object.freeze(i.concat(t));let a=await fr("key",t.key,r,i);if(a===ge)return ge;a===Ge&&(t.key=null);let o=await fr("value",t.value,r,i);if(o===ge)return ge;o===Ge&&(t.value=null)}}return n}function ru(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 iu(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(K.isMap(t))return r.Map?.(e,t,i);if(K.isSeq(t))return r.Seq?.(e,t,i);if(K.isPair(t))return r.Pair?.(e,t,i);if(K.isScalar(t))return r.Scalar?.(e,t,i);if(K.isAlias(t))return r.Alias?.(e,t,i)}function nu(e,t,r){let i=t[t.length-1];if(K.isCollection(i))i.items[e]=r;else if(K.isPair(i))e==="key"?i.key=r:i.value=r;else if(K.isDocument(i))i.contents=r;else{let n=K.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}Oo.visit=wn;Oo.visitAsync=yn});var Ho=S(ou=>{"use strict";var au=A(),Ev=Yr(),xv={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Cv=e=>e.replace(/[!,[\]{}]/g,t=>xv[t]),Xr=class e{constructor(t,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,r)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,r){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let i=t.trim().split(/[ \t]+/),n=i.shift();switch(n){case"%TAG":{if(i.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[a,o]=i;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;let[a]=i;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return r(6,`Unsupported YAML version ${a}`,o),!1}}default:return r(0,`Unknown directive ${n}`,!0),!1}}tagName(t,r){if(t==="!")return"!";if(t[0]!=="!")return r(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}let[,i,n]=t.match(/^(.*!)([^!]*)$/s);n||r(`The ${t} tag has no suffix`);let a=this.tags[i];if(a)try{return a+decodeURIComponent(n)}catch(o){return r(String(o)),null}return i==="!"?t:(r(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[r,i]of Object.entries(this.tags))if(t.startsWith(i))return r+Cv(t.substring(i.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),n;if(t&&i.length>0&&au.isNode(t.contents)){let a={};Ev.visit(t.contents,(o,s)=>{au.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of i)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&r.push(`%TAG ${a} ${o}`);return r.join(`
5
+ `)}};Xr.defaultYaml={explicit:!1,version:"1.2"};Xr.defaultTags={"!!":"tag:yaml.org,2002:"};ou.Directives=Xr});var Nn=S(Qr=>{"use strict";var su=A(),Pv=Yr();function Rv(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(r)}return!0}function cu(e){let t=new Set;return Pv.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function lu(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function Av(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=cu(e));let o=lu(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(su.isScalar(o.node)||su.isCollection(o.node)))o.node.anchor=o.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=a,s}}},sourceObjects:i}}Qr.anchorIsValid=Rv;Qr.anchorNames=cu;Qr.createNodeAnchors=Av;Qr.findNewAnchor=lu});var Do=S(uu=>{"use strict";function Zr(e,t,r,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let n=0,a=i.length;n<a;++n){let o=i[n],s=Zr(e,i,String(n),o);s===void 0?delete i[n]:s!==o&&(i[n]=s)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let a=i.get(n),o=Zr(e,i,n,a);o===void 0?i.delete(n):o!==a&&i.set(n,o)}else if(i instanceof Set)for(let n of Array.from(i)){let a=Zr(e,i,n,n);a===void 0?i.delete(n):a!==n&&(i.delete(n),i.add(a))}else for(let[n,a]of Object.entries(i)){let o=Zr(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}uu.applyReviver=Zr});var kt=S(fu=>{"use strict";var _v=A();function du(e,t,r){if(Array.isArray(e))return e.map((i,n)=>du(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!_v.hasAnchor(e))return e.toJSON(t,r);let i={aliasCount:0,count:1,res:void 0};r.anchors.set(e,i),r.onCreate=a=>{i.res=a,delete r.onCreate};let n=e.toJSON(t,r);return r.onCreate&&r.onCreate(n),n}return typeof e=="bigint"&&!r?.keep?Number(e):e}fu.toJS=du});var bn=S(hu=>{"use strict";var Iv=Do(),pu=A(),Tv=kt(),Bo=class{constructor(t){Object.defineProperty(this,pu.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:r,maxAliasCount:i,onAnchor:n,reviver:a}={}){if(!pu.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},s=Tv.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?Iv.applyReviver(a,{"":s},"",s):s}};hu.NodeBase=Bo});var ei=S(mu=>{"use strict";var jv=Nn(),$v=Yr(),pr=A(),Ov=bn(),Hv=kt(),Lo=class extends Ov.NodeBase{constructor(t){super(pr.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,r){if(r?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;r?.aliasResolveCache?i=r.aliasResolveCache:(i=[],$v.visit(t,{Node:(a,o)=>{(pr.isAlias(o)||pr.hasAnchor(o))&&i.push(o)}}),r&&(r.aliasResolveCache=i));let n;for(let a of i){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,r){if(!r)return{source:this.source};let{anchors:i,doc:n,maxAliasCount:a}=r,o=this.resolve(n,r);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=i.get(o);if(s||(Hv.toJS(o,null,r),s=i.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=kn(n,o,i)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,r,i){let n=`*${this.source}`;if(t){if(jv.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 kn(e,t,r){if(pr.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(pr.isCollection(t)){let i=0;for(let n of t.items){let a=kn(e,n,r);a>i&&(i=a)}return i}else if(pr.isPair(t)){let i=kn(e,t.key,r),n=kn(e,t.value,r);return Math.max(i,n)}return 1}mu.Alias=Lo});var G=S(Vo=>{"use strict";var Dv=A(),Bv=bn(),Lv=kt(),Vv=e=>!e||typeof e!="function"&&typeof e!="object",St=class extends Bv.NodeBase{constructor(t){super(Dv.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:Lv.toJS(this.value,t,r)}toString(){return String(this.value)}};St.BLOCK_FOLDED="BLOCK_FOLDED";St.BLOCK_LITERAL="BLOCK_LITERAL";St.PLAIN="PLAIN";St.QUOTE_DOUBLE="QUOTE_DOUBLE";St.QUOTE_SINGLE="QUOTE_SINGLE";Vo.Scalar=St;Vo.isScalarValue=Vv});var ti=S(gu=>{"use strict";var Mv=ei(),Gt=A(),vu=G(),Fv="tag:yaml.org,2002:";function qv(e,t,r){if(t){let i=r.filter(a=>a.tag===t),n=i.find(a=>!a.format)??i[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return r.find(i=>i.identify?.(e)&&!i.format)}function Wv(e,t,r){if(Gt.isDocument(e)&&(e=e.contents),Gt.isNode(e))return e;if(Gt.isPair(e)){let u=r.schema[Gt.MAP].createNode?.(r.schema,null,r);return u.items.push(e),u}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:i,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=r,c;if(i&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new Mv.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=Fv+t.slice(2));let l=qv(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let u=new vu.Scalar(e);return c&&(c.node=u),u}l=e instanceof Map?o[Gt.MAP]:Symbol.iterator in Object(e)?o[Gt.SEQ]:o[Gt.MAP]}a&&(a(l),delete r.onTagObj);let f=l?.createNode?l.createNode(r.schema,e,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,e,r):new vu.Scalar(e);return t?f.tag=t:l.default||(f.tag=l.tag),c&&(c.node=f),f}gu.createNode=Wv});var En=S(Sn=>{"use strict";var zv=ti(),Ue=A(),Jv=bn();function Mo(e,t,r){let i=r;for(let n=t.length-1;n>=0;--n){let a=t[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=i,i=o}else i=new Map([[a,i]])}return zv.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var wu=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Fo=class extends Jv.NodeBase{constructor(t,r){super(t),Object.defineProperty(this,"schema",{value:r,configurable:!0,enumerable:!1,writable:!0})}clone(t){let r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(r.schema=t),r.items=r.items.map(i=>Ue.isNode(i)||Ue.isPair(i)?i.clone(t):i),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(wu(t))this.add(r);else{let[i,...n]=t,a=this.get(i,!0);if(Ue.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,Mo(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}deleteIn(t){let[r,...i]=t;if(i.length===0)return this.delete(r);let n=this.get(r,!0);if(Ue.isCollection(n))return n.deleteIn(i);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}getIn(t,r){let[i,...n]=t,a=this.get(i,!0);return n.length===0?!r&&Ue.isScalar(a)?a.value:a:Ue.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!Ue.isPair(r))return!1;let i=r.value;return i==null||t&&Ue.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(t){let[r,...i]=t;if(i.length===0)return this.has(r);let n=this.get(r,!0);return Ue.isCollection(n)?n.hasIn(i):!1}setIn(t,r){let[i,...n]=t;if(n.length===0)this.set(i,r);else{let a=this.get(i,!0);if(Ue.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,Mo(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};Sn.Collection=Fo;Sn.collectionFromPath=Mo;Sn.isEmptyPath=wu});var ri=S(xn=>{"use strict";var Gv=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function qo(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Uv=(e,t,r)=>e.endsWith(`
6
6
  `)?qo(r,t):r.includes(`
7
7
  `)?`
8
- `+qo(r,t):(e.endsWith(" ")?"":" ")+r;xn.indentComment=qo;xn.lineComment=Jv;xn.stringifyComment=zv});var Nu=S(ii=>{"use strict";var Gv="flow",Wo="block",Cn="quoted";function Uv(e,t,r="flow",{indentAtStart:i,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;n<a&&(a=0);let c=Math.max(1+a,1+n-t.length);if(e.length<=c)return e;let l=[],f={},u=n-t.length;typeof i=="number"&&(i>n-Math.max(2,a)?l.push(0):u=n-i);let d,m,v=!1,h=-1,p=-1,w=-1;r===Wo&&(h=yu(e,h,t.length),h!==-1&&(u=h+c));for(let y;y=e[h+=1];){if(r===Cn&&y==="\\"){switch(p=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}w=h}if(y===`
8
+ `+qo(r,t):(e.endsWith(" ")?"":" ")+r;xn.indentComment=qo;xn.lineComment=Uv;xn.stringifyComment=Gv});var Nu=S(ii=>{"use strict";var Kv="flow",Wo="block",Cn="quoted";function Yv(e,t,r="flow",{indentAtStart:i,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;n<a&&(a=0);let c=Math.max(1+a,1+n-t.length);if(e.length<=c)return e;let l=[],f={},u=n-t.length;typeof i=="number"&&(i>n-Math.max(2,a)?l.push(0):u=n-i);let d,m,v=!1,h=-1,p=-1,w=-1;r===Wo&&(h=yu(e,h,t.length),h!==-1&&(u=h+c));for(let y;y=e[h+=1];){if(r===Cn&&y==="\\"){switch(p=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}w=h}if(y===`
9
9
  `)r===Wo&&(h=yu(e,h,t.length)),u=h+t.length+c,d=void 0;else{if(y===" "&&m&&m!==" "&&m!==`
10
10
  `&&m!==" "){let b=e[h+1];b&&b!==" "&&b!==`
11
11
  `&&b!==" "&&(d=h)}if(h>=u)if(d)l.push(d),u=d+c,d=void 0;else if(r===Cn){for(;m===" "||m===" ";)m=y,y=e[h+=1],v=!0;let b=h>w+1?h-2:p-1;if(f[b])return e;l.push(b),f[b]=!0,u=b+c,d=void 0}else v=!0}m=y}if(v&&s&&s(),l.length===0)return e;o&&o();let g=e.slice(0,l[0]);for(let y=0;y<l.length;++y){let b=l[y],N=l[y+1]||e.length;b===0?g=`
12
12
  ${t}${e.slice(0,N)}`:(r===Cn&&f[b]&&(g+=`${e[b]}\\`),g+=`
13
13
  ${t}${e.slice(b+1,N)}`)}return g}function yu(e,t,r){let i=t,n=t+1,a=e[n];for(;a===" "||a===" ";)if(t<n+r)a=e[++t];else{do a=e[++t];while(a&&a!==`
14
- `);i=t,n=t+1,a=e[n]}return i}ii.FOLD_BLOCK=Wo;ii.FOLD_FLOW=Gv;ii.FOLD_QUOTED=Cn;ii.foldFlowLines=Uv});var ai=S(bu=>{"use strict";var $e=G(),Et=Nu(),Rn=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),An=e=>/^(%|---|\.\.\.)/m.test(e);function Kv(e,t,r){if(!t||t<0)return!1;let i=t-r,n=e.length;if(n<=i)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
14
+ `);i=t,n=t+1,a=e[n]}return i}ii.FOLD_BLOCK=Wo;ii.FOLD_FLOW=Kv;ii.FOLD_QUOTED=Cn;ii.foldFlowLines=Yv});var ai=S(bu=>{"use strict";var $e=G(),Et=Nu(),Rn=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),An=e=>/^(%|---|\.\.\.)/m.test(e);function Xv(e,t,r){if(!t||t<0)return!1;let i=t-r,n=e.length;if(n<=i)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
15
15
  `){if(a-o>i)return!0;if(o=a+1,n-o<=i)return!1}return!0}function ni(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:i}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(An(e)?" ":""),o="",s=0;for(let c=0,l=r[c];l;l=r[++c])if(l===" "&&r[c+1]==="\\"&&r[c+2]==="n"&&(o+=r.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(r[c+1]){case"u":{o+=r.slice(s,c);let f=r.substr(c+2,4);switch(f){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:f.substr(0,2)==="00"?o+="\\x"+f.substr(2):o+=r.substr(c,6)}c+=5,s=c+1}break;case"n":if(i||r[c+2]==='"'||r.length<n)c+=1;else{for(o+=r.slice(s,c)+`
16
16
 
17
17
  `;r[c+2]==="\\"&&r[c+3]==="n"&&r[c+4]!=='"';)o+=`
@@ -20,7 +20,7 @@ ${t}${e.slice(b+1,N)}`)}return g}function yu(e,t,r){let i=t,n=t+1,a=e[n];for(;a=
20
20
  ${r}`)+"'";return t.implicitKey?i:Et.foldFlowLines(i,r,Et.FOLD_FLOW,Rn(t,!1))}function hr(e,t){let{singleQuote:r}=t.options,i;if(r===!1)i=ni;else{let n=e.includes('"'),a=e.includes("'");n&&!a?i=zo:a&&!n?i=ni:i=r?zo:ni}return i(e,t)}var Jo;try{Jo=new RegExp(`(^|(?<!
21
21
  ))
22
22
  +(?!
23
- |$)`,"g")}catch{Jo=/\n+(?!\n|$)/g}function Pn({comment:e,type:t,value:r},i,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=i.options;if(!o||/\n[\t ]+$/.test(r))return hr(r,i);let l=i.indent||(i.forceBlockIndent||An(r)?" ":""),f=o==="literal"?!0:o==="folded"||t===$e.Scalar.BLOCK_FOLDED?!1:t===$e.Scalar.BLOCK_LITERAL?!0:!Kv(r,c,l.length);if(!r)return f?`|
23
+ |$)`,"g")}catch{Jo=/\n+(?!\n|$)/g}function Pn({comment:e,type:t,value:r},i,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=i.options;if(!o||/\n[\t ]+$/.test(r))return hr(r,i);let l=i.indent||(i.forceBlockIndent||An(r)?" ":""),f=o==="literal"?!0:o==="folded"||t===$e.Scalar.BLOCK_FOLDED?!1:t===$e.Scalar.BLOCK_LITERAL?!0:!Xv(r,c,l.length);if(!r)return f?`|
24
24
  `:`>
25
25
  `;let u,d;for(d=r.length;d>0;--d){let N=r[d-1];if(N!==`
26
26
  `&&N!==" "&&N!==" ")break}let m=r.substring(d),v=m.indexOf(`
@@ -29,12 +29,12 @@ ${r}`)+"'";return t.implicitKey?i:Et.foldFlowLines(i,r,Et.FOLD_FLOW,Rn(t,!1))}fu
29
29
  `)w=p;else break}let g=r.substring(0,w<p?w+1:p);g&&(r=r.substring(g.length),g=g.replace(/\n+/g,`$&${l}`));let b=(h?l?"2":"1":"")+u;if(e&&(b+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!f){let N=r.replace(/\n+/g,`
30
30
  $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),E=!1,P=Rn(i,!0);o!=="folded"&&t!==$e.Scalar.BLOCK_FOLDED&&(P.onOverflow=()=>{E=!0});let k=Et.foldFlowLines(`${g}${N}${m}`,l,Et.FOLD_BLOCK,P);if(!E)return`>${b}
31
31
  ${l}${k}`}return r=r.replace(/\n+/g,`$&${l}`),`|${b}
32
- ${l}${g}${r}${m}`}function Yv(e,t,r,i){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:f}=t;if(s&&a.includes(`
32
+ ${l}${g}${r}${m}`}function Qv(e,t,r,i){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:f}=t;if(s&&a.includes(`
33
33
  `)||f&&/[[\]{},]/.test(a))return hr(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||f||!a.includes(`
34
34
  `)?hr(a,t):Pn(e,t,r,i);if(!s&&!f&&n!==$e.Scalar.PLAIN&&a.includes(`
35
35
  `))return Pn(e,t,r,i);if(An(a)){if(c==="")return t.forceBlockIndent=!0,Pn(e,t,r,i);if(s&&c===l)return hr(a,t)}let u=a.replace(/\n+/g,`$&
36
- ${c}`);if(o){let d=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(u),{compat:m,tags:v}=t.doc.schema;if(v.some(d)||m?.some(d))return hr(a,t)}return s?u:Et.foldFlowLines(u,c,Et.FOLD_FLOW,Rn(t,!1))}function Xv(e,t,r,i){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==$e.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=$e.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case $e.Scalar.BLOCK_FOLDED:case $e.Scalar.BLOCK_LITERAL:return n||a?hr(o.value,t):Pn(o,t,r,i);case $e.Scalar.QUOTE_DOUBLE:return ni(o.value,t);case $e.Scalar.QUOTE_SINGLE:return zo(o.value,t);case $e.Scalar.PLAIN:return Yv(o,t,r,i);default:return null}},l=c(s);if(l===null){let{defaultKeyType:f,defaultStringType:u}=t.options,d=n&&f||u;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}bu.stringifyString=Xv});var oi=S(Go=>{"use strict";var Qv=Nn(),xt=A(),Zv=ri(),eg=ai();function tg(e,t){let r=Object.assign({blockQuote:!0,commentString:Zv.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),i;switch(r.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:e,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:i,options:r}}function rg(e,t){if(t.tag){let n=e.filter(a=>a.tag===t.tag);if(n.length>0)return n.find(a=>a.format===t.format)??n[0]}let r,i;if(xt.isScalar(t)){i=t.value;let n=e.filter(a=>a.identify?.(i));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}r=n.find(a=>a.format===t.format)??n.find(a=>!a.format)}else i=t,r=e.find(n=>n.nodeClass&&i instanceof n.nodeClass);if(!r){let n=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${n} value`)}return r}function ig(e,t,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=(xt.isScalar(e)||xt.isCollection(e))&&e.anchor;a&&Qv.anchorIsValid(a)&&(r.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(i.directives.tagString(o)),n.join(" ")}function ng(e,t,r,i){if(xt.isPair(e))return e.toString(t,r,i);if(xt.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=xt.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=rg(t.doc.schema.tags,a));let o=ig(a,n,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,t,r,i):xt.isScalar(a)?eg.stringifyString(a,t,r,i):a.toString(t,r,i);return o?xt.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
- ${t.indent}${s}`:s}Go.createStringifyContext=tg;Go.stringify=ng});var xu=S(Eu=>{"use strict";var lt=A(),ku=G(),Su=oi(),si=ri();function ag({key:e,value:t},r,i,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:f,simpleKeys:u}}=r,d=lt.isNode(e)&&e.comment||null;if(u){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(lt.isCollection(e)||!lt.isNode(e)&&typeof e=="object"){let P="With simple keys, collection cannot be used as a key value";throw new Error(P)}}let m=!u&&(!e||d&&t==null&&!r.inFlow||lt.isCollection(e)||(lt.isScalar(e)?e.type===ku.Scalar.BLOCK_FOLDED||e.type===ku.Scalar.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!m&&(u||!a),indent:s+c});let v=!1,h=!1,p=Su.stringify(e,r,()=>v=!0,()=>h=!0);if(!m&&!r.inFlow&&p.length>1024){if(u)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");m=!0}if(r.inFlow){if(a||t==null)return v&&i&&i(),p===""?"?":m?`? ${p}`:p}else if(a&&!u||t==null&&m)return p=`? ${p}`,d&&!v?p+=si.lineComment(p,r.indent,l(d)):h&&n&&n(),p;v&&(d=null),m?(d&&(p+=si.lineComment(p,r.indent,l(d))),p=`? ${p}
36
+ ${c}`);if(o){let d=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(u),{compat:m,tags:v}=t.doc.schema;if(v.some(d)||m?.some(d))return hr(a,t)}return s?u:Et.foldFlowLines(u,c,Et.FOLD_FLOW,Rn(t,!1))}function Zv(e,t,r,i){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==$e.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=$e.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case $e.Scalar.BLOCK_FOLDED:case $e.Scalar.BLOCK_LITERAL:return n||a?hr(o.value,t):Pn(o,t,r,i);case $e.Scalar.QUOTE_DOUBLE:return ni(o.value,t);case $e.Scalar.QUOTE_SINGLE:return zo(o.value,t);case $e.Scalar.PLAIN:return Qv(o,t,r,i);default:return null}},l=c(s);if(l===null){let{defaultKeyType:f,defaultStringType:u}=t.options,d=n&&f||u;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}bu.stringifyString=Zv});var oi=S(Go=>{"use strict";var eg=Nn(),xt=A(),tg=ri(),rg=ai();function ig(e,t){let r=Object.assign({blockQuote:!0,commentString:tg.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),i;switch(r.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:e,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:i,options:r}}function ng(e,t){if(t.tag){let n=e.filter(a=>a.tag===t.tag);if(n.length>0)return n.find(a=>a.format===t.format)??n[0]}let r,i;if(xt.isScalar(t)){i=t.value;let n=e.filter(a=>a.identify?.(i));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}r=n.find(a=>a.format===t.format)??n.find(a=>!a.format)}else i=t,r=e.find(n=>n.nodeClass&&i instanceof n.nodeClass);if(!r){let n=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${n} value`)}return r}function ag(e,t,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=(xt.isScalar(e)||xt.isCollection(e))&&e.anchor;a&&eg.anchorIsValid(a)&&(r.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(i.directives.tagString(o)),n.join(" ")}function og(e,t,r,i){if(xt.isPair(e))return e.toString(t,r,i);if(xt.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=xt.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=ng(t.doc.schema.tags,a));let o=ag(a,n,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,t,r,i):xt.isScalar(a)?rg.stringifyString(a,t,r,i):a.toString(t,r,i);return o?xt.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
+ ${t.indent}${s}`:s}Go.createStringifyContext=ig;Go.stringify=og});var xu=S(Eu=>{"use strict";var lt=A(),ku=G(),Su=oi(),si=ri();function sg({key:e,value:t},r,i,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:f,simpleKeys:u}}=r,d=lt.isNode(e)&&e.comment||null;if(u){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(lt.isCollection(e)||!lt.isNode(e)&&typeof e=="object"){let P="With simple keys, collection cannot be used as a key value";throw new Error(P)}}let m=!u&&(!e||d&&t==null&&!r.inFlow||lt.isCollection(e)||(lt.isScalar(e)?e.type===ku.Scalar.BLOCK_FOLDED||e.type===ku.Scalar.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!m&&(u||!a),indent:s+c});let v=!1,h=!1,p=Su.stringify(e,r,()=>v=!0,()=>h=!0);if(!m&&!r.inFlow&&p.length>1024){if(u)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");m=!0}if(r.inFlow){if(a||t==null)return v&&i&&i(),p===""?"?":m?`? ${p}`:p}else if(a&&!u||t==null&&m)return p=`? ${p}`,d&&!v?p+=si.lineComment(p,r.indent,l(d)):h&&n&&n(),p;v&&(d=null),m?(d&&(p+=si.lineComment(p,r.indent,l(d))),p=`? ${p}
38
38
  ${s}:`):(p=`${p}:`,d&&(p+=si.lineComment(p,r.indent,l(d))));let w,g,y;lt.isNode(t)?(w=!!t.spaceBefore,g=t.commentBefore,y=t.comment):(w=!1,g=null,y=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!m&&!d&&lt.isScalar(t)&&(r.indentAtStart=p.length+1),h=!1,!f&&c.length>=2&&!r.inFlow&&!m&&lt.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let b=!1,N=Su.stringify(t,r,()=>b=!0,()=>h=!0),E=" ";if(d||w||g){if(E=w?`
39
39
  `:"",g){let P=l(g);E+=`
40
40
  ${si.indentComment(P,r.indent)}`}N===""&&!r.inFlow?E===`
@@ -44,32 +44,32 @@ ${si.indentComment(P,r.indent)}`}N===""&&!r.inFlow?E===`
44
44
  ${r.indent}`}else if(!m&&lt.isCollection(t)){let P=N[0],k=N.indexOf(`
45
45
  `),T=k!==-1,F=r.inFlow??t.flow??t.items.length===0;if(T||!F){let ee=!1;if(T&&(P==="&"||P==="!")){let j=N.indexOf(" ");P==="&"&&j!==-1&&j<k&&N[j+1]==="!"&&(j=N.indexOf(" ",j+1)),(j===-1||k<j)&&(ee=!0)}ee||(E=`
46
46
  ${r.indent}`)}}else(N===""||N[0]===`
47
- `)&&(E="");return p+=E+N,r.inFlow?b&&i&&i():y&&!b?p+=si.lineComment(p,r.indent,l(y)):h&&n&&n(),p}Eu.stringifyPair=ag});var Ko=S(Uo=>{"use strict";var Cu=mn("process");function og(e,...t){e==="debug"&&console.log(...t)}function sg(e,t){(e==="debug"||e==="warn")&&(typeof Cu.emitWarning=="function"?Cu.emitWarning(t):console.warn(t))}Uo.debug=og;Uo.warn=sg});var $n=S(jn=>{"use strict";var Tn=A(),Pu=G(),_n="<<",In={identify:e=>e===_n||typeof e=="symbol"&&e.description===_n,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Pu.Scalar(Symbol(_n)),{addToJSMap:Ru}),stringify:()=>_n},cg=(e,t)=>(In.identify(t)||Tn.isScalar(t)&&(!t.type||t.type===Pu.Scalar.PLAIN)&&In.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===In.tag&&r.default);function Ru(e,t,r){let i=Au(e,r);if(Tn.isSeq(i))for(let n of i.items)Yo(e,t,n);else if(Array.isArray(i))for(let n of i)Yo(e,t,n);else Yo(e,t,i)}function Yo(e,t,r){let i=Au(e,r);if(!Tn.isMap(i))throw new Error("Merge sources must be maps or map aliases");let n=i.toJSON(null,e,Map);for(let[a,o]of n)t instanceof Map?t.has(a)||t.set(a,o):t instanceof Set?t.add(a):Object.prototype.hasOwnProperty.call(t,a)||Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function Au(e,t){return e&&Tn.isAlias(t)?t.resolve(e.doc,e):t}jn.addMergeToJSMap=Ru;jn.isMergeKey=cg;jn.merge=In});var Qo=S(Tu=>{"use strict";var lg=Ko(),_u=$n(),ug=oi(),Iu=A(),Xo=kt();function dg(e,t,{key:r,value:i}){if(Iu.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,i);else if(_u.isMergeKey(e,r))_u.addMergeToJSMap(e,t,i);else{let n=Xo.toJS(r,"",e);if(t instanceof Map)t.set(n,Xo.toJS(i,n,e));else if(t instanceof Set)t.add(n);else{let a=fg(r,n,e),o=Xo.toJS(i,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function fg(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(Iu.isNode(e)&&r?.doc){let i=ug.createStringifyContext(r.doc,{});i.anchors=new Set;for(let a of r.anchors.keys())i.anchors.add(a.anchor);i.inFlow=!0,i.inStringifyKey=!0;let n=e.toString(i);if(!r.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),lg.warn(r.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),r.mapKeyWarned=!0}return n}return JSON.stringify(t)}Tu.addPairToJSMap=dg});var Ct=S(Zo=>{"use strict";var ju=ti(),pg=xu(),hg=Qo(),On=A();function mg(e,t,r){let i=ju.createNode(e,void 0,r),n=ju.createNode(t,void 0,r);return new Hn(i,n)}var Hn=class e{constructor(t,r=null){Object.defineProperty(this,On.NODE_TYPE,{value:On.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:i}=this;return On.isNode(r)&&(r=r.clone(t)),On.isNode(i)&&(i=i.clone(t)),new e(r,i)}toJSON(t,r){let i=r?.mapAsMap?new Map:{};return hg.addPairToJSMap(r,i,this)}toString(t,r,i){return t?.doc?pg.stringifyPair(this,t,r,i):JSON.stringify(this)}};Zo.Pair=Hn;Zo.createPair=mg});var es=S(Ou=>{"use strict";var Ut=A(),$u=oi(),Dn=ri();function vg(e,t,r){return(t.inFlow??e.flow?wg:gg)(e,t,r)}function gg({comment:e,items:t},r,{blockItemPrefix:i,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=r,f=Object.assign({},r,{indent:a,type:null}),u=!1,d=[];for(let v=0;v<t.length;++v){let h=t[v],p=null;if(Ut.isNode(h))!u&&h.spaceBefore&&d.push(""),Bn(r,d,h.commentBefore,u),h.comment&&(p=h.comment);else if(Ut.isPair(h)){let g=Ut.isNode(h.key)?h.key:null;g&&(!u&&g.spaceBefore&&d.push(""),Bn(r,d,g.commentBefore,u))}u=!1;let w=$u.stringify(h,f,()=>p=null,()=>u=!0);p&&(w+=Dn.lineComment(w,a,l(p))),u&&p&&(u=!1),d.push(i+w)}let m;if(d.length===0)m=n.start+n.end;else{m=d[0];for(let v=1;v<d.length;++v){let h=d[v];m+=h?`
47
+ `)&&(E="");return p+=E+N,r.inFlow?b&&i&&i():y&&!b?p+=si.lineComment(p,r.indent,l(y)):h&&n&&n(),p}Eu.stringifyPair=sg});var Ko=S(Uo=>{"use strict";var Cu=mn("process");function cg(e,...t){e==="debug"&&console.log(...t)}function lg(e,t){(e==="debug"||e==="warn")&&(typeof Cu.emitWarning=="function"?Cu.emitWarning(t):console.warn(t))}Uo.debug=cg;Uo.warn=lg});var $n=S(jn=>{"use strict";var Tn=A(),Pu=G(),_n="<<",In={identify:e=>e===_n||typeof e=="symbol"&&e.description===_n,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Pu.Scalar(Symbol(_n)),{addToJSMap:Ru}),stringify:()=>_n},ug=(e,t)=>(In.identify(t)||Tn.isScalar(t)&&(!t.type||t.type===Pu.Scalar.PLAIN)&&In.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===In.tag&&r.default);function Ru(e,t,r){let i=Au(e,r);if(Tn.isSeq(i))for(let n of i.items)Yo(e,t,n);else if(Array.isArray(i))for(let n of i)Yo(e,t,n);else Yo(e,t,i)}function Yo(e,t,r){let i=Au(e,r);if(!Tn.isMap(i))throw new Error("Merge sources must be maps or map aliases");let n=i.toJSON(null,e,Map);for(let[a,o]of n)t instanceof Map?t.has(a)||t.set(a,o):t instanceof Set?t.add(a):Object.prototype.hasOwnProperty.call(t,a)||Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function Au(e,t){return e&&Tn.isAlias(t)?t.resolve(e.doc,e):t}jn.addMergeToJSMap=Ru;jn.isMergeKey=ug;jn.merge=In});var Qo=S(Tu=>{"use strict";var dg=Ko(),_u=$n(),fg=oi(),Iu=A(),Xo=kt();function pg(e,t,{key:r,value:i}){if(Iu.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,i);else if(_u.isMergeKey(e,r))_u.addMergeToJSMap(e,t,i);else{let n=Xo.toJS(r,"",e);if(t instanceof Map)t.set(n,Xo.toJS(i,n,e));else if(t instanceof Set)t.add(n);else{let a=hg(r,n,e),o=Xo.toJS(i,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function hg(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(Iu.isNode(e)&&r?.doc){let i=fg.createStringifyContext(r.doc,{});i.anchors=new Set;for(let a of r.anchors.keys())i.anchors.add(a.anchor);i.inFlow=!0,i.inStringifyKey=!0;let n=e.toString(i);if(!r.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),dg.warn(r.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),r.mapKeyWarned=!0}return n}return JSON.stringify(t)}Tu.addPairToJSMap=pg});var Ct=S(Zo=>{"use strict";var ju=ti(),mg=xu(),vg=Qo(),On=A();function gg(e,t,r){let i=ju.createNode(e,void 0,r),n=ju.createNode(t,void 0,r);return new Hn(i,n)}var Hn=class e{constructor(t,r=null){Object.defineProperty(this,On.NODE_TYPE,{value:On.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:i}=this;return On.isNode(r)&&(r=r.clone(t)),On.isNode(i)&&(i=i.clone(t)),new e(r,i)}toJSON(t,r){let i=r?.mapAsMap?new Map:{};return vg.addPairToJSMap(r,i,this)}toString(t,r,i){return t?.doc?mg.stringifyPair(this,t,r,i):JSON.stringify(this)}};Zo.Pair=Hn;Zo.createPair=gg});var es=S(Ou=>{"use strict";var Ut=A(),$u=oi(),Dn=ri();function wg(e,t,r){return(t.inFlow??e.flow?Ng:yg)(e,t,r)}function yg({comment:e,items:t},r,{blockItemPrefix:i,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=r,f=Object.assign({},r,{indent:a,type:null}),u=!1,d=[];for(let v=0;v<t.length;++v){let h=t[v],p=null;if(Ut.isNode(h))!u&&h.spaceBefore&&d.push(""),Bn(r,d,h.commentBefore,u),h.comment&&(p=h.comment);else if(Ut.isPair(h)){let g=Ut.isNode(h.key)?h.key:null;g&&(!u&&g.spaceBefore&&d.push(""),Bn(r,d,g.commentBefore,u))}u=!1;let w=$u.stringify(h,f,()=>p=null,()=>u=!0);p&&(w+=Dn.lineComment(w,a,l(p))),u&&p&&(u=!1),d.push(i+w)}let m;if(d.length===0)m=n.start+n.end;else{m=d[0];for(let v=1;v<d.length;++v){let h=d[v];m+=h?`
48
48
  ${c}${h}`:`
49
49
  `}}return e?(m+=`
50
- `+Dn.indentComment(l(e),c),s&&s()):u&&o&&o(),m}function wg({items:e},t,{flowChars:r,itemIndent:i}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;i+=a;let c=Object.assign({},t,{indent:i,inFlow:!0,type:null}),l=!1,f=0,u=[];for(let v=0;v<e.length;++v){let h=e[v],p=null;if(Ut.isNode(h))h.spaceBefore&&u.push(""),Bn(t,u,h.commentBefore,!1),h.comment&&(p=h.comment);else if(Ut.isPair(h)){let g=Ut.isNode(h.key)?h.key:null;g&&(g.spaceBefore&&u.push(""),Bn(t,u,g.commentBefore,!1),g.comment&&(l=!0));let y=Ut.isNode(h.value)?h.value:null;y?(y.comment&&(p=y.comment),y.commentBefore&&(l=!0)):h.value==null&&g?.comment&&(p=g.comment)}p&&(l=!0);let w=$u.stringify(h,c,()=>p=null);l||(l=u.length>f||w.includes(`
50
+ `+Dn.indentComment(l(e),c),s&&s()):u&&o&&o(),m}function Ng({items:e},t,{flowChars:r,itemIndent:i}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;i+=a;let c=Object.assign({},t,{indent:i,inFlow:!0,type:null}),l=!1,f=0,u=[];for(let v=0;v<e.length;++v){let h=e[v],p=null;if(Ut.isNode(h))h.spaceBefore&&u.push(""),Bn(t,u,h.commentBefore,!1),h.comment&&(p=h.comment);else if(Ut.isPair(h)){let g=Ut.isNode(h.key)?h.key:null;g&&(g.spaceBefore&&u.push(""),Bn(t,u,g.commentBefore,!1),g.comment&&(l=!0));let y=Ut.isNode(h.value)?h.value:null;y?(y.comment&&(p=y.comment),y.commentBefore&&(l=!0)):h.value==null&&g?.comment&&(p=g.comment)}p&&(l=!0);let w=$u.stringify(h,c,()=>p=null);l||(l=u.length>f||w.includes(`
51
51
  `)),v<e.length-1?w+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=u.reduce((g,y)=>g+y.length+2,2)+(w.length+2)>t.options.lineWidth)),l&&(w+=",")),p&&(w+=Dn.lineComment(w,i,s(p))),u.push(w),f=u.length}let{start:d,end:m}=r;if(u.length===0)return d+m;if(!l){let v=u.reduce((h,p)=>h+p.length+2,2);l=t.options.lineWidth>0&&v>t.options.lineWidth}if(l){let v=d;for(let h of u)v+=h?`
52
52
  ${a}${n}${h}`:`
53
53
  `;return`${v}
54
- ${n}${m}`}else return`${d}${o}${u.join(" ")}${o}${m}`}function Bn({indent:e,options:{commentString:t}},r,i,n){if(i&&n&&(i=i.replace(/^\n+/,"")),i){let a=Dn.indentComment(t(i),e);r.push(a.trimStart())}}Ou.stringifyCollection=vg});var Rt=S(rs=>{"use strict";var yg=es(),Ng=Qo(),bg=En(),Pt=A(),Ln=Ct(),kg=G();function ci(e,t){let r=Pt.isScalar(t)?t.value:t;for(let i of e)if(Pt.isPair(i)&&(i.key===t||i.key===r||Pt.isScalar(i.key)&&i.key.value===r))return i}var ts=class extends bg.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Pt.MAP,t),this.items=[]}static from(t,r,i){let{keepUndefined:n,replacer:a}=i,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(r,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||n)&&o.items.push(Ln.createPair(c,l,i))};if(r instanceof Map)for(let[c,l]of r)s(c,l);else if(r&&typeof r=="object")for(let c of Object.keys(r))s(c,r[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,r){let i;Pt.isPair(t)?i=t:!t||typeof t!="object"||!("key"in t)?i=new Ln.Pair(t,t?.value):i=new Ln.Pair(t.key,t.value);let n=ci(this.items,i.key),a=this.schema?.sortMapEntries;if(n){if(!r)throw new Error(`Key ${i.key} already set`);Pt.isScalar(n.value)&&kg.isScalarValue(i.value)?n.value.value=i.value:n.value=i.value}else if(a){let o=this.items.findIndex(s=>a(i,s)<0);o===-1?this.items.push(i):this.items.splice(o,0,i)}else this.items.push(i)}delete(t){let r=ci(this.items,t);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(t,r){let n=ci(this.items,t)?.value;return(!r&&Pt.isScalar(n)?n.value:n)??void 0}has(t){return!!ci(this.items,t)}set(t,r){this.add(new Ln.Pair(t,r),!0)}toJSON(t,r,i){let n=i?new i:r?.mapAsMap?new Map:{};r?.onCreate&&r.onCreate(n);for(let a of this.items)Ng.addPairToJSMap(r,n,a);return n}toString(t,r,i){if(!t)return JSON.stringify(this);for(let n of this.items)if(!Pt.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})),yg.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:i,onComment:r})}};rs.YAMLMap=ts;rs.findPair=ci});var mr=S(Du=>{"use strict";var Sg=A(),Hu=Rt(),Eg={collection:"map",default:!0,nodeClass:Hu.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return Sg.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>Hu.YAMLMap.from(e,t,r)};Du.map=Eg});var At=S(Bu=>{"use strict";var xg=ti(),Cg=es(),Pg=En(),Mn=A(),Rg=G(),Ag=kt(),is=class extends Pg.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Mn.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let r=Vn(t);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(t,r){let i=Vn(t);if(typeof i!="number")return;let n=this.items[i];return!r&&Mn.isScalar(n)?n.value:n}has(t){let r=Vn(t);return typeof r=="number"&&r<this.items.length}set(t,r){let i=Vn(t);if(typeof i!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[i];Mn.isScalar(n)&&Rg.isScalarValue(r)?n.value=r:this.items[i]=r}toJSON(t,r){let i=[];r?.onCreate&&r.onCreate(i);let n=0;for(let a of this.items)i.push(Ag.toJS(a,String(n++),r));return i}toString(t,r,i){return t?Cg.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:i,onComment:r}):JSON.stringify(this)}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r)){let o=0;for(let s of r){if(typeof n=="function"){let c=r instanceof Set?s:String(o++);s=n.call(r,c,s)}a.items.push(xg.createNode(s,void 0,i))}}return a}};function Vn(e){let t=Mn.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Bu.YAMLSeq=is});var vr=S(Vu=>{"use strict";var _g=A(),Lu=At(),Ig={collection:"seq",default:!0,nodeClass:Lu.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return _g.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>Lu.YAMLSeq.from(e,t,r)};Vu.seq=Ig});var li=S(Mu=>{"use strict";var Tg=ai(),jg={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,r,i){return t=Object.assign({actualString:!0},t),Tg.stringifyString(e,t,r,i)}};Mu.string=jg});var Fn=S(Wu=>{"use strict";var Fu=G(),qu={identify:e=>e==null,createNode:()=>new Fu.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Fu.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&qu.test.test(e)?e:t.options.nullStr};Wu.nullTag=qu});var ns=S(Ju=>{"use strict";var $g=G(),zu={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new $g.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&zu.test.test(e)){let i=e[0]==="t"||e[0]==="T";if(t===i)return e}return t?r.options.trueStr:r.options.falseStr}};Ju.boolTag=zu});var gr=S(Gu=>{"use strict";function Og({format:e,minFractionDigits:t,tag:r,value:i}){if(typeof i=="bigint")return String(i);let n=typeof i=="number"?i:Number(i);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let a=Object.is(i,-0)?"-0":JSON.stringify(i);if(!e&&t&&(!r||r==="tag:yaml.org,2002:float")&&/^-?\d/.test(a)&&!a.includes("e")){let o=a.indexOf(".");o<0&&(o=a.length,a+=".");let s=t-(a.length-o-1);for(;s-- >0;)a+="0"}return a}Gu.stringifyNumber=Og});var os=S(qn=>{"use strict";var Hg=G(),as=gr(),Dg={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:as.stringifyNumber},Bg={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():as.stringifyNumber(e)}},Lg={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 Hg.Scalar(parseFloat(e)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:as.stringifyNumber};qn.float=Lg;qn.floatExp=Bg;qn.floatNaN=Dg});var cs=S(zn=>{"use strict";var Uu=gr(),Wn=e=>typeof e=="bigint"||Number.isInteger(e),ss=(e,t,r,{intAsBigInt:i})=>i?BigInt(e):parseInt(e.substring(t),r);function Ku(e,t,r){let{value:i}=e;return Wn(i)&&i>=0?r+i.toString(t):Uu.stringifyNumber(e)}var Vg={identify:e=>Wn(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>ss(e,2,8,r),stringify:e=>Ku(e,8,"0o")},Mg={identify:Wn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>ss(e,0,10,r),stringify:Uu.stringifyNumber},Fg={identify:e=>Wn(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>ss(e,2,16,r),stringify:e=>Ku(e,16,"0x")};zn.int=Mg;zn.intHex=Fg;zn.intOct=Vg});var Xu=S(Yu=>{"use strict";var qg=mr(),Wg=Fn(),zg=vr(),Jg=li(),Gg=ns(),ls=os(),us=cs(),Ug=[qg.map,zg.seq,Jg.string,Wg.nullTag,Gg.boolTag,us.intOct,us.int,us.intHex,ls.floatNaN,ls.floatExp,ls.float];Yu.schema=Ug});var ed=S(Zu=>{"use strict";var Kg=G(),Yg=mr(),Xg=vr();function Qu(e){return typeof e=="bigint"||Number.isInteger(e)}var Jn=({value:e})=>JSON.stringify(e),Qg=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Jn},{identify:e=>e==null,createNode:()=>new Kg.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Jn},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Jn},{identify:Qu,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:r})=>r?BigInt(e):parseInt(e,10),stringify:({value:e})=>Qu(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:Jn}],Zg={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},ew=[Yg.map,Xg.seq].concat(Qg,Zg);Zu.schema=ew});var fs=S(td=>{"use strict";var ui=mn("buffer"),ds=G(),tw=ai(),rw={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof ui.Buffer=="function")return ui.Buffer.from(e,"base64");if(typeof atob=="function"){let r=atob(e.replace(/[\n\r]/g,"")),i=new Uint8Array(r.length);for(let n=0;n<r.length;++n)i[n]=r.charCodeAt(n);return i}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:r},i,n,a){if(!r)return"";let o=r,s;if(typeof ui.Buffer=="function")s=o instanceof ui.Buffer?o.toString("base64"):ui.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=ds.Scalar.BLOCK_LITERAL),t!==ds.Scalar.QUOTE_DOUBLE){let c=Math.max(i.options.lineWidth-i.indent.length,i.options.minContentWidth),l=Math.ceil(s.length/c),f=new Array(l);for(let u=0,d=0;u<l;++u,d+=c)f[u]=s.substr(d,c);s=f.join(t===ds.Scalar.BLOCK_LITERAL?`
55
- `:" ")}return tw.stringifyString({comment:e,type:t,value:s},i,n,a)}};td.binary=rw});var Kn=S(Un=>{"use strict";var Gn=A(),ps=Ct(),iw=G(),nw=At();function rd(e,t){if(Gn.isSeq(e))for(let r=0;r<e.items.length;++r){let i=e.items[r];if(!Gn.isPair(i)){if(Gn.isMap(i)){i.items.length>1&&t("Each pair must have its own sequence indicator");let n=i.items[0]||new ps.Pair(new iw.Scalar(null));if(i.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${i.commentBefore}
54
+ ${n}${m}`}else return`${d}${o}${u.join(" ")}${o}${m}`}function Bn({indent:e,options:{commentString:t}},r,i,n){if(i&&n&&(i=i.replace(/^\n+/,"")),i){let a=Dn.indentComment(t(i),e);r.push(a.trimStart())}}Ou.stringifyCollection=wg});var Rt=S(rs=>{"use strict";var bg=es(),kg=Qo(),Sg=En(),Pt=A(),Ln=Ct(),Eg=G();function ci(e,t){let r=Pt.isScalar(t)?t.value:t;for(let i of e)if(Pt.isPair(i)&&(i.key===t||i.key===r||Pt.isScalar(i.key)&&i.key.value===r))return i}var ts=class extends Sg.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Pt.MAP,t),this.items=[]}static from(t,r,i){let{keepUndefined:n,replacer:a}=i,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(r,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||n)&&o.items.push(Ln.createPair(c,l,i))};if(r instanceof Map)for(let[c,l]of r)s(c,l);else if(r&&typeof r=="object")for(let c of Object.keys(r))s(c,r[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,r){let i;Pt.isPair(t)?i=t:!t||typeof t!="object"||!("key"in t)?i=new Ln.Pair(t,t?.value):i=new Ln.Pair(t.key,t.value);let n=ci(this.items,i.key),a=this.schema?.sortMapEntries;if(n){if(!r)throw new Error(`Key ${i.key} already set`);Pt.isScalar(n.value)&&Eg.isScalarValue(i.value)?n.value.value=i.value:n.value=i.value}else if(a){let o=this.items.findIndex(s=>a(i,s)<0);o===-1?this.items.push(i):this.items.splice(o,0,i)}else this.items.push(i)}delete(t){let r=ci(this.items,t);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(t,r){let n=ci(this.items,t)?.value;return(!r&&Pt.isScalar(n)?n.value:n)??void 0}has(t){return!!ci(this.items,t)}set(t,r){this.add(new Ln.Pair(t,r),!0)}toJSON(t,r,i){let n=i?new i:r?.mapAsMap?new Map:{};r?.onCreate&&r.onCreate(n);for(let a of this.items)kg.addPairToJSMap(r,n,a);return n}toString(t,r,i){if(!t)return JSON.stringify(this);for(let n of this.items)if(!Pt.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})),bg.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:i,onComment:r})}};rs.YAMLMap=ts;rs.findPair=ci});var mr=S(Du=>{"use strict";var xg=A(),Hu=Rt(),Cg={collection:"map",default:!0,nodeClass:Hu.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return xg.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>Hu.YAMLMap.from(e,t,r)};Du.map=Cg});var At=S(Bu=>{"use strict";var Pg=ti(),Rg=es(),Ag=En(),Mn=A(),_g=G(),Ig=kt(),is=class extends Ag.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Mn.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let r=Vn(t);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(t,r){let i=Vn(t);if(typeof i!="number")return;let n=this.items[i];return!r&&Mn.isScalar(n)?n.value:n}has(t){let r=Vn(t);return typeof r=="number"&&r<this.items.length}set(t,r){let i=Vn(t);if(typeof i!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[i];Mn.isScalar(n)&&_g.isScalarValue(r)?n.value=r:this.items[i]=r}toJSON(t,r){let i=[];r?.onCreate&&r.onCreate(i);let n=0;for(let a of this.items)i.push(Ig.toJS(a,String(n++),r));return i}toString(t,r,i){return t?Rg.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:i,onComment:r}):JSON.stringify(this)}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r)){let o=0;for(let s of r){if(typeof n=="function"){let c=r instanceof Set?s:String(o++);s=n.call(r,c,s)}a.items.push(Pg.createNode(s,void 0,i))}}return a}};function Vn(e){let t=Mn.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Bu.YAMLSeq=is});var vr=S(Vu=>{"use strict";var Tg=A(),Lu=At(),jg={collection:"seq",default:!0,nodeClass:Lu.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return Tg.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>Lu.YAMLSeq.from(e,t,r)};Vu.seq=jg});var li=S(Mu=>{"use strict";var $g=ai(),Og={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,r,i){return t=Object.assign({actualString:!0},t),$g.stringifyString(e,t,r,i)}};Mu.string=Og});var Fn=S(Wu=>{"use strict";var Fu=G(),qu={identify:e=>e==null,createNode:()=>new Fu.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Fu.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&qu.test.test(e)?e:t.options.nullStr};Wu.nullTag=qu});var ns=S(Ju=>{"use strict";var Hg=G(),zu={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new Hg.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&zu.test.test(e)){let i=e[0]==="t"||e[0]==="T";if(t===i)return e}return t?r.options.trueStr:r.options.falseStr}};Ju.boolTag=zu});var gr=S(Gu=>{"use strict";function Dg({format:e,minFractionDigits:t,tag:r,value:i}){if(typeof i=="bigint")return String(i);let n=typeof i=="number"?i:Number(i);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let a=Object.is(i,-0)?"-0":JSON.stringify(i);if(!e&&t&&(!r||r==="tag:yaml.org,2002:float")&&/^-?\d/.test(a)&&!a.includes("e")){let o=a.indexOf(".");o<0&&(o=a.length,a+=".");let s=t-(a.length-o-1);for(;s-- >0;)a+="0"}return a}Gu.stringifyNumber=Dg});var os=S(qn=>{"use strict";var Bg=G(),as=gr(),Lg={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:as.stringifyNumber},Vg={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():as.stringifyNumber(e)}},Mg={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 Bg.Scalar(parseFloat(e)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:as.stringifyNumber};qn.float=Mg;qn.floatExp=Vg;qn.floatNaN=Lg});var cs=S(zn=>{"use strict";var Uu=gr(),Wn=e=>typeof e=="bigint"||Number.isInteger(e),ss=(e,t,r,{intAsBigInt:i})=>i?BigInt(e):parseInt(e.substring(t),r);function Ku(e,t,r){let{value:i}=e;return Wn(i)&&i>=0?r+i.toString(t):Uu.stringifyNumber(e)}var Fg={identify:e=>Wn(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>ss(e,2,8,r),stringify:e=>Ku(e,8,"0o")},qg={identify:Wn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>ss(e,0,10,r),stringify:Uu.stringifyNumber},Wg={identify:e=>Wn(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>ss(e,2,16,r),stringify:e=>Ku(e,16,"0x")};zn.int=qg;zn.intHex=Wg;zn.intOct=Fg});var Xu=S(Yu=>{"use strict";var zg=mr(),Jg=Fn(),Gg=vr(),Ug=li(),Kg=ns(),ls=os(),us=cs(),Yg=[zg.map,Gg.seq,Ug.string,Jg.nullTag,Kg.boolTag,us.intOct,us.int,us.intHex,ls.floatNaN,ls.floatExp,ls.float];Yu.schema=Yg});var ed=S(Zu=>{"use strict";var Xg=G(),Qg=mr(),Zg=vr();function Qu(e){return typeof e=="bigint"||Number.isInteger(e)}var Jn=({value:e})=>JSON.stringify(e),ew=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Jn},{identify:e=>e==null,createNode:()=>new Xg.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Jn},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Jn},{identify:Qu,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:r})=>r?BigInt(e):parseInt(e,10),stringify:({value:e})=>Qu(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:Jn}],tw={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},rw=[Qg.map,Zg.seq].concat(ew,tw);Zu.schema=rw});var fs=S(td=>{"use strict";var ui=mn("buffer"),ds=G(),iw=ai(),nw={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof ui.Buffer=="function")return ui.Buffer.from(e,"base64");if(typeof atob=="function"){let r=atob(e.replace(/[\n\r]/g,"")),i=new Uint8Array(r.length);for(let n=0;n<r.length;++n)i[n]=r.charCodeAt(n);return i}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:r},i,n,a){if(!r)return"";let o=r,s;if(typeof ui.Buffer=="function")s=o instanceof ui.Buffer?o.toString("base64"):ui.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=ds.Scalar.BLOCK_LITERAL),t!==ds.Scalar.QUOTE_DOUBLE){let c=Math.max(i.options.lineWidth-i.indent.length,i.options.minContentWidth),l=Math.ceil(s.length/c),f=new Array(l);for(let u=0,d=0;u<l;++u,d+=c)f[u]=s.substr(d,c);s=f.join(t===ds.Scalar.BLOCK_LITERAL?`
55
+ `:" ")}return iw.stringifyString({comment:e,type:t,value:s},i,n,a)}};td.binary=nw});var Kn=S(Un=>{"use strict";var Gn=A(),ps=Ct(),aw=G(),ow=At();function rd(e,t){if(Gn.isSeq(e))for(let r=0;r<e.items.length;++r){let i=e.items[r];if(!Gn.isPair(i)){if(Gn.isMap(i)){i.items.length>1&&t("Each pair must have its own sequence indicator");let n=i.items[0]||new ps.Pair(new aw.Scalar(null));if(i.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${i.commentBefore}
56
56
  ${n.key.commentBefore}`:i.commentBefore),i.comment){let a=n.value??n.key;a.comment=a.comment?`${i.comment}
57
- ${a.comment}`:i.comment}i=n}e.items[r]=Gn.isPair(i)?i:new ps.Pair(i)}}else t("Expected a sequence for this tag");return e}function id(e,t,r){let{replacer:i}=r,n=new nw.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof i=="function"&&(o=i.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(ps.createPair(s,c,r))}return n}var aw={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:rd,createNode:id};Un.createPairs=id;Un.pairs=aw;Un.resolvePairs=rd});var vs=S(ms=>{"use strict";var nd=A(),hs=kt(),di=Rt(),ow=At(),ad=Kn(),Kt=class e extends ow.YAMLSeq{constructor(){super(),this.add=di.YAMLMap.prototype.add.bind(this),this.delete=di.YAMLMap.prototype.delete.bind(this),this.get=di.YAMLMap.prototype.get.bind(this),this.has=di.YAMLMap.prototype.has.bind(this),this.set=di.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,r){if(!r)return super.toJSON(t);let i=new Map;r?.onCreate&&r.onCreate(i);for(let n of this.items){let a,o;if(nd.isPair(n)?(a=hs.toJS(n.key,"",r),o=hs.toJS(n.value,a,r)):a=hs.toJS(n,"",r),i.has(a))throw new Error("Ordered maps must not include duplicate keys");i.set(a,o)}return i}static from(t,r,i){let n=ad.createPairs(t,r,i),a=new this;return a.items=n.items,a}};Kt.tag="tag:yaml.org,2002:omap";var sw={collection:"seq",identify:e=>e instanceof Map,nodeClass:Kt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=ad.resolvePairs(e,t),i=[];for(let{key:n}of r.items)nd.isScalar(n)&&(i.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new Kt,r)},createNode:(e,t,r)=>Kt.from(e,t,r)};ms.YAMLOMap=Kt;ms.omap=sw});var ud=S(gs=>{"use strict";var od=G();function sd({value:e,source:t},r){return t&&(e?cd:ld).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var cd={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 od.Scalar(!0),stringify:sd},ld={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 od.Scalar(!1),stringify:sd};gs.falseTag=ld;gs.trueTag=cd});var dd=S(Yn=>{"use strict";var cw=G(),ws=gr(),lw={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:ws.stringifyNumber},uw={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():ws.stringifyNumber(e)}},dw={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 cw.Scalar(parseFloat(e.replace(/_/g,""))),r=e.indexOf(".");if(r!==-1){let i=e.substring(r+1).replace(/_/g,"");i[i.length-1]==="0"&&(t.minFractionDigits=i.length)}return t},stringify:ws.stringifyNumber};Yn.float=dw;Yn.floatExp=uw;Yn.floatNaN=lw});var pd=S(pi=>{"use strict";var fd=gr(),fi=e=>typeof e=="bigint"||Number.isInteger(e);function Xn(e,t,r,{intAsBigInt:i}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),i){switch(r){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return n==="-"?BigInt(-1)*o:o}let a=parseInt(e,r);return n==="-"?-1*a:a}function ys(e,t,r){let{value:i}=e;if(fi(i)){let n=i.toString(t);return i<0?"-"+r+n.substr(1):r+n}return fd.stringifyNumber(e)}var fw={identify:fi,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>Xn(e,2,2,r),stringify:e=>ys(e,2,"0b")},pw={identify:fi,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>Xn(e,1,8,r),stringify:e=>ys(e,8,"0")},hw={identify:fi,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>Xn(e,0,10,r),stringify:fd.stringifyNumber},mw={identify:fi,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>Xn(e,2,16,r),stringify:e=>ys(e,16,"0x")};pi.int=hw;pi.intBin=fw;pi.intHex=mw;pi.intOct=pw});var bs=S(Ns=>{"use strict";var ea=A(),Qn=Ct(),Zn=Rt(),Yt=class e extends Zn.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;ea.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new Qn.Pair(t.key,null):r=new Qn.Pair(t,null),Zn.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let i=Zn.findPair(this.items,t);return!r&&ea.isPair(i)?ea.isScalar(i.key)?i.key.value:i.key:i}set(t,r){if(typeof r!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof r}`);let i=Zn.findPair(this.items,t);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new Qn.Pair(t))}toJSON(t,r){return super.toJSON(t,r,Set)}toString(t,r,i){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),r,i);throw new Error("Set items must all have null values")}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r))for(let o of r)typeof n=="function"&&(o=n.call(r,o,o)),a.items.push(Qn.createPair(o,null,i));return a}};Yt.tag="tag:yaml.org,2002:set";var vw={collection:"map",identify:e=>e instanceof Set,nodeClass:Yt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>Yt.from(e,t,r),resolve(e,t){if(ea.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Yt,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Ns.YAMLSet=Yt;Ns.set=vw});var Ss=S(ta=>{"use strict";var gw=gr();function ks(e,t){let r=e[0],i=r==="-"||r==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=i.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return r==="-"?n(-1)*a:a}function hd(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return gw.stringifyNumber(e);let i="";t<0&&(i="-",t*=r(-1));let n=r(60),a=[t%n];return t<60?a.unshift(0):(t=(t-a[0])/n,a.unshift(t%n),t>=60&&(t=(t-a[0])/n,a.unshift(t))),i+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var ww={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:r})=>ks(e,r),stringify:hd},yw={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=>ks(e,!1),stringify:hd},md={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(md.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,i,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(r,i-1,n,a||0,o||0,s||0,c),f=t[8];if(f&&f!=="Z"){let u=ks(f,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};ta.floatTime=yw;ta.intTime=ww;ta.timestamp=md});var wd=S(gd=>{"use strict";var Nw=mr(),bw=Fn(),kw=vr(),Sw=li(),Ew=fs(),vd=ud(),Es=dd(),ra=pd(),xw=$n(),Cw=vs(),Pw=Kn(),Rw=bs(),xs=Ss(),Aw=[Nw.map,kw.seq,Sw.string,bw.nullTag,vd.trueTag,vd.falseTag,ra.intBin,ra.intOct,ra.int,ra.intHex,Es.floatNaN,Es.floatExp,Es.float,Ew.binary,xw.merge,Cw.omap,Pw.pairs,Rw.set,xs.intTime,xs.floatTime,xs.timestamp];gd.schema=Aw});var Rd=S(Rs=>{"use strict";var kd=mr(),_w=Fn(),Sd=vr(),Iw=li(),Tw=ns(),Cs=os(),Ps=cs(),jw=Xu(),$w=ed(),Ed=fs(),hi=$n(),xd=vs(),Cd=Kn(),yd=wd(),Pd=bs(),ia=Ss(),Nd=new Map([["core",jw.schema],["failsafe",[kd.map,Sd.seq,Iw.string]],["json",$w.schema],["yaml11",yd.schema],["yaml-1.1",yd.schema]]),bd={binary:Ed.binary,bool:Tw.boolTag,float:Cs.float,floatExp:Cs.floatExp,floatNaN:Cs.floatNaN,floatTime:ia.floatTime,int:Ps.int,intHex:Ps.intHex,intOct:Ps.intOct,intTime:ia.intTime,map:kd.map,merge:hi.merge,null:_w.nullTag,omap:xd.omap,pairs:Cd.pairs,seq:Sd.seq,set:Pd.set,timestamp:ia.timestamp},Ow={"tag:yaml.org,2002:binary":Ed.binary,"tag:yaml.org,2002:merge":hi.merge,"tag:yaml.org,2002:omap":xd.omap,"tag:yaml.org,2002:pairs":Cd.pairs,"tag:yaml.org,2002:set":Pd.set,"tag:yaml.org,2002:timestamp":ia.timestamp};function Hw(e,t,r){let i=Nd.get(t);if(i&&!e)return r&&!i.includes(hi.merge)?i.concat(hi.merge):i.slice();let n=i;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(Nd.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${a} or define customTags array`)}if(Array.isArray(e))for(let a of e)n=n.concat(a);else typeof e=="function"&&(n=e(n.slice()));return r&&(n=n.concat(hi.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?bd[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(bd).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}Rs.coreKnownTags=Ow;Rs.getTags=Hw});var Is=S(Ad=>{"use strict";var As=A(),Dw=mr(),Bw=vr(),Lw=li(),na=Rd(),Vw=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,_s=class e{constructor({compat:t,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?na.getTags(t,"compat"):t?na.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?na.coreKnownTags:{},this.tags=na.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,As.MAP,{value:Dw.map}),Object.defineProperty(this,As.SCALAR,{value:Lw.string}),Object.defineProperty(this,As.SEQ,{value:Bw.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Vw:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Ad.Schema=_s});var Id=S(_d=>{"use strict";var Mw=A(),Ts=oi(),mi=ri();function Fw(e,t){let r=[],i=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(r.push(c),i=!0):e.directives.docStart&&(i=!0)}i&&r.push("---");let n=Ts.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=a(e.commentBefore);r.unshift(mi.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(Mw.isNode(e.contents)){if(e.contents.spaceBefore&&i&&r.push(""),e.contents.commentBefore){let f=a(e.contents.commentBefore);r.push(mi.indentComment(f,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Ts.stringify(e.contents,n,()=>s=null,c);s&&(l+=mi.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(Ts.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
57
+ ${a.comment}`:i.comment}i=n}e.items[r]=Gn.isPair(i)?i:new ps.Pair(i)}}else t("Expected a sequence for this tag");return e}function id(e,t,r){let{replacer:i}=r,n=new ow.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof i=="function"&&(o=i.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(ps.createPair(s,c,r))}return n}var sw={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:rd,createNode:id};Un.createPairs=id;Un.pairs=sw;Un.resolvePairs=rd});var vs=S(ms=>{"use strict";var nd=A(),hs=kt(),di=Rt(),cw=At(),ad=Kn(),Kt=class e extends cw.YAMLSeq{constructor(){super(),this.add=di.YAMLMap.prototype.add.bind(this),this.delete=di.YAMLMap.prototype.delete.bind(this),this.get=di.YAMLMap.prototype.get.bind(this),this.has=di.YAMLMap.prototype.has.bind(this),this.set=di.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,r){if(!r)return super.toJSON(t);let i=new Map;r?.onCreate&&r.onCreate(i);for(let n of this.items){let a,o;if(nd.isPair(n)?(a=hs.toJS(n.key,"",r),o=hs.toJS(n.value,a,r)):a=hs.toJS(n,"",r),i.has(a))throw new Error("Ordered maps must not include duplicate keys");i.set(a,o)}return i}static from(t,r,i){let n=ad.createPairs(t,r,i),a=new this;return a.items=n.items,a}};Kt.tag="tag:yaml.org,2002:omap";var lw={collection:"seq",identify:e=>e instanceof Map,nodeClass:Kt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=ad.resolvePairs(e,t),i=[];for(let{key:n}of r.items)nd.isScalar(n)&&(i.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new Kt,r)},createNode:(e,t,r)=>Kt.from(e,t,r)};ms.YAMLOMap=Kt;ms.omap=lw});var ud=S(gs=>{"use strict";var od=G();function sd({value:e,source:t},r){return t&&(e?cd:ld).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var cd={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 od.Scalar(!0),stringify:sd},ld={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 od.Scalar(!1),stringify:sd};gs.falseTag=ld;gs.trueTag=cd});var dd=S(Yn=>{"use strict";var uw=G(),ws=gr(),dw={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:ws.stringifyNumber},fw={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():ws.stringifyNumber(e)}},pw={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 uw.Scalar(parseFloat(e.replace(/_/g,""))),r=e.indexOf(".");if(r!==-1){let i=e.substring(r+1).replace(/_/g,"");i[i.length-1]==="0"&&(t.minFractionDigits=i.length)}return t},stringify:ws.stringifyNumber};Yn.float=pw;Yn.floatExp=fw;Yn.floatNaN=dw});var pd=S(pi=>{"use strict";var fd=gr(),fi=e=>typeof e=="bigint"||Number.isInteger(e);function Xn(e,t,r,{intAsBigInt:i}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),i){switch(r){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return n==="-"?BigInt(-1)*o:o}let a=parseInt(e,r);return n==="-"?-1*a:a}function ys(e,t,r){let{value:i}=e;if(fi(i)){let n=i.toString(t);return i<0?"-"+r+n.substr(1):r+n}return fd.stringifyNumber(e)}var hw={identify:fi,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>Xn(e,2,2,r),stringify:e=>ys(e,2,"0b")},mw={identify:fi,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>Xn(e,1,8,r),stringify:e=>ys(e,8,"0")},vw={identify:fi,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>Xn(e,0,10,r),stringify:fd.stringifyNumber},gw={identify:fi,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>Xn(e,2,16,r),stringify:e=>ys(e,16,"0x")};pi.int=vw;pi.intBin=hw;pi.intHex=gw;pi.intOct=mw});var bs=S(Ns=>{"use strict";var ea=A(),Qn=Ct(),Zn=Rt(),Yt=class e extends Zn.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;ea.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new Qn.Pair(t.key,null):r=new Qn.Pair(t,null),Zn.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let i=Zn.findPair(this.items,t);return!r&&ea.isPair(i)?ea.isScalar(i.key)?i.key.value:i.key:i}set(t,r){if(typeof r!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof r}`);let i=Zn.findPair(this.items,t);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new Qn.Pair(t))}toJSON(t,r){return super.toJSON(t,r,Set)}toString(t,r,i){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),r,i);throw new Error("Set items must all have null values")}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r))for(let o of r)typeof n=="function"&&(o=n.call(r,o,o)),a.items.push(Qn.createPair(o,null,i));return a}};Yt.tag="tag:yaml.org,2002:set";var ww={collection:"map",identify:e=>e instanceof Set,nodeClass:Yt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>Yt.from(e,t,r),resolve(e,t){if(ea.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Yt,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Ns.YAMLSet=Yt;Ns.set=ww});var Ss=S(ta=>{"use strict";var yw=gr();function ks(e,t){let r=e[0],i=r==="-"||r==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=i.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return r==="-"?n(-1)*a:a}function hd(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return yw.stringifyNumber(e);let i="";t<0&&(i="-",t*=r(-1));let n=r(60),a=[t%n];return t<60?a.unshift(0):(t=(t-a[0])/n,a.unshift(t%n),t>=60&&(t=(t-a[0])/n,a.unshift(t))),i+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Nw={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:r})=>ks(e,r),stringify:hd},bw={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=>ks(e,!1),stringify:hd},md={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(md.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,i,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(r,i-1,n,a||0,o||0,s||0,c),f=t[8];if(f&&f!=="Z"){let u=ks(f,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};ta.floatTime=bw;ta.intTime=Nw;ta.timestamp=md});var wd=S(gd=>{"use strict";var kw=mr(),Sw=Fn(),Ew=vr(),xw=li(),Cw=fs(),vd=ud(),Es=dd(),ra=pd(),Pw=$n(),Rw=vs(),Aw=Kn(),_w=bs(),xs=Ss(),Iw=[kw.map,Ew.seq,xw.string,Sw.nullTag,vd.trueTag,vd.falseTag,ra.intBin,ra.intOct,ra.int,ra.intHex,Es.floatNaN,Es.floatExp,Es.float,Cw.binary,Pw.merge,Rw.omap,Aw.pairs,_w.set,xs.intTime,xs.floatTime,xs.timestamp];gd.schema=Iw});var Rd=S(Rs=>{"use strict";var kd=mr(),Tw=Fn(),Sd=vr(),jw=li(),$w=ns(),Cs=os(),Ps=cs(),Ow=Xu(),Hw=ed(),Ed=fs(),hi=$n(),xd=vs(),Cd=Kn(),yd=wd(),Pd=bs(),ia=Ss(),Nd=new Map([["core",Ow.schema],["failsafe",[kd.map,Sd.seq,jw.string]],["json",Hw.schema],["yaml11",yd.schema],["yaml-1.1",yd.schema]]),bd={binary:Ed.binary,bool:$w.boolTag,float:Cs.float,floatExp:Cs.floatExp,floatNaN:Cs.floatNaN,floatTime:ia.floatTime,int:Ps.int,intHex:Ps.intHex,intOct:Ps.intOct,intTime:ia.intTime,map:kd.map,merge:hi.merge,null:Tw.nullTag,omap:xd.omap,pairs:Cd.pairs,seq:Sd.seq,set:Pd.set,timestamp:ia.timestamp},Dw={"tag:yaml.org,2002:binary":Ed.binary,"tag:yaml.org,2002:merge":hi.merge,"tag:yaml.org,2002:omap":xd.omap,"tag:yaml.org,2002:pairs":Cd.pairs,"tag:yaml.org,2002:set":Pd.set,"tag:yaml.org,2002:timestamp":ia.timestamp};function Bw(e,t,r){let i=Nd.get(t);if(i&&!e)return r&&!i.includes(hi.merge)?i.concat(hi.merge):i.slice();let n=i;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(Nd.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${a} or define customTags array`)}if(Array.isArray(e))for(let a of e)n=n.concat(a);else typeof e=="function"&&(n=e(n.slice()));return r&&(n=n.concat(hi.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?bd[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(bd).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}Rs.coreKnownTags=Dw;Rs.getTags=Bw});var Is=S(Ad=>{"use strict";var As=A(),Lw=mr(),Vw=vr(),Mw=li(),na=Rd(),Fw=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,_s=class e{constructor({compat:t,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?na.getTags(t,"compat"):t?na.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?na.coreKnownTags:{},this.tags=na.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,As.MAP,{value:Lw.map}),Object.defineProperty(this,As.SCALAR,{value:Mw.string}),Object.defineProperty(this,As.SEQ,{value:Vw.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Fw:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Ad.Schema=_s});var Id=S(_d=>{"use strict";var qw=A(),Ts=oi(),mi=ri();function Ww(e,t){let r=[],i=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(r.push(c),i=!0):e.directives.docStart&&(i=!0)}i&&r.push("---");let n=Ts.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=a(e.commentBefore);r.unshift(mi.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(qw.isNode(e.contents)){if(e.contents.spaceBefore&&i&&r.push(""),e.contents.commentBefore){let f=a(e.contents.commentBefore);r.push(mi.indentComment(f,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Ts.stringify(e.contents,n,()=>s=null,c);s&&(l+=mi.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(Ts.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
58
58
  `)?(r.push("..."),r.push(mi.indentComment(c,""))):r.push(`... ${c}`)}else r.push("...");else{let c=e.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&r[r.length-1]!==""&&r.push(""),r.push(mi.indentComment(a(c),"")))}return r.join(`
59
59
  `)+`
60
- `}_d.stringifyDocument=Fw});var vi=S(Td=>{"use strict";var qw=ei(),wr=En(),Ce=A(),Ww=Ct(),zw=kt(),Jw=Is(),Gw=Id(),js=Nn(),Uw=Do(),Kw=ti(),$s=Ho(),Os=class e{constructor(t,r,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Ce.NODE_TYPE,{value:Ce.DOC});let n=null;typeof r=="function"||Array.isArray(r)?n=r:i===void 0&&r&&(i=r,r=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},i);this.options=a;let{version:o}=a;i?._directives?(this.directives=i._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new $s.Directives({version:o}),this.setSchema(o,i),this.contents=t===void 0?null:this.createNode(t,n,i)}clone(){let t=Object.create(e.prototype,{[Ce.NODE_TYPE]:{value:Ce.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=Ce.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){yr(this.contents)&&this.contents.add(t)}addIn(t,r){yr(this.contents)&&this.contents.addIn(t,r)}createAlias(t,r){if(!t.anchor){let i=js.anchorNames(this);t.anchor=!r||i.has(r)?js.findNewAnchor(r||"a",i):r}return new qw.Alias(t.anchor)}createNode(t,r,i){let n;if(typeof r=="function")t=r.call({"":t},"",t),n=r;else if(Array.isArray(r)){let p=g=>typeof g=="number"||g instanceof String||g instanceof Number,w=r.filter(p).map(String);w.length>0&&(r=r.concat(w)),n=r}else i===void 0&&r&&(i=r,r=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:f}=i??{},{onAnchor:u,setAnchors:d,sourceObjects:m}=js.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:m},h=Kw.createNode(t,f,v);return s&&Ce.isCollection(h)&&(h.flow=!0),d(),h}createPair(t,r,i={}){let n=this.createNode(t,null,i),a=this.createNode(r,null,i);return new Ww.Pair(n,a)}delete(t){return yr(this.contents)?this.contents.delete(t):!1}deleteIn(t){return wr.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):yr(this.contents)?this.contents.deleteIn(t):!1}get(t,r){return Ce.isCollection(this.contents)?this.contents.get(t,r):void 0}getIn(t,r){return wr.isEmptyPath(t)?!r&&Ce.isScalar(this.contents)?this.contents.value:this.contents:Ce.isCollection(this.contents)?this.contents.getIn(t,r):void 0}has(t){return Ce.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return wr.isEmptyPath(t)?this.contents!==void 0:Ce.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,r){this.contents==null?this.contents=wr.collectionFromPath(this.schema,[t],r):yr(this.contents)&&this.contents.set(t,r)}setIn(t,r){wr.isEmptyPath(t)?this.contents=r:this.contents==null?this.contents=wr.collectionFromPath(this.schema,Array.from(t),r):yr(this.contents)&&this.contents.setIn(t,r)}setSchema(t,r={}){typeof t=="number"&&(t=String(t));let i;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new $s.Directives({version:"1.1"}),i={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new $s.Directives({version:t}),i={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,i=null;break;default:{let n=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${n}`)}}if(r.schema instanceof Object)this.schema=r.schema;else if(i)this.schema=new Jw.Schema(Object.assign(i,r));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:r,mapAsMap:i,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=zw.toJS(this.contents,r??"",s);if(typeof a=="function")for(let{count:l,res:f}of s.anchors.values())a(f,l);return typeof o=="function"?Uw.applyReviver(o,{"":c},"",c):c}toJSON(t,r){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:r})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let r=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${r}`)}return Gw.stringifyDocument(this,t)}};function yr(e){if(Ce.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Td.Document=Os});var yi=S(wi=>{"use strict";var gi=class extends Error{constructor(t,r,i,n){super(),this.name=t,this.code=i,this.message=n,this.pos=r}},Hs=class extends gi{constructor(t,r,i){super("YAMLParseError",t,r,i)}},Ds=class extends gi{constructor(t,r,i){super("YAMLWarning",t,r,i)}},Yw=(e,t)=>r=>{if(r.pos[0]===-1)return;r.linePos=r.pos.map(s=>t.linePos(s));let{line:i,col:n}=r.linePos[0];r.message+=` at line ${i}, column ${n}`;let a=n-1,o=e.substring(t.lineStarts[i-1],t.lineStarts[i]).replace(/[\n\r]+$/,"");if(a>=60&&o.length>80){let s=Math.min(a-39,o.length-79);o="…"+o.substring(s),a-=s-1}if(o.length>80&&(o=o.substring(0,79)+"…"),i>1&&/^ *$/.test(o.substring(0,a))){let s=e.substring(t.lineStarts[i-2],t.lineStarts[i-1]);s.length>80&&(s=s.substring(0,79)+`…
60
+ `}_d.stringifyDocument=Ww});var vi=S(Td=>{"use strict";var zw=ei(),wr=En(),Ce=A(),Jw=Ct(),Gw=kt(),Uw=Is(),Kw=Id(),js=Nn(),Yw=Do(),Xw=ti(),$s=Ho(),Os=class e{constructor(t,r,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Ce.NODE_TYPE,{value:Ce.DOC});let n=null;typeof r=="function"||Array.isArray(r)?n=r:i===void 0&&r&&(i=r,r=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},i);this.options=a;let{version:o}=a;i?._directives?(this.directives=i._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new $s.Directives({version:o}),this.setSchema(o,i),this.contents=t===void 0?null:this.createNode(t,n,i)}clone(){let t=Object.create(e.prototype,{[Ce.NODE_TYPE]:{value:Ce.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=Ce.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){yr(this.contents)&&this.contents.add(t)}addIn(t,r){yr(this.contents)&&this.contents.addIn(t,r)}createAlias(t,r){if(!t.anchor){let i=js.anchorNames(this);t.anchor=!r||i.has(r)?js.findNewAnchor(r||"a",i):r}return new zw.Alias(t.anchor)}createNode(t,r,i){let n;if(typeof r=="function")t=r.call({"":t},"",t),n=r;else if(Array.isArray(r)){let p=g=>typeof g=="number"||g instanceof String||g instanceof Number,w=r.filter(p).map(String);w.length>0&&(r=r.concat(w)),n=r}else i===void 0&&r&&(i=r,r=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:f}=i??{},{onAnchor:u,setAnchors:d,sourceObjects:m}=js.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:m},h=Xw.createNode(t,f,v);return s&&Ce.isCollection(h)&&(h.flow=!0),d(),h}createPair(t,r,i={}){let n=this.createNode(t,null,i),a=this.createNode(r,null,i);return new Jw.Pair(n,a)}delete(t){return yr(this.contents)?this.contents.delete(t):!1}deleteIn(t){return wr.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):yr(this.contents)?this.contents.deleteIn(t):!1}get(t,r){return Ce.isCollection(this.contents)?this.contents.get(t,r):void 0}getIn(t,r){return wr.isEmptyPath(t)?!r&&Ce.isScalar(this.contents)?this.contents.value:this.contents:Ce.isCollection(this.contents)?this.contents.getIn(t,r):void 0}has(t){return Ce.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return wr.isEmptyPath(t)?this.contents!==void 0:Ce.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,r){this.contents==null?this.contents=wr.collectionFromPath(this.schema,[t],r):yr(this.contents)&&this.contents.set(t,r)}setIn(t,r){wr.isEmptyPath(t)?this.contents=r:this.contents==null?this.contents=wr.collectionFromPath(this.schema,Array.from(t),r):yr(this.contents)&&this.contents.setIn(t,r)}setSchema(t,r={}){typeof t=="number"&&(t=String(t));let i;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new $s.Directives({version:"1.1"}),i={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new $s.Directives({version:t}),i={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,i=null;break;default:{let n=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${n}`)}}if(r.schema instanceof Object)this.schema=r.schema;else if(i)this.schema=new Uw.Schema(Object.assign(i,r));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:r,mapAsMap:i,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=Gw.toJS(this.contents,r??"",s);if(typeof a=="function")for(let{count:l,res:f}of s.anchors.values())a(f,l);return typeof o=="function"?Yw.applyReviver(o,{"":c},"",c):c}toJSON(t,r){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:r})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let r=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${r}`)}return Kw.stringifyDocument(this,t)}};function yr(e){if(Ce.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Td.Document=Os});var yi=S(wi=>{"use strict";var gi=class extends Error{constructor(t,r,i,n){super(),this.name=t,this.code=i,this.message=n,this.pos=r}},Hs=class extends gi{constructor(t,r,i){super("YAMLParseError",t,r,i)}},Ds=class extends gi{constructor(t,r,i){super("YAMLWarning",t,r,i)}},Qw=(e,t)=>r=>{if(r.pos[0]===-1)return;r.linePos=r.pos.map(s=>t.linePos(s));let{line:i,col:n}=r.linePos[0];r.message+=` at line ${i}, column ${n}`;let a=n-1,o=e.substring(t.lineStarts[i-1],t.lineStarts[i]).replace(/[\n\r]+$/,"");if(a>=60&&o.length>80){let s=Math.min(a-39,o.length-79);o="…"+o.substring(s),a-=s-1}if(o.length>80&&(o=o.substring(0,79)+"…"),i>1&&/^ *$/.test(o.substring(0,a))){let s=e.substring(t.lineStarts[i-2],t.lineStarts[i-1]);s.length>80&&(s=s.substring(0,79)+`…
61
61
  `),o=s+o}if(/[^ ]/.test(o)){let s=1,c=r.linePos[1];c?.line===i&&c.col>n&&(s=Math.max(1,Math.min(c.col-n,80-a)));let l=" ".repeat(a)+"^".repeat(s);r.message+=`:
62
62
 
63
63
  ${o}
64
64
  ${l}
65
- `}};wi.YAMLError=gi;wi.YAMLParseError=Hs;wi.YAMLWarning=Ds;wi.prettifyError=Yw});var Ni=S(jd=>{"use strict";function Xw(e,{flow:t,indicator:r,next:i,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,f=s,u="",d="",m=!1,v=!1,h=null,p=null,w=null,g=null,y=null,b=null,N=null;for(let k of e)switch(v&&(k.type!=="space"&&k.type!=="newline"&&k.type!=="comma"&&a(k.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),h&&(l&&k.type!=="comment"&&k.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),k.type){case"space":!t&&(r!=="doc-start"||i?.type!=="flow-collection")&&k.source.includes(" ")&&(h=k),f=!0;break;case"comment":{f||a(k,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let T=k.source.substring(1)||" ";u?u+=d+T:u=T,d="",l=!1;break}case"newline":l?u?u+=k.source:(!b||r!=="seq-item-ind")&&(c=!0):d+=k.source,l=!0,m=!0,(p||w)&&(g=k),f=!0;break;case"anchor":p&&a(k,"MULTIPLE_ANCHORS","A node can have at most one anchor"),k.source.endsWith(":")&&a(k.offset+k.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),p=k,N??(N=k.offset),l=!1,f=!1,v=!0;break;case"tag":{w&&a(k,"MULTIPLE_TAGS","A node can have at most one tag"),w=k,N??(N=k.offset),l=!1,f=!1,v=!0;break}case r:(p||w)&&a(k,"BAD_PROP_ORDER",`Anchors and tags must be after the ${k.source} indicator`),b&&a(k,"UNEXPECTED_TOKEN",`Unexpected ${k.source} in ${t??"collection"}`),b=k,l=r==="seq-item-ind"||r==="explicit-key-ind",f=!1;break;case"comma":if(t){y&&a(k,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),y=k,l=!1,f=!1;break}default:a(k,"UNEXPECTED_TOKEN",`Unexpected ${k.type} token`),l=!1,f=!1}let E=e[e.length-1],P=E?E.offset+E.source.length:n;return v&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&a(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:y,found:b,spaceBefore:c,comment:u,hasNewline:m,anchor:p,tag:w,newlineAfterProp:g,end:P,start:N??P}}jd.resolveProps=Xw});var aa=S($d=>{"use strict";function Bs(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
66
- `))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let r of t.start)if(r.type==="newline")return!0;if(t.sep){for(let r of t.sep)if(r.type==="newline")return!0}if(Bs(t.key)||Bs(t.value))return!0}return!1;default:return!0}}$d.containsNewline=Bs});var Ls=S(Od=>{"use strict";var Qw=aa();function Zw(e,t,r){if(t?.type==="flow-collection"){let i=t.end[0];i.indent===e&&(i.source==="]"||i.source==="}")&&Qw.containsNewline(t)&&r(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Od.flowIndentCheck=Zw});var Vs=S(Dd=>{"use strict";var Hd=A();function ey(e,t,r){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let n=typeof i=="function"?i:(a,o)=>a===o||Hd.isScalar(a)&&Hd.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,r))}Dd.mapIncludes=ey});var qd=S(Fd=>{"use strict";var Bd=Ct(),ty=Rt(),Ld=Ni(),ry=aa(),Vd=Ls(),iy=Vs(),Md="All mapping items must start at the same column";function ny({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??ty.YAMLMap,s=new o(r.schema);r.atRoot&&(r.atRoot=!1);let c=i.offset,l=null;for(let f of i.items){let{start:u,key:d,sep:m,value:v}=f,h=Ld.resolveProps(u,{indicator:"explicit-key-ind",next:d??m?.[0],offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0}),p=!h.found;if(p){if(d&&(d.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in d&&d.indent!==i.indent&&n(c,"BAD_INDENT",Md)),!h.anchor&&!h.tag&&!m){l=h.end,h.comment&&(s.comment?s.comment+=`
67
- `+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||ry.containsNewline(d))&&n(d??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==i.indent&&n(c,"BAD_INDENT",Md);r.atKey=!0;let w=h.end,g=d?e(r,d,h,n):t(r,w,u,null,h,n);r.schema.compat&&Vd.flowIndentCheck(i.indent,d,n),r.atKey=!1,iy.mapIncludes(r,s.items,g)&&n(w,"DUPLICATE_KEY","Map keys must be unique");let y=Ld.resolveProps(m??[],{indicator:"map-value-ind",next:v,offset:g.range[2],onError:n,parentIndent:i.indent,startOnNewline:!d||d.type==="block-scalar"});if(c=y.end,y.found){p&&(v?.type==="block-map"&&!y.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&h.start<y.found.offset-1024&&n(g.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let b=v?e(r,v,y,n):t(r,c,m,null,y,n);r.schema.compat&&Vd.flowIndentCheck(i.indent,v,n),c=b.range[2];let N=new Bd.Pair(g,b);r.options.keepSourceTokens&&(N.srcToken=f),s.items.push(N)}else{p&&n(g.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),y.comment&&(g.comment?g.comment+=`
68
- `+y.comment:g.comment=y.comment);let b=new Bd.Pair(g);r.options.keepSourceTokens&&(b.srcToken=f),s.items.push(b)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[i.offset,c,l??c],s}Fd.resolveBlockMap=ny});var zd=S(Wd=>{"use strict";var ay=At(),oy=Ni(),sy=Ls();function cy({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??ay.YAMLSeq,s=new o(r.schema);r.atRoot&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let c=i.offset,l=null;for(let{start:f,value:u}of i.items){let d=oy.resolveProps(f,{indicator:"seq-item-ind",next:u,offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||u)u?.type==="block-seq"?n(d.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=d.end,d.comment&&(s.comment=d.comment);continue}let m=u?e(r,u,d,n):t(r,d.end,f,null,d,n);r.schema.compat&&sy.flowIndentCheck(i.indent,u,n),c=m.range[2],s.items.push(m)}return s.range=[i.offset,c,l??c],s}Wd.resolveBlockSeq=cy});var Nr=S(Jd=>{"use strict";function ly(e,t,r,i){let n="";if(e){let a=!1,o="";for(let s of e){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{r&&!a&&i(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let f=c.substring(1)||" ";n?n+=o+f:n=f,o="";break}case"newline":n&&(o+=c),a=!0;break;default:i(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:n,offset:t}}Jd.resolveEnd=ly});var Yd=S(Kd=>{"use strict";var uy=A(),dy=Ct(),Gd=Rt(),fy=At(),py=Nr(),Ud=Ni(),hy=aa(),my=Vs(),Ms="Block collections are not allowed within flow collections",Fs=e=>e&&(e.type==="block-map"||e.type==="block-seq");function vy({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=i.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Gd.YAMLMap:fy.YAMLSeq),l=new c(r.schema);l.flow=!0;let f=r.atRoot;f&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let u=i.offset+i.start.source.length;for(let p=0;p<i.items.length;++p){let w=i.items[p],{start:g,key:y,sep:b,value:N}=w,E=Ud.resolveProps(g,{flow:s,indicator:"explicit-key-ind",next:y??b?.[0],offset:u,onError:n,parentIndent:i.indent,startOnNewline:!1});if(!E.found){if(!E.anchor&&!E.tag&&!b&&!N){p===0&&E.comma?n(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):p<i.items.length-1&&n(E.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),E.comment&&(l.comment?l.comment+=`
69
- `+E.comment:l.comment=E.comment),u=E.end;continue}!o&&r.options.strict&&hy.containsNewline(y)&&n(y,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(p===0)E.comma&&n(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(E.comma||n(E.start,"MISSING_CHAR",`Missing , between ${s} items`),E.comment){let P="";e:for(let k of g)switch(k.type){case"comma":case"space":break;case"comment":P=k.source.substring(1);break e;default:break e}if(P){let k=l.items[l.items.length-1];uy.isPair(k)&&(k=k.value??k.key),k.comment?k.comment+=`
65
+ `}};wi.YAMLError=gi;wi.YAMLParseError=Hs;wi.YAMLWarning=Ds;wi.prettifyError=Qw});var Ni=S(jd=>{"use strict";function Zw(e,{flow:t,indicator:r,next:i,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,f=s,u="",d="",m=!1,v=!1,h=null,p=null,w=null,g=null,y=null,b=null,N=null;for(let k of e)switch(v&&(k.type!=="space"&&k.type!=="newline"&&k.type!=="comma"&&a(k.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),h&&(l&&k.type!=="comment"&&k.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),k.type){case"space":!t&&(r!=="doc-start"||i?.type!=="flow-collection")&&k.source.includes(" ")&&(h=k),f=!0;break;case"comment":{f||a(k,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let T=k.source.substring(1)||" ";u?u+=d+T:u=T,d="",l=!1;break}case"newline":l?u?u+=k.source:(!b||r!=="seq-item-ind")&&(c=!0):d+=k.source,l=!0,m=!0,(p||w)&&(g=k),f=!0;break;case"anchor":p&&a(k,"MULTIPLE_ANCHORS","A node can have at most one anchor"),k.source.endsWith(":")&&a(k.offset+k.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),p=k,N??(N=k.offset),l=!1,f=!1,v=!0;break;case"tag":{w&&a(k,"MULTIPLE_TAGS","A node can have at most one tag"),w=k,N??(N=k.offset),l=!1,f=!1,v=!0;break}case r:(p||w)&&a(k,"BAD_PROP_ORDER",`Anchors and tags must be after the ${k.source} indicator`),b&&a(k,"UNEXPECTED_TOKEN",`Unexpected ${k.source} in ${t??"collection"}`),b=k,l=r==="seq-item-ind"||r==="explicit-key-ind",f=!1;break;case"comma":if(t){y&&a(k,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),y=k,l=!1,f=!1;break}default:a(k,"UNEXPECTED_TOKEN",`Unexpected ${k.type} token`),l=!1,f=!1}let E=e[e.length-1],P=E?E.offset+E.source.length:n;return v&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&a(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:y,found:b,spaceBefore:c,comment:u,hasNewline:m,anchor:p,tag:w,newlineAfterProp:g,end:P,start:N??P}}jd.resolveProps=Zw});var aa=S($d=>{"use strict";function Bs(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
66
+ `))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let r of t.start)if(r.type==="newline")return!0;if(t.sep){for(let r of t.sep)if(r.type==="newline")return!0}if(Bs(t.key)||Bs(t.value))return!0}return!1;default:return!0}}$d.containsNewline=Bs});var Ls=S(Od=>{"use strict";var ey=aa();function ty(e,t,r){if(t?.type==="flow-collection"){let i=t.end[0];i.indent===e&&(i.source==="]"||i.source==="}")&&ey.containsNewline(t)&&r(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Od.flowIndentCheck=ty});var Vs=S(Dd=>{"use strict";var Hd=A();function ry(e,t,r){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let n=typeof i=="function"?i:(a,o)=>a===o||Hd.isScalar(a)&&Hd.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,r))}Dd.mapIncludes=ry});var qd=S(Fd=>{"use strict";var Bd=Ct(),iy=Rt(),Ld=Ni(),ny=aa(),Vd=Ls(),ay=Vs(),Md="All mapping items must start at the same column";function oy({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??iy.YAMLMap,s=new o(r.schema);r.atRoot&&(r.atRoot=!1);let c=i.offset,l=null;for(let f of i.items){let{start:u,key:d,sep:m,value:v}=f,h=Ld.resolveProps(u,{indicator:"explicit-key-ind",next:d??m?.[0],offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0}),p=!h.found;if(p){if(d&&(d.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in d&&d.indent!==i.indent&&n(c,"BAD_INDENT",Md)),!h.anchor&&!h.tag&&!m){l=h.end,h.comment&&(s.comment?s.comment+=`
67
+ `+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||ny.containsNewline(d))&&n(d??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==i.indent&&n(c,"BAD_INDENT",Md);r.atKey=!0;let w=h.end,g=d?e(r,d,h,n):t(r,w,u,null,h,n);r.schema.compat&&Vd.flowIndentCheck(i.indent,d,n),r.atKey=!1,ay.mapIncludes(r,s.items,g)&&n(w,"DUPLICATE_KEY","Map keys must be unique");let y=Ld.resolveProps(m??[],{indicator:"map-value-ind",next:v,offset:g.range[2],onError:n,parentIndent:i.indent,startOnNewline:!d||d.type==="block-scalar"});if(c=y.end,y.found){p&&(v?.type==="block-map"&&!y.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&h.start<y.found.offset-1024&&n(g.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let b=v?e(r,v,y,n):t(r,c,m,null,y,n);r.schema.compat&&Vd.flowIndentCheck(i.indent,v,n),c=b.range[2];let N=new Bd.Pair(g,b);r.options.keepSourceTokens&&(N.srcToken=f),s.items.push(N)}else{p&&n(g.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),y.comment&&(g.comment?g.comment+=`
68
+ `+y.comment:g.comment=y.comment);let b=new Bd.Pair(g);r.options.keepSourceTokens&&(b.srcToken=f),s.items.push(b)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[i.offset,c,l??c],s}Fd.resolveBlockMap=oy});var zd=S(Wd=>{"use strict";var sy=At(),cy=Ni(),ly=Ls();function uy({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??sy.YAMLSeq,s=new o(r.schema);r.atRoot&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let c=i.offset,l=null;for(let{start:f,value:u}of i.items){let d=cy.resolveProps(f,{indicator:"seq-item-ind",next:u,offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||u)u?.type==="block-seq"?n(d.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=d.end,d.comment&&(s.comment=d.comment);continue}let m=u?e(r,u,d,n):t(r,d.end,f,null,d,n);r.schema.compat&&ly.flowIndentCheck(i.indent,u,n),c=m.range[2],s.items.push(m)}return s.range=[i.offset,c,l??c],s}Wd.resolveBlockSeq=uy});var Nr=S(Jd=>{"use strict";function dy(e,t,r,i){let n="";if(e){let a=!1,o="";for(let s of e){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{r&&!a&&i(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let f=c.substring(1)||" ";n?n+=o+f:n=f,o="";break}case"newline":n&&(o+=c),a=!0;break;default:i(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:n,offset:t}}Jd.resolveEnd=dy});var Yd=S(Kd=>{"use strict";var fy=A(),py=Ct(),Gd=Rt(),hy=At(),my=Nr(),Ud=Ni(),vy=aa(),gy=Vs(),Ms="Block collections are not allowed within flow collections",Fs=e=>e&&(e.type==="block-map"||e.type==="block-seq");function wy({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=i.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Gd.YAMLMap:hy.YAMLSeq),l=new c(r.schema);l.flow=!0;let f=r.atRoot;f&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let u=i.offset+i.start.source.length;for(let p=0;p<i.items.length;++p){let w=i.items[p],{start:g,key:y,sep:b,value:N}=w,E=Ud.resolveProps(g,{flow:s,indicator:"explicit-key-ind",next:y??b?.[0],offset:u,onError:n,parentIndent:i.indent,startOnNewline:!1});if(!E.found){if(!E.anchor&&!E.tag&&!b&&!N){p===0&&E.comma?n(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):p<i.items.length-1&&n(E.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),E.comment&&(l.comment?l.comment+=`
69
+ `+E.comment:l.comment=E.comment),u=E.end;continue}!o&&r.options.strict&&vy.containsNewline(y)&&n(y,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(p===0)E.comma&&n(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(E.comma||n(E.start,"MISSING_CHAR",`Missing , between ${s} items`),E.comment){let P="";e:for(let k of g)switch(k.type){case"comma":case"space":break;case"comment":P=k.source.substring(1);break e;default:break e}if(P){let k=l.items[l.items.length-1];fy.isPair(k)&&(k=k.value??k.key),k.comment?k.comment+=`
70
70
  `+P:k.comment=P,E.comment=E.comment.substring(P.length+1)}}if(!o&&!b&&!E.found){let P=N?e(r,N,E,n):t(r,E.end,b,null,E,n);l.items.push(P),u=P.range[2],Fs(N)&&n(P.range,"BLOCK_IN_FLOW",Ms)}else{r.atKey=!0;let P=E.end,k=y?e(r,y,E,n):t(r,P,g,null,E,n);Fs(y)&&n(k.range,"BLOCK_IN_FLOW",Ms),r.atKey=!1;let T=Ud.resolveProps(b??[],{flow:s,indicator:"map-value-ind",next:N,offset:k.range[2],onError:n,parentIndent:i.indent,startOnNewline:!1});if(T.found){if(!o&&!E.found&&r.options.strict){if(b)for(let j of b){if(j===T.found)break;if(j.type==="newline"){n(j,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}E.start<T.found.offset-1024&&n(T.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else N&&("source"in N&&N.source?.[0]===":"?n(N,"MISSING_CHAR",`Missing space after : in ${s}`):n(T.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let F=N?e(r,N,T,n):T.found?t(r,T.end,b,null,T,n):null;F?Fs(N)&&n(F.range,"BLOCK_IN_FLOW",Ms):T.comment&&(k.comment?k.comment+=`
71
- `+T.comment:k.comment=T.comment);let ee=new dy.Pair(k,F);if(r.options.keepSourceTokens&&(ee.srcToken=w),o){let j=l;my.mapIncludes(r,j.items,k)&&n(P,"DUPLICATE_KEY","Map keys must be unique"),j.items.push(ee)}else{let j=new Gd.YAMLMap(r.schema);j.flow=!0,j.items.push(ee);let bt=(F??k).range;j.range=[k.range[0],bt[1],bt[2]],l.items.push(j)}u=F?F.range[2]:T.end}}let d=o?"}":"]",[m,...v]=i.end,h=u;if(m?.source===d)h=m.offset+m.source.length;else{let p=s[0].toUpperCase()+s.substring(1),w=f?`${p} must end with a ${d}`:`${p} in block collection must be sufficiently indented and end with a ${d}`;n(u,f?"MISSING_CHAR":"BAD_INDENT",w),m&&m.source.length!==1&&v.unshift(m)}if(v.length>0){let p=py.resolveEnd(v,h,r.options.strict,n);p.comment&&(l.comment?l.comment+=`
72
- `+p.comment:l.comment=p.comment),l.range=[i.offset,h,p.offset]}else l.range=[i.offset,h,h];return l}Kd.resolveFlowCollection=vy});var Qd=S(Xd=>{"use strict";var gy=A(),wy=G(),yy=Rt(),Ny=At(),by=qd(),ky=zd(),Sy=Yd();function qs(e,t,r,i,n,a){let o=r.type==="block-map"?by.resolveBlockMap(e,t,r,i,a):r.type==="block-seq"?ky.resolveBlockSeq(e,t,r,i,a):Sy.resolveFlowCollection(e,t,r,i,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function Ey(e,t,r,i,n){let a=i.tag,o=a?t.directives.tagName(a.source,d=>n(a,"TAG_RESOLVE_FAILED",d)):null;if(r.type==="block-seq"){let{anchor:d,newlineAfterProp:m}=i,v=d&&a?d.offset>a.offset?d:a:d??a;v&&(!m||m.offset<v.offset)&&n(v,"MISSING_CHAR","Missing newline after block sequence props")}let s=r.type==="block-map"?"map":r.type==="block-seq"?"seq":r.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===yy.YAMLMap.tagName&&s==="map"||o===Ny.YAMLSeq.tagName&&s==="seq")return qs(e,t,r,n,o);let c=t.schema.tags.find(d=>d.tag===o&&d.collection===s);if(!c){let d=t.schema.knownTags[o];if(d?.collection===s)t.schema.tags.push(Object.assign({},d,{default:!1})),c=d;else return d?n(a,"BAD_COLLECTION_TYPE",`${d.tag} used for ${s} collection, but expects ${d.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),qs(e,t,r,n,o)}let l=qs(e,t,r,n,o,c),f=c.resolve?.(l,d=>n(a,"TAG_RESOLVE_FAILED",d),t.options)??l,u=gy.isNode(f)?f:new wy.Scalar(f);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}Xd.composeCollection=Ey});var zs=S(Zd=>{"use strict";var Ws=G();function xy(e,t,r){let i=t.offset,n=Cy(t,e.options.strict,r);if(!n)return{value:"",type:null,comment:"",range:[i,i,i]};let a=n.mode===">"?Ws.Scalar.BLOCK_FOLDED:Ws.Scalar.BLOCK_LITERAL,o=t.source?Py(t.source):[],s=o.length;for(let h=o.length-1;h>=0;--h){let p=o[h][1];if(p===""||p==="\r")s=h;else break}if(s===0){let h=n.chomp==="+"&&o.length>0?`
71
+ `+T.comment:k.comment=T.comment);let ee=new py.Pair(k,F);if(r.options.keepSourceTokens&&(ee.srcToken=w),o){let j=l;gy.mapIncludes(r,j.items,k)&&n(P,"DUPLICATE_KEY","Map keys must be unique"),j.items.push(ee)}else{let j=new Gd.YAMLMap(r.schema);j.flow=!0,j.items.push(ee);let bt=(F??k).range;j.range=[k.range[0],bt[1],bt[2]],l.items.push(j)}u=F?F.range[2]:T.end}}let d=o?"}":"]",[m,...v]=i.end,h=u;if(m?.source===d)h=m.offset+m.source.length;else{let p=s[0].toUpperCase()+s.substring(1),w=f?`${p} must end with a ${d}`:`${p} in block collection must be sufficiently indented and end with a ${d}`;n(u,f?"MISSING_CHAR":"BAD_INDENT",w),m&&m.source.length!==1&&v.unshift(m)}if(v.length>0){let p=my.resolveEnd(v,h,r.options.strict,n);p.comment&&(l.comment?l.comment+=`
72
+ `+p.comment:l.comment=p.comment),l.range=[i.offset,h,p.offset]}else l.range=[i.offset,h,h];return l}Kd.resolveFlowCollection=wy});var Qd=S(Xd=>{"use strict";var yy=A(),Ny=G(),by=Rt(),ky=At(),Sy=qd(),Ey=zd(),xy=Yd();function qs(e,t,r,i,n,a){let o=r.type==="block-map"?Sy.resolveBlockMap(e,t,r,i,a):r.type==="block-seq"?Ey.resolveBlockSeq(e,t,r,i,a):xy.resolveFlowCollection(e,t,r,i,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function Cy(e,t,r,i,n){let a=i.tag,o=a?t.directives.tagName(a.source,d=>n(a,"TAG_RESOLVE_FAILED",d)):null;if(r.type==="block-seq"){let{anchor:d,newlineAfterProp:m}=i,v=d&&a?d.offset>a.offset?d:a:d??a;v&&(!m||m.offset<v.offset)&&n(v,"MISSING_CHAR","Missing newline after block sequence props")}let s=r.type==="block-map"?"map":r.type==="block-seq"?"seq":r.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===by.YAMLMap.tagName&&s==="map"||o===ky.YAMLSeq.tagName&&s==="seq")return qs(e,t,r,n,o);let c=t.schema.tags.find(d=>d.tag===o&&d.collection===s);if(!c){let d=t.schema.knownTags[o];if(d?.collection===s)t.schema.tags.push(Object.assign({},d,{default:!1})),c=d;else return d?n(a,"BAD_COLLECTION_TYPE",`${d.tag} used for ${s} collection, but expects ${d.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),qs(e,t,r,n,o)}let l=qs(e,t,r,n,o,c),f=c.resolve?.(l,d=>n(a,"TAG_RESOLVE_FAILED",d),t.options)??l,u=yy.isNode(f)?f:new Ny.Scalar(f);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}Xd.composeCollection=Cy});var zs=S(Zd=>{"use strict";var Ws=G();function Py(e,t,r){let i=t.offset,n=Ry(t,e.options.strict,r);if(!n)return{value:"",type:null,comment:"",range:[i,i,i]};let a=n.mode===">"?Ws.Scalar.BLOCK_FOLDED:Ws.Scalar.BLOCK_LITERAL,o=t.source?Ay(t.source):[],s=o.length;for(let h=o.length-1;h>=0;--h){let p=o[h][1];if(p===""||p==="\r")s=h;else break}if(s===0){let h=n.chomp==="+"&&o.length>0?`
73
73
  `.repeat(Math.max(1,o.length-1)):"",p=i+n.length;return t.source&&(p+=t.source.length),{value:h,type:a,comment:n.comment,range:[i,p,p]}}let c=t.indent+n.indent,l=t.offset+n.length,f=0;for(let h=0;h<s;++h){let[p,w]=o[h];if(w===""||w==="\r")n.indent===0&&p.length>c&&(c=p.length);else{p.length<c&&r(l+p.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(c=p.length),f=h,c===0&&!e.atRoot&&r(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=p.length+w.length+1}for(let h=o.length-1;h>=s;--h)o[h][0].length>c&&(s=h+1);let u="",d="",m=!1;for(let h=0;h<f;++h)u+=o[h][0].slice(c)+`
74
74
  `;for(let h=f;h<s;++h){let[p,w]=o[h];l+=p.length+w.length+1;let g=w[w.length-1]==="\r";if(g&&(w=w.slice(0,-1)),w&&p.length<c){let b=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;r(l-w.length-(g?2:1),"BAD_INDENT",b),p=""}a===Ws.Scalar.BLOCK_LITERAL?(u+=d+p.slice(c)+w,d=`
75
75
  `):p.length>c||w[0]===" "?(d===" "?d=`
@@ -84,41 +84,41 @@ ${l}
84
84
  `+o[h][0].slice(c);u[u.length-1]!==`
85
85
  `&&(u+=`
86
86
  `);break;default:u+=`
87
- `}let v=i+n.length+t.source.length;return{value:u,type:a,comment:n.comment,range:[i,v,v]}}function Cy({offset:e,props:t},r,i){if(t[0].type!=="block-scalar-header")return i(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",c=-1;for(let d=1;d<n.length;++d){let m=n[d];if(!s&&(m==="-"||m==="+"))s=m;else{let v=Number(m);!o&&v?o=v:c===-1&&(c=e+d)}}c!==-1&&i(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,f="",u=n.length;for(let d=1;d<t.length;++d){let m=t[d];switch(m.type){case"space":l=!0;case"newline":u+=m.source.length;break;case"comment":r&&!l&&i(m,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),u+=m.source.length,f=m.source.substring(1);break;case"error":i(m,"UNEXPECTED_TOKEN",m.message),u+=m.source.length;break;default:{let v=`Unexpected token in block scalar header: ${m.type}`;i(m,"UNEXPECTED_TOKEN",v);let h=m.source;h&&typeof h=="string"&&(u+=h.length)}}}return{mode:a,indent:o,chomp:s,comment:f,length:u}}function Py(e){let t=e.split(/\n( *)/),r=t[0],i=r.match(/^( *)/),a=[i?.[1]?[i[1],r.slice(i[1].length)]:["",r]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}Zd.resolveBlockScalar=xy});var Gs=S(tf=>{"use strict";var Js=G(),Ry=Nr();function Ay(e,t,r){let{offset:i,type:n,source:a,end:o}=e,s,c,l=(d,m,v)=>r(i+d,m,v);switch(n){case"scalar":s=Js.Scalar.PLAIN,c=_y(a,l);break;case"single-quoted-scalar":s=Js.Scalar.QUOTE_SINGLE,c=Iy(a,l);break;case"double-quoted-scalar":s=Js.Scalar.QUOTE_DOUBLE,c=Ty(a,l);break;default:return r(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[i,i+a.length,i+a.length]}}let f=i+a.length,u=Ry.resolveEnd(o,f,t,r);return{value:c,type:s,comment:u.comment,range:[i,f,u.offset]}}function _y(e,t){let r="";switch(e[0]){case" ":r="a tab character";break;case",":r="flow indicator character ,";break;case"%":r="directive indicator character %";break;case"|":case">":{r=`block scalar indicator ${e[0]}`;break}case"@":case"`":{r=`reserved character ${e[0]}`;break}}return r&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${r}`),ef(e)}function Iy(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),ef(e.slice(1,-1)).replace(/''/g,"'")}function ef(e){let t,r;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
87
+ `}let v=i+n.length+t.source.length;return{value:u,type:a,comment:n.comment,range:[i,v,v]}}function Ry({offset:e,props:t},r,i){if(t[0].type!=="block-scalar-header")return i(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",c=-1;for(let d=1;d<n.length;++d){let m=n[d];if(!s&&(m==="-"||m==="+"))s=m;else{let v=Number(m);!o&&v?o=v:c===-1&&(c=e+d)}}c!==-1&&i(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,f="",u=n.length;for(let d=1;d<t.length;++d){let m=t[d];switch(m.type){case"space":l=!0;case"newline":u+=m.source.length;break;case"comment":r&&!l&&i(m,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),u+=m.source.length,f=m.source.substring(1);break;case"error":i(m,"UNEXPECTED_TOKEN",m.message),u+=m.source.length;break;default:{let v=`Unexpected token in block scalar header: ${m.type}`;i(m,"UNEXPECTED_TOKEN",v);let h=m.source;h&&typeof h=="string"&&(u+=h.length)}}}return{mode:a,indent:o,chomp:s,comment:f,length:u}}function Ay(e){let t=e.split(/\n( *)/),r=t[0],i=r.match(/^( *)/),a=[i?.[1]?[i[1],r.slice(i[1].length)]:["",r]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}Zd.resolveBlockScalar=Py});var Gs=S(tf=>{"use strict";var Js=G(),_y=Nr();function Iy(e,t,r){let{offset:i,type:n,source:a,end:o}=e,s,c,l=(d,m,v)=>r(i+d,m,v);switch(n){case"scalar":s=Js.Scalar.PLAIN,c=Ty(a,l);break;case"single-quoted-scalar":s=Js.Scalar.QUOTE_SINGLE,c=jy(a,l);break;case"double-quoted-scalar":s=Js.Scalar.QUOTE_DOUBLE,c=$y(a,l);break;default:return r(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[i,i+a.length,i+a.length]}}let f=i+a.length,u=_y.resolveEnd(o,f,t,r);return{value:c,type:s,comment:u.comment,range:[i,f,u.offset]}}function Ty(e,t){let r="";switch(e[0]){case" ":r="a tab character";break;case",":r="flow indicator character ,";break;case"%":r="directive indicator character %";break;case"|":case">":{r=`block scalar indicator ${e[0]}`;break}case"@":case"`":{r=`reserved character ${e[0]}`;break}}return r&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${r}`),ef(e)}function jy(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),ef(e.slice(1,-1)).replace(/''/g,"'")}function ef(e){let t,r;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
88
88
  `,"sy"),r=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
89
89
  `,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,r=/[ \t]*(.*?)[ \t]*\r?\n/sy}let i=t.exec(e);if(!i)return e;let n=i[1],a=" ",o=t.lastIndex;for(r.lastIndex=o;i=r.exec(e);)i[1]===""?a===`
90
90
  `?n+=a:a=`
91
- `:(n+=a+i[1],a=" "),o=r.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,i=s.exec(e),n+a+(i?.[1]??"")}function Ty(e,t){let r="";for(let i=1;i<e.length-1;++i){let n=e[i];if(!(n==="\r"&&e[i+1]===`
91
+ `:(n+=a+i[1],a=" "),o=r.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,i=s.exec(e),n+a+(i?.[1]??"")}function $y(e,t){let r="";for(let i=1;i<e.length-1;++i){let n=e[i];if(!(n==="\r"&&e[i+1]===`
92
92
  `))if(n===`
93
- `){let{fold:a,offset:o}=jy(e,i);r+=a,i=o}else if(n==="\\"){let a=e[++i],o=$y[a];if(o)r+=o;else if(a===`
93
+ `){let{fold:a,offset:o}=Oy(e,i);r+=a,i=o}else if(n==="\\"){let a=e[++i],o=Hy[a];if(o)r+=o;else if(a===`
94
94
  `)for(a=e[i+1];a===" "||a===" ";)a=e[++i+1];else if(a==="\r"&&e[i+1]===`
95
- `)for(a=e[++i+1];a===" "||a===" ";)a=e[++i+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;r+=Oy(e,i+1,s,t),i+=s}else{let s=e.substr(i-1,2);t(i-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),r+=s}}else if(n===" "||n===" "){let a=i,o=e[i+1];for(;o===" "||o===" ";)o=e[++i+1];o!==`
95
+ `)for(a=e[++i+1];a===" "||a===" ";)a=e[++i+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;r+=Dy(e,i+1,s,t),i+=s}else{let s=e.substr(i-1,2);t(i-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),r+=s}}else if(n===" "||n===" "){let a=i,o=e[i+1];for(;o===" "||o===" ";)o=e[++i+1];o!==`
96
96
  `&&!(o==="\r"&&e[i+2]===`
97
- `)&&(r+=i>a?e.slice(a,i+1):n)}else r+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),r}function jy(e,t){let r="",i=e[t+1];for(;(i===" "||i===" "||i===`
97
+ `)&&(r+=i>a?e.slice(a,i+1):n)}else r+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),r}function Oy(e,t){let r="",i=e[t+1];for(;(i===" "||i===" "||i===`
98
98
  `||i==="\r")&&!(i==="\r"&&e[t+2]!==`
99
99
  `);)i===`
100
100
  `&&(r+=`
101
- `),t+=1,i=e[t+1];return r||(r=" "),{fold:r,offset:t}}var $y={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
102
- `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Oy(e,t,r,i){let n=e.substr(t,r),o=n.length===r&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,r+2);return i(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}tf.resolveFlowScalar=Ay});var af=S(nf=>{"use strict";var Xt=A(),rf=G(),Hy=zs(),Dy=Gs();function By(e,t,r,i){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?Hy.resolveBlockScalar(e,t,i):Dy.resolveFlowScalar(t,e.options.strict,i),c=r?e.directives.tagName(r.source,u=>i(r,"TAG_RESOLVE_FAILED",u)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[Xt.SCALAR]:c?l=Ly(e.schema,n,c,r,i):t.type==="scalar"?l=Vy(e,n,t,i):l=e.schema[Xt.SCALAR];let f;try{let u=l.resolve(n,d=>i(r??t,"TAG_RESOLVE_FAILED",d),e.options);f=Xt.isScalar(u)?u:new rf.Scalar(u)}catch(u){let d=u instanceof Error?u.message:String(u);i(r??t,"TAG_RESOLVE_FAILED",d),f=new rf.Scalar(n)}return f.range=s,f.source=n,a&&(f.type=a),c&&(f.tag=c),l.format&&(f.format=l.format),o&&(f.comment=o),f}function Ly(e,t,r,i,n){if(r==="!")return e[Xt.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===r)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(t))return s;let o=e.knownTags[r];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${r}`,r!=="tag:yaml.org,2002:str"),e[Xt.SCALAR])}function Vy({atKey:e,directives:t,schema:r},i,n,a){let o=r.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(i))||r[Xt.SCALAR];if(r.compat){let s=r.compat.find(c=>c.default&&c.test?.test(i))??r[Xt.SCALAR];if(o.tag!==s.tag){let c=t.tagString(o.tag),l=t.tagString(s.tag),f=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",f,!0)}}return o}nf.composeScalar=By});var sf=S(of=>{"use strict";function My(e,t,r){if(t){r??(r=t.length);for(let i=r-1;i>=0;--i){let n=t[i];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}for(n=t[++i];n?.type==="space";)e+=n.source.length,n=t[++i];break}}return e}of.emptyScalarPosition=My});var uf=S(Ks=>{"use strict";var Fy=ei(),qy=A(),Wy=Qd(),cf=af(),zy=Nr(),Jy=sf(),Gy={composeNode:lf,composeEmptyNode:Us};function lf(e,t,r,i){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=r,l,f=!0;switch(t.type){case"alias":l=Uy(e,t,i),(s||c)&&i(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=cf.composeScalar(e,t,c,i),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Wy.composeCollection(Gy,e,t,r,i),s&&(l.anchor=s.source.substring(1))}catch(u){let d=u instanceof Error?u.message:String(u);i(t,"RESOURCE_EXHAUSTION",d)}break;default:{let u=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;i(t,"UNEXPECTED_TOKEN",u),f=!1}}return l??(l=Us(e,t.offset,void 0,null,r,i)),s&&l.anchor===""&&i(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&e.options.stringKeys&&(!qy.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&i(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&f&&(l.srcToken=t),l}function Us(e,t,r,i,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let f={type:"scalar",offset:Jy.emptyScalarPosition(t,r,i),indent:-1,source:""},u=cf.composeScalar(e,f,s,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(u.spaceBefore=!0),a&&(u.comment=a,u.range[2]=c),u}function Uy({options:e},{offset:t,source:r,end:i},n){let a=new Fy.Alias(r.substring(1));a.source===""&&n(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(t+r.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+r.length,s=zy.resolveEnd(i,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}Ks.composeEmptyNode=Us;Ks.composeNode=lf});var pf=S(ff=>{"use strict";var Ky=vi(),df=uf(),Yy=Nr(),Xy=Ni();function Qy(e,t,{offset:r,start:i,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new Ky.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=Xy.resolveProps(i,{indicator:"doc-start",next:n??a?.[0],offset:r,onError:o,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!f.hasNewline&&o(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?df.composeNode(l,n,f,o):df.composeEmptyNode(l,f.end,i,null,f,o);let u=c.contents.range[2],d=Yy.resolveEnd(a,u,!1,o);return d.comment&&(c.comment=d.comment),c.range=[r,u,d.offset],c}ff.composeDoc=Qy});var Xs=S(vf=>{"use strict";var Zy=mn("process"),eN=Ho(),tN=vi(),bi=yi(),hf=A(),rN=pf(),iN=Nr();function ki(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:r}=e;return[t,t+(typeof r=="string"?r.length:1)]}function mf(e){let t="",r=!1,i=!1;for(let n=0;n<e.length;++n){let a=e[n];switch(a[0]){case"#":t+=(t===""?"":i?`
101
+ `),t+=1,i=e[t+1];return r||(r=" "),{fold:r,offset:t}}var Hy={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
102
+ `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Dy(e,t,r,i){let n=e.substr(t,r),o=n.length===r&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,r+2);return i(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}tf.resolveFlowScalar=Iy});var af=S(nf=>{"use strict";var Xt=A(),rf=G(),By=zs(),Ly=Gs();function Vy(e,t,r,i){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?By.resolveBlockScalar(e,t,i):Ly.resolveFlowScalar(t,e.options.strict,i),c=r?e.directives.tagName(r.source,u=>i(r,"TAG_RESOLVE_FAILED",u)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[Xt.SCALAR]:c?l=My(e.schema,n,c,r,i):t.type==="scalar"?l=Fy(e,n,t,i):l=e.schema[Xt.SCALAR];let f;try{let u=l.resolve(n,d=>i(r??t,"TAG_RESOLVE_FAILED",d),e.options);f=Xt.isScalar(u)?u:new rf.Scalar(u)}catch(u){let d=u instanceof Error?u.message:String(u);i(r??t,"TAG_RESOLVE_FAILED",d),f=new rf.Scalar(n)}return f.range=s,f.source=n,a&&(f.type=a),c&&(f.tag=c),l.format&&(f.format=l.format),o&&(f.comment=o),f}function My(e,t,r,i,n){if(r==="!")return e[Xt.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===r)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(t))return s;let o=e.knownTags[r];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${r}`,r!=="tag:yaml.org,2002:str"),e[Xt.SCALAR])}function Fy({atKey:e,directives:t,schema:r},i,n,a){let o=r.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(i))||r[Xt.SCALAR];if(r.compat){let s=r.compat.find(c=>c.default&&c.test?.test(i))??r[Xt.SCALAR];if(o.tag!==s.tag){let c=t.tagString(o.tag),l=t.tagString(s.tag),f=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",f,!0)}}return o}nf.composeScalar=Vy});var sf=S(of=>{"use strict";function qy(e,t,r){if(t){r??(r=t.length);for(let i=r-1;i>=0;--i){let n=t[i];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}for(n=t[++i];n?.type==="space";)e+=n.source.length,n=t[++i];break}}return e}of.emptyScalarPosition=qy});var uf=S(Ks=>{"use strict";var Wy=ei(),zy=A(),Jy=Qd(),cf=af(),Gy=Nr(),Uy=sf(),Ky={composeNode:lf,composeEmptyNode:Us};function lf(e,t,r,i){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=r,l,f=!0;switch(t.type){case"alias":l=Yy(e,t,i),(s||c)&&i(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=cf.composeScalar(e,t,c,i),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Jy.composeCollection(Ky,e,t,r,i),s&&(l.anchor=s.source.substring(1))}catch(u){let d=u instanceof Error?u.message:String(u);i(t,"RESOURCE_EXHAUSTION",d)}break;default:{let u=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;i(t,"UNEXPECTED_TOKEN",u),f=!1}}return l??(l=Us(e,t.offset,void 0,null,r,i)),s&&l.anchor===""&&i(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&e.options.stringKeys&&(!zy.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&i(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&f&&(l.srcToken=t),l}function Us(e,t,r,i,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let f={type:"scalar",offset:Uy.emptyScalarPosition(t,r,i),indent:-1,source:""},u=cf.composeScalar(e,f,s,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(u.spaceBefore=!0),a&&(u.comment=a,u.range[2]=c),u}function Yy({options:e},{offset:t,source:r,end:i},n){let a=new Wy.Alias(r.substring(1));a.source===""&&n(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(t+r.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+r.length,s=Gy.resolveEnd(i,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}Ks.composeEmptyNode=Us;Ks.composeNode=lf});var pf=S(ff=>{"use strict";var Xy=vi(),df=uf(),Qy=Nr(),Zy=Ni();function eN(e,t,{offset:r,start:i,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new Xy.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=Zy.resolveProps(i,{indicator:"doc-start",next:n??a?.[0],offset:r,onError:o,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!f.hasNewline&&o(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?df.composeNode(l,n,f,o):df.composeEmptyNode(l,f.end,i,null,f,o);let u=c.contents.range[2],d=Qy.resolveEnd(a,u,!1,o);return d.comment&&(c.comment=d.comment),c.range=[r,u,d.offset],c}ff.composeDoc=eN});var Xs=S(vf=>{"use strict";var tN=mn("process"),rN=Ho(),iN=vi(),bi=yi(),hf=A(),nN=pf(),aN=Nr();function ki(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:r}=e;return[t,t+(typeof r=="string"?r.length:1)]}function mf(e){let t="",r=!1,i=!1;for(let n=0;n<e.length;++n){let a=e[n];switch(a[0]){case"#":t+=(t===""?"":i?`
103
103
 
104
104
  `:`
105
- `)+(a.substring(1)||" "),r=!0,i=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),r=!1;break;default:r||(i=!0),r=!1}}return{comment:t,afterEmptyLine:i}}var Ys=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,i,n,a)=>{let o=ki(r);a?this.warnings.push(new bi.YAMLWarning(o,i,n)):this.errors.push(new bi.YAMLParseError(o,i,n))},this.directives=new eN.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,r){let{comment:i,afterEmptyLine:n}=mf(this.prelude);if(i){let a=t.contents;if(r)t.comment=t.comment?`${t.comment}
105
+ `)+(a.substring(1)||" "),r=!0,i=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),r=!1;break;default:r||(i=!0),r=!1}}return{comment:t,afterEmptyLine:i}}var Ys=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,i,n,a)=>{let o=ki(r);a?this.warnings.push(new bi.YAMLWarning(o,i,n)):this.errors.push(new bi.YAMLParseError(o,i,n))},this.directives=new rN.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,r){let{comment:i,afterEmptyLine:n}=mf(this.prelude);if(i){let a=t.contents;if(r)t.comment=t.comment?`${t.comment}
106
106
  ${i}`:i;else if(n||t.directives.docStart||!a)t.commentBefore=i;else if(hf.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];hf.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${i}
107
107
  ${s}`:i}else{let o=a.commentBefore;a.commentBefore=o?`${i}
108
- ${o}`:i}}if(r){for(let a=0;a<this.errors.length;++a)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:mf(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,r=!1,i=-1){for(let n of t)yield*this.next(n);yield*this.end(r,i)}*next(t){switch(Zy.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(r,i,n)=>{let a=ki(t);a[0]+=r,this.onError(a,"BAD_DIRECTIVE",i,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let r=rN.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!r.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(r,!1),this.doc&&(yield this.doc),this.doc=r,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let r=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,i=new bi.YAMLParseError(ki(t),"UNEXPECTED_TOKEN",r);this.atDirectives||!this.doc?this.errors.push(i):this.doc.errors.push(i);break}case"doc-end":{if(!this.doc){let i="Unexpected doc-end without preceding document";this.errors.push(new bi.YAMLParseError(ki(t),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let r=iN.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),r.comment){let i=this.doc.comment;this.doc.comment=i?`${i}
109
- ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new bi.YAMLParseError(ki(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,r=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let i=Object.assign({_directives:this.directives},this.options),n=new tN.Document(void 0,i);this.atDirectives&&this.onError(r,"MISSING_CHAR","Missing directives-end indicator line"),n.range=[0,r,r],this.decorate(n,!1),yield n}}};vf.Composer=Ys});var yf=S(oa=>{"use strict";var nN=zs(),aN=Gs(),oN=yi(),gf=ai();function sN(e,t=!0,r){if(e){let i=(n,a,o)=>{let s=typeof n=="number"?n:Array.isArray(n)?n[0]:n.offset;if(r)r(s,a,o);else throw new oN.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return aN.resolveFlowScalar(e,t,i);case"block-scalar":return nN.resolveBlockScalar({options:{strict:t}},e,i)}}return null}function cN(e,t){let{implicitKey:r=!1,indent:i,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=gf.stringifyString({type:o,value:e},{implicitKey:r,indent:i>0?" ".repeat(i):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:i,source:`
108
+ ${o}`:i}}if(r){for(let a=0;a<this.errors.length;++a)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:mf(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,r=!1,i=-1){for(let n of t)yield*this.next(n);yield*this.end(r,i)}*next(t){switch(tN.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(r,i,n)=>{let a=ki(t);a[0]+=r,this.onError(a,"BAD_DIRECTIVE",i,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let r=nN.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!r.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(r,!1),this.doc&&(yield this.doc),this.doc=r,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let r=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,i=new bi.YAMLParseError(ki(t),"UNEXPECTED_TOKEN",r);this.atDirectives||!this.doc?this.errors.push(i):this.doc.errors.push(i);break}case"doc-end":{if(!this.doc){let i="Unexpected doc-end without preceding document";this.errors.push(new bi.YAMLParseError(ki(t),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let r=aN.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),r.comment){let i=this.doc.comment;this.doc.comment=i?`${i}
109
+ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new bi.YAMLParseError(ki(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,r=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let i=Object.assign({_directives:this.directives},this.options),n=new iN.Document(void 0,i);this.atDirectives&&this.onError(r,"MISSING_CHAR","Missing directives-end indicator line"),n.range=[0,r,r],this.decorate(n,!1),yield n}}};vf.Composer=Ys});var yf=S(oa=>{"use strict";var oN=zs(),sN=Gs(),cN=yi(),gf=ai();function lN(e,t=!0,r){if(e){let i=(n,a,o)=>{let s=typeof n=="number"?n:Array.isArray(n)?n[0]:n.offset;if(r)r(s,a,o);else throw new cN.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return sN.resolveFlowScalar(e,t,i);case"block-scalar":return oN.resolveBlockScalar({options:{strict:t}},e,i)}}return null}function uN(e,t){let{implicitKey:r=!1,indent:i,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=gf.stringifyString({type:o,value:e},{implicitKey:r,indent:i>0?" ".repeat(i):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:i,source:`
110
110
  `}];switch(s[0]){case"|":case">":{let l=s.indexOf(`
111
111
  `),f=s.substring(0,l),u=s.substring(l+1)+`
112
112
  `,d=[{type:"block-scalar-header",offset:a,indent:i,source:f}];return wf(d,c)||d.push({type:"newline",offset:-1,indent:i,source:`
113
- `}),{type:"block-scalar",offset:a,indent:i,props:d,source:u}}case'"':return{type:"double-quoted-scalar",offset:a,indent:i,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:i,source:s,end:c};default:return{type:"scalar",offset:a,indent:i,source:s,end:c}}}function lN(e,t,r={}){let{afterKey:i=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=r,s="indent"in e?e.indent:null;if(i&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=gf.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">":uN(e,c);break;case'"':Qs(e,c,"double-quoted-scalar");break;case"'":Qs(e,c,"single-quoted-scalar");break;default:Qs(e,c,"scalar")}}function uN(e,t){let r=t.indexOf(`
113
+ `}),{type:"block-scalar",offset:a,indent:i,props:d,source:u}}case'"':return{type:"double-quoted-scalar",offset:a,indent:i,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:i,source:s,end:c};default:return{type:"scalar",offset:a,indent:i,source:s,end:c}}}function dN(e,t,r={}){let{afterKey:i=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=r,s="indent"in e?e.indent:null;if(i&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=gf.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">":fN(e,c);break;case'"':Qs(e,c,"double-quoted-scalar");break;case"'":Qs(e,c,"single-quoted-scalar");break;default:Qs(e,c,"scalar")}}function fN(e,t){let r=t.indexOf(`
114
114
  `),i=t.substring(0,r),n=t.substring(r+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=i,e.source=n}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:i}];wf(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 wf(e,t){if(t)for(let r of t)switch(r.type){case"space":case"comment":e.push(r);break;case"newline":return e.push(r),!0}return!1}function Qs(e,t,r){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=r,e.source=t;break;case"block-scalar":{let i=e.props.slice(1),n=t.length;e.props[0].type==="block-scalar-header"&&(n-=e.props[0].source.length);for(let a of i)a.offset+=n;delete e.props,Object.assign(e,{type:r,source:t,end:i});break}case"block-map":case"block-seq":{let n={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
117
- `};delete e.items,Object.assign(e,{type:r,source:t,end:[n]});break}default:{let i="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:r,indent:i,source:t,end:n})}}}oa.createScalarToken=cN;oa.resolveAsScalar=sN;oa.setScalarValue=lN});var bf=S(Nf=>{"use strict";var dN=e=>"type"in e?ca(e):sa(e);function ca(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=ca(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=sa(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=sa(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=sa(e);if(e.end)for(let r of e.end)t+=r.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let r of e.end)t+=r.source;return t}}}function sa({start:e,key:t,sep:r,value:i}){let n="";for(let a of e)n+=a.source;if(t&&(n+=ca(t)),r)for(let a of r)n+=a.source;return i&&(n+=ca(i)),n}Nf.stringify=dN});var xf=S(Ef=>{"use strict";var Zs=Symbol("break visit"),fN=Symbol("skip children"),kf=Symbol("remove item");function Qt(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Sf(Object.freeze([]),e,t)}Qt.BREAK=Zs;Qt.SKIP=fN;Qt.REMOVE=kf;Qt.itemAtPath=(e,t)=>{let r=e;for(let[i,n]of t){let a=r?.[i];if(a&&"items"in a)r=a.items[n];else return}return r};Qt.parentCollection=(e,t)=>{let r=Qt.itemAtPath(e,t.slice(0,-1)),i=t[t.length-1][0],n=r?.[i];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function Sf(e,t,r){let i=r(t,e);if(typeof i=="symbol")return i;for(let n of["key","value"]){let a=t[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=Sf(Object.freeze(e.concat([[n,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===Zs)return Zs;s===kf&&(a.items.splice(o,1),o-=1)}}typeof i=="function"&&n==="key"&&(i=i(t,e))}}return typeof i=="function"?i(t,e):i}Ef.visit=Qt});var la=S(we=>{"use strict";var ec=yf(),pN=bf(),hN=xf(),tc="\uFEFF",rc="",ic="",nc="",mN=e=>!!e&&"items"in e,vN=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function gN(e){switch(e){case tc:return"<BOM>";case rc:return"<DOC>";case ic:return"<FLOW_END>";case nc:return"<SCALAR>";default:return JSON.stringify(e)}}function wN(e){switch(e){case tc:return"byte-order-mark";case rc:return"doc-mode";case ic:return"flow-error-end";case nc:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
117
+ `};delete e.items,Object.assign(e,{type:r,source:t,end:[n]});break}default:{let i="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:r,indent:i,source:t,end:n})}}}oa.createScalarToken=uN;oa.resolveAsScalar=lN;oa.setScalarValue=dN});var bf=S(Nf=>{"use strict";var pN=e=>"type"in e?ca(e):sa(e);function ca(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=ca(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=sa(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=sa(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=sa(e);if(e.end)for(let r of e.end)t+=r.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let r of e.end)t+=r.source;return t}}}function sa({start:e,key:t,sep:r,value:i}){let n="";for(let a of e)n+=a.source;if(t&&(n+=ca(t)),r)for(let a of r)n+=a.source;return i&&(n+=ca(i)),n}Nf.stringify=pN});var xf=S(Ef=>{"use strict";var Zs=Symbol("break visit"),hN=Symbol("skip children"),kf=Symbol("remove item");function Qt(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Sf(Object.freeze([]),e,t)}Qt.BREAK=Zs;Qt.SKIP=hN;Qt.REMOVE=kf;Qt.itemAtPath=(e,t)=>{let r=e;for(let[i,n]of t){let a=r?.[i];if(a&&"items"in a)r=a.items[n];else return}return r};Qt.parentCollection=(e,t)=>{let r=Qt.itemAtPath(e,t.slice(0,-1)),i=t[t.length-1][0],n=r?.[i];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function Sf(e,t,r){let i=r(t,e);if(typeof i=="symbol")return i;for(let n of["key","value"]){let a=t[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=Sf(Object.freeze(e.concat([[n,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===Zs)return Zs;s===kf&&(a.items.splice(o,1),o-=1)}}typeof i=="function"&&n==="key"&&(i=i(t,e))}}return typeof i=="function"?i(t,e):i}Ef.visit=Qt});var la=S(we=>{"use strict";var ec=yf(),mN=bf(),vN=xf(),tc="\uFEFF",rc="",ic="",nc="",gN=e=>!!e&&"items"in e,wN=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function yN(e){switch(e){case tc:return"<BOM>";case rc:return"<DOC>";case ic:return"<FLOW_END>";case nc:return"<SCALAR>";default:return JSON.stringify(e)}}function NN(e){switch(e){case tc:return"byte-order-mark";case rc:return"doc-mode";case ic:return"flow-error-end";case nc: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}we.createScalarToken=ec.createScalarToken;we.resolveAsScalar=ec.resolveAsScalar;we.setScalarValue=ec.setScalarValue;we.stringify=pN.stringify;we.visit=hN.visit;we.BOM=tc;we.DOCUMENT=rc;we.FLOW_END=ic;we.SCALAR=nc;we.isCollection=mN;we.isScalar=vN;we.prettyToken=gN;we.tokenType=wN});var sc=S(Pf=>{"use strict";var Si=la();function Oe(e){switch(e){case void 0:case" ":case`
120
- `:case"\r":case" ":return!0;default:return!1}}var Cf=new Set("0123456789ABCDEFabcdef"),yN=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),ua=new Set(",[]{}"),NN=new Set(` ,[]{}
121
- \r `),ac=e=>!e||NN.has(e),oc=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,r=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!r;let i=this.next??"stream";for(;i&&(r||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let t=this.pos,r=this.buffer[t];for(;r===" "||r===" ";)r=this.buffer[++t];return!r||r==="#"||r===`
119
+ `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}we.createScalarToken=ec.createScalarToken;we.resolveAsScalar=ec.resolveAsScalar;we.setScalarValue=ec.setScalarValue;we.stringify=mN.stringify;we.visit=vN.visit;we.BOM=tc;we.DOCUMENT=rc;we.FLOW_END=ic;we.SCALAR=nc;we.isCollection=gN;we.isScalar=wN;we.prettyToken=yN;we.tokenType=NN});var sc=S(Pf=>{"use strict";var Si=la();function Oe(e){switch(e){case void 0:case" ":case`
120
+ `:case"\r":case" ":return!0;default:return!1}}var Cf=new Set("0123456789ABCDEFabcdef"),bN=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),ua=new Set(",[]{}"),kN=new Set(` ,[]{}
121
+ \r `),ac=e=>!e||kN.has(e),oc=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,r=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!r;let i=this.next??"stream";for(;i&&(r||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let t=this.pos,r=this.buffer[t];for(;r===" "||r===" ";)r=this.buffer[++t];return!r||r==="#"||r===`
122
122
  `?!0:r==="\r"?this.buffer[t+1]===`
123
123
  `:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let r=this.buffer[t];if(this.indentNext>0){let i=0;for(;r===" ";)r=this.buffer[++i+t];if(r==="\r"){let n=this.buffer[i+t+1];if(n===`
124
124
  `||!n&&!this.atEnd)return t+i+1}return r===`
@@ -133,14 +133,14 @@ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.pus
133
133
  `&&a>=this.pos&&a+1+r>s)t=a;else break}while(!0);return yield Si.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,r=this.pos-1,i=this.pos-1,n;for(;n=this.buffer[++i];)if(n===":"){let a=this.buffer[i+1];if(Oe(a)||t&&ua.has(a))break;r=i}else if(Oe(n)){let a=this.buffer[i+1];if(n==="\r"&&(a===`
134
134
  `?(i+=1,n=`
135
135
  `,a=this.buffer[i+1]):r=i),a==="#"||t&&ua.has(a))break;if(n===`
136
- `){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&ua.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield Si.SCALAR,yield*this.pushToIndex(r+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,r){let i=this.buffer.slice(this.pos,t);return i?(yield i,this.pos+=i.length,i.length):(r&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(ac),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(Oe(i)||r&&ua.has(i)){r?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,r=this.buffer[t];for(;!Oe(r)&&r!==">";)r=this.buffer[++t];return yield*this.pushToIndex(r===">"?t+1:t,!1)}else{let t=this.pos+1,r=this.buffer[t];for(;r;)if(yN.has(r))r=this.buffer[++t];else if(r==="%"&&Cf.has(this.buffer[t+1])&&Cf.has(this.buffer[t+2]))r=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
136
+ `){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&ua.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield Si.SCALAR,yield*this.pushToIndex(r+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,r){let i=this.buffer.slice(this.pos,t);return i?(yield i,this.pos+=i.length,i.length):(r&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(ac),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(Oe(i)||r&&ua.has(i)){r?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,r=this.buffer[t];for(;!Oe(r)&&r!==">";)r=this.buffer[++t];return yield*this.pushToIndex(r===">"?t+1:t,!1)}else{let t=this.pos+1,r=this.buffer[t];for(;r;)if(bN.has(r))r=this.buffer[++t];else if(r==="%"&&Cf.has(this.buffer[t+1])&&Cf.has(this.buffer[t+2]))r=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
137
137
  `?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
138
- `?yield*this.pushCount(2):0}*pushSpaces(t){let r=this.pos-1,i;do i=this.buffer[++r];while(i===" "||t&&i===" ");let n=r-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=r),n}*pushUntil(t){let r=this.pos,i=this.buffer[r];for(;!t(i);)i=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};Pf.Lexer=oc});var lc=S(Rf=>{"use strict";var cc=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let r=0,i=this.lineStarts.length;for(;r<i;){let a=r+i>>1;this.lineStarts[a]<t?r=a+1:i=a}if(this.lineStarts[r]===t)return{line:r+1,col:1};if(r===0)return{line:0,col:t};let n=this.lineStarts[r-1];return{line:r,col:t-n+1}}}};Rf.LineCounter=cc});var dc=S(jf=>{"use strict";var bN=mn("process"),Af=la(),kN=sc();function _t(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function _f(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 Tf(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 da(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 br(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 fa(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let r=0;r<t.length;++r)e.push(t[r])}function If(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!_t(t.start,"explicit-key-ind")&&!_t(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Tf(t.value)?t.value.end?fa(t.value.end,t.sep):t.value.end=t.sep:fa(t.start,t.sep),delete t.sep)}var uc=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 kN.Lexer,this.onNewLine=t}*parse(t,r=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let i of this.lexer.lex(t,r))yield*this.next(i);r||(yield*this.end())}*next(t){if(this.source=t,bN.env.LOG_TOKENS&&console.log("|",Af.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=Af.tokenType(t);if(r)if(r==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=r,yield*this.step(),r){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let i=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:i,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let r=t??this.stack.pop();if(!r)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield r;else{let i=this.peek(1);switch(r.type==="block-scalar"?r.indent="indent"in i?i.indent:0:r.type==="flow-collection"&&i.type==="document"&&(r.indent=0),r.type==="flow-collection"&&If(r),i.type){case"document":i.value=r;break;case"block-scalar":i.props.push(r);break;case"block-map":{let n=i.items[i.items.length-1];if(n.value){i.items.push({start:[],key:r,sep:[]}),this.onKeyLine=!0;return}else if(n.sep)n.value=r;else{Object.assign(n,{key:r,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case"block-seq":{let n=i.items[i.items.length-1];n.value?i.items.push({start:[],value:r}):n.value=r;break}case"flow-collection":{let n=i.items[i.items.length-1];!n||n.value?i.items.push({start:[],key:r,sep:[]}):n.sep?n.value=r:Object.assign(n,{key:r,sep:[]});return}default:yield*this.pop(),yield*this.pop(r)}if((i.type==="document"||i.type==="block-map"||i.type==="block-seq")&&(r.type==="block-map"||r.type==="block-seq")){let n=r.items[r.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&_f(n.start)===-1&&(r.indent===0||n.start.every(a=>a.type!=="comment"||a.indent<r.indent))&&(i.type==="document"?i.end=n.start:i.items.push({start:n.start}),r.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{_f(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let r=da(this.peek(2)),i=br(r),n;t.end?(n=t.end,n.push(this.sourceToken),delete t.end):n=[this.sourceToken];let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:i,key:t,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let r=this.source.indexOf(`
138
+ `?yield*this.pushCount(2):0}*pushSpaces(t){let r=this.pos-1,i;do i=this.buffer[++r];while(i===" "||t&&i===" ");let n=r-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=r),n}*pushUntil(t){let r=this.pos,i=this.buffer[r];for(;!t(i);)i=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};Pf.Lexer=oc});var lc=S(Rf=>{"use strict";var cc=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let r=0,i=this.lineStarts.length;for(;r<i;){let a=r+i>>1;this.lineStarts[a]<t?r=a+1:i=a}if(this.lineStarts[r]===t)return{line:r+1,col:1};if(r===0)return{line:0,col:t};let n=this.lineStarts[r-1];return{line:r,col:t-n+1}}}};Rf.LineCounter=cc});var dc=S(jf=>{"use strict";var SN=mn("process"),Af=la(),EN=sc();function _t(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function _f(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 Tf(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 da(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 br(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 fa(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let r=0;r<t.length;++r)e.push(t[r])}function If(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!_t(t.start,"explicit-key-ind")&&!_t(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Tf(t.value)?t.value.end?fa(t.value.end,t.sep):t.value.end=t.sep:fa(t.start,t.sep),delete t.sep)}var uc=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 EN.Lexer,this.onNewLine=t}*parse(t,r=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let i of this.lexer.lex(t,r))yield*this.next(i);r||(yield*this.end())}*next(t){if(this.source=t,SN.env.LOG_TOKENS&&console.log("|",Af.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=Af.tokenType(t);if(r)if(r==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=r,yield*this.step(),r){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let i=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:i,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let r=t??this.stack.pop();if(!r)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield r;else{let i=this.peek(1);switch(r.type==="block-scalar"?r.indent="indent"in i?i.indent:0:r.type==="flow-collection"&&i.type==="document"&&(r.indent=0),r.type==="flow-collection"&&If(r),i.type){case"document":i.value=r;break;case"block-scalar":i.props.push(r);break;case"block-map":{let n=i.items[i.items.length-1];if(n.value){i.items.push({start:[],key:r,sep:[]}),this.onKeyLine=!0;return}else if(n.sep)n.value=r;else{Object.assign(n,{key:r,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case"block-seq":{let n=i.items[i.items.length-1];n.value?i.items.push({start:[],value:r}):n.value=r;break}case"flow-collection":{let n=i.items[i.items.length-1];!n||n.value?i.items.push({start:[],key:r,sep:[]}):n.sep?n.value=r:Object.assign(n,{key:r,sep:[]});return}default:yield*this.pop(),yield*this.pop(r)}if((i.type==="document"||i.type==="block-map"||i.type==="block-seq")&&(r.type==="block-map"||r.type==="block-seq")){let n=r.items[r.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&_f(n.start)===-1&&(r.indent===0||n.start.every(a=>a.type!=="comment"||a.indent<r.indent))&&(i.type==="document"?i.end=n.start:i.items.push({start:n.start}),r.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{_f(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let r=da(this.peek(2)),i=br(r),n;t.end?(n=t.end,n.push(this.sourceToken),delete t.end):n=[this.sourceToken];let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:i,key:t,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let r=this.source.indexOf(`
139
139
  `)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
140
140
  `,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else if(r.sep)r.sep.push(this.sourceToken);else{if(this.atIndentedComment(r.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){fa(n,r.start),n.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let i=!this.onKeyLine&&this.indent===t.indent,n=i&&(r.sep||r.explicitKey)&&this.type!=="seq-item-ind",a=[];if(n&&r.sep&&!r.value){let o=[];for(let s=0;s<r.sep.length;++s){let c=r.sep[s];switch(c.type){case"newline":o.push(s);break;case"space":break;case"comment":c.indent>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=r.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":n||r.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"explicit-key-ind":!r.sep&&!r.explicitKey?(r.start.push(this.sourceToken),r.explicitKey=!0):n||r.value?(a.push(this.sourceToken),t.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(r.explicitKey)if(r.sep)if(r.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(_t(r.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]});else if(Tf(r.key)&&!_t(r.sep,"newline")){let o=br(r.start),s=r.key,c=r.sep;c.push(this.sourceToken),delete r.key,delete r.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?r.sep=r.sep.concat(a,this.sourceToken):r.sep.push(this.sourceToken);else if(_t(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=br(r.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else r.sep?r.value||n?t.items.push({start:a,key:null,sep:[this.sourceToken]}):_t(r.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);n||r.value?(t.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):r.sep?this.stack.push(o):(Object.assign(r,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!r.explicitKey&&r.sep&&!_t(r.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else i&&t.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(r.value){let i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(r.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){fa(n,r.start),n.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return;case"anchor":case"tag":if(r.value||this.indent<=t.indent)break;r.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;r.value||_t(r.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return}if(this.indent>t.indent){let i=this.startBlockValue(t);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let r=t.items[t.items.length-1];if(this.type==="flow-error-end"){let i;do yield*this.pop(),i=this.peek(1);while(i?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!r||r.sep?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return;case"map-value-ind":!r||r.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!r||r.value?t.items.push({start:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let n=this.flowScalar(this.type);!r||r.value?t.items.push({start:[],key:n,sep:[]}):r.sep?this.stack.push(n):Object.assign(r,{key:n,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let i=this.startBlockValue(t);i?this.stack.push(i):(yield*this.pop(),yield*this.step())}else{let i=this.peek(2);if(i.type==="block-map"&&(this.type==="map-value-ind"&&i.indent===t.indent||this.type==="newline"&&!i.items[i.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&i.type!=="flow-collection"){let n=da(i),a=br(n);If(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let r=this.source.indexOf(`
141
141
  `)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
142
- `,r)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=da(t),i=br(r);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let r=da(t),i=br(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,r){return this.type!=="comment"||this.indent<=r?!1:t.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};jf.Parser=uc});var Bf=S(xi=>{"use strict";var $f=Xs(),SN=vi(),Ei=yi(),EN=Ko(),xN=A(),CN=lc(),Of=dc();function Hf(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new CN.LineCounter||null,prettyErrors:t}}function PN(e,t={}){let{lineCounter:r,prettyErrors:i}=Hf(t),n=new Of.Parser(r?.addNewLine),a=new $f.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach(Ei.prettifyError(e,r)),s.warnings.forEach(Ei.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Df(e,t={}){let{lineCounter:r,prettyErrors:i}=Hf(t),n=new Of.Parser(r?.addNewLine),a=new $f.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 Ei.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(Ei.prettifyError(e,r)),o.warnings.forEach(Ei.prettifyError(e,r))),o}function RN(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=Df(e,r);if(!n)return null;if(n.warnings.forEach(a=>EN.warn(n.options.logLevel,a)),n.errors.length>0){if(n.options.logLevel!=="silent")throw n.errors[0];n.errors=[]}return n.toJS(Object.assign({reviver:i},r))}function AN(e,t,r){let i=null;if(typeof t=="function"||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r=="string"&&(r=r.length),typeof r=="number"){let n=Math.round(r);r=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=r??t??{};if(!n)return}return xN.isDocument(e)&&!i?e.toString(r):new SN.Document(e,i,r).toString(r)}xi.parse=RN;xi.parseAllDocuments=PN;xi.parseDocument=Df;xi.stringify=AN});var kr=S($=>{"use strict";var _N=Xs(),IN=vi(),TN=Is(),fc=yi(),jN=ei(),It=A(),$N=Ct(),ON=G(),HN=Rt(),DN=At(),BN=la(),LN=sc(),VN=lc(),MN=dc(),pa=Bf(),Lf=Yr();$.Composer=_N.Composer;$.Document=IN.Document;$.Schema=TN.Schema;$.YAMLError=fc.YAMLError;$.YAMLParseError=fc.YAMLParseError;$.YAMLWarning=fc.YAMLWarning;$.Alias=jN.Alias;$.isAlias=It.isAlias;$.isCollection=It.isCollection;$.isDocument=It.isDocument;$.isMap=It.isMap;$.isNode=It.isNode;$.isPair=It.isPair;$.isScalar=It.isScalar;$.isSeq=It.isSeq;$.Pair=$N.Pair;$.Scalar=ON.Scalar;$.YAMLMap=HN.YAMLMap;$.YAMLSeq=DN.YAMLSeq;$.CST=BN;$.Lexer=LN.Lexer;$.LineCounter=VN.LineCounter;$.Parser=MN.Parser;$.parse=pa.parse;$.parseAllDocuments=pa.parseAllDocuments;$.parseDocument=pa.parseDocument;$.stringify=pa.stringify;$.visit=Lf.visit;$.visitAsync=Lf.visitAsync});var fl=Kr(kr(),1);import{promises as xh}from"node:fs";import Te from"node:path";import{execFileSync as FN}from"child_process";import Ci from"path";function Tt(e,t){return FN("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function qN(e,t){let r=Ci.normalize(e),i=Ci.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function z(e){try{let t=Ci.resolve(Tt(e,["rev-parse","--show-toplevel"])),i=Tt(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?Ci.resolve(i.slice(9)):t,a=null;try{a=Tt(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!qN(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function ha(e){try{Tt(e,["rev-parse","--is-inside-work-tree"]);let t=Tt(e,["worktree","list","--porcelain"]).split(/\r?\n/u),r=[],i=null;for(let n of t)n.startsWith("worktree ")?(i&&r.push(i),i={root:Ci.resolve(n.slice(9)),branch:null,detached:!1}):i&&n.startsWith("branch refs/heads/")?i.branch=n.slice(18):i&&n==="detached"&&(i.detached=!0);return i&&r.push(i),r}catch{return[]}}function Zt(e){return ha(e).map(t=>t.root)}function Sr(e,t){try{return Tt(e,["check-ref-format","--branch",t]),Tt(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function Er(e,t){try{let r=Tt(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}import{execFileSync as WN}from"node:child_process";var zN=3e4,JN=8*1024*1024,pc=class extends Error{constructor(r,i,n){super(`git ${i.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=r;this.args=i;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr};function GN(e,t){try{return WN("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:zN,maxBuffer:JN,windowsHide:!0})}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new pc(e,t,i)}}function I(e,t){return GN(e,t).trim()}function ut(e){return I(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function hc(e,t){I(e,["check-ref-format","--branch",t])}import{createHash as XN}from"node:crypto";import{promises as He}from"node:fs";import Pe from"node:path";import{TextDecoder as QN}from"node:util";var UN=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),KN=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function YN(e){return e.toLowerCase().startsWith(".env")}function Pi(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>YN(i))?"environment-file":r.some(i=>KN.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>UN.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}function jt(e){return e!==0&&e!==0n&&e!=="0"}function Ke(e,t){return jt(e.dev)&&jt(t.dev)&&jt(e.ino)&&jt(t.ino)}function M(e,t){let r=jt(e.dev)&&jt(t.dev);if(r&&e.dev!==t.dev)return!1;let i=jt(e.ino)&&jt(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var va=1024*1024;function mc(e,t){let r=Pe.relative(e,t);return r===""||!Pe.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Pe.sep}`)}function ZN(e){let t=Pe.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})||Pe.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let r=e.toLowerCase(),i=Pi(e);if(i||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${i??"native-runtime"}): ${e}`);return e}function eb(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function tb(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ma(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Ke(r,i)?M(r,i):M(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Vf(e){let t=await He.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await He.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function rb(e,t){let r=Pe.resolve(e),i=Pe.resolve(t);if(!mc(r,i))throw new Error("Native artifact path is outside its root");let n=[await Vf(r)],a=r;for(let o of Pe.relative(r,i).split(Pe.sep).filter(Boolean)){a=Pe.join(a,o);let s=await Vf(a);if(!mc(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function Mf(e){for(let t of e){let r=await He.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!tb(t,r)||await He.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function Y(e){let t=ZN(e.ref),r=e.maxBytes===null?null:eb(e.maxBytes??va),i=Pe.resolve(e.root,...t.split("/")),n=await rb(e.root,Pe.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await He.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(r!==null&&a.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);let o=await He.realpath(i);if(!mc(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await He.open(i,"r");try{let[c,l,f]=await Promise.all([s.stat(),He.lstat(i),He.realpath(i)]);if(await Mf(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||f!==o||!ma(a,c)||!ma(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let u=[],d=0,m=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let y=r===null?m.length:r+1-d,b=await s.read(m,0,Math.min(m.length,y),null);if(b.bytesRead===0)break;if(d+=b.bytesRead,r!==null&&d>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);u.push(Buffer.from(m.subarray(0,b.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,h,p]=await Promise.all([s.stat(),He.lstat(i),He.realpath(i)]);if(await Mf(n),!h.isFile()||h.isSymbolicLink()||p!==o||!ma(c,v)||!ma(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let w=Buffer.concat(u,d),g;try{g=new QN("utf-8",{fatal:!0}).decode(w)}catch(y){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:y})}return{ref:t,size:d,hash:e.includeHash===!1?null:XN("sha256").update(w).digest("hex"),text:g}}finally{await s.close()}}import{createHash as ib}from"crypto";function De(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function nb(e,t){t.has(e)&&De("cyclic structures are not supported"),t.add(e);try{let r=Object.keys(e);for(let i=0;i<e.length;i+=1)Object.prototype.hasOwnProperty.call(e,i)||De("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&De("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&De("symbol properties are not supported"),`[${e.map(i=>vc(i,t)).join(",")}]`}finally{t.delete(e)}}function ab(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&De("only plain objects are supported"),t.has(e)&&De("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&De("symbol properties are not supported"),t.add(e);try{let i=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=i[o];return(!s||!("value"in s))&&De("accessor properties are not supported"),`${JSON.stringify(o)}:${vc(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function vc(e,t){if(e===null)return"null";switch(typeof e){case"boolean":return e?"true":"false";case"string":return JSON.stringify(e);case"number":return Number.isFinite(e)||De("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?nb(e,t):ab(e,t);case"bigint":case"function":case"symbol":case"undefined":return De(`${typeof e} values are not supported`)}return De("unsupported value type")}function gc(e){return vc(e,new Set)}function X(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 ib("sha256").update(`${e}
143
- ${gc(t)}`).digest("hex")}import qb from"path";var Ai=Kr(kr(),1);import $t from"path";var _i=64*1024,ga=1024,wa=64,Ff=1024,qf=64,yc=5,Ri={learning:!0,retrieval:!0},Nc={provider:"local"},ob=12e4,Wf=6e5,sb=[".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/**"],cb=["**/.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"],lb=[...sb,...cb].sort((e,t)=>e.localeCompare(t,"en"));var ke={include:["**/*"],exclude:[...lb],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},xr={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it.
142
+ `,r)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=da(t),i=br(r);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let r=da(t),i=br(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,r){return this.type!=="comment"||this.indent<=r?!1:t.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};jf.Parser=uc});var Bf=S(xi=>{"use strict";var $f=Xs(),xN=vi(),Ei=yi(),CN=Ko(),PN=A(),RN=lc(),Of=dc();function Hf(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new RN.LineCounter||null,prettyErrors:t}}function AN(e,t={}){let{lineCounter:r,prettyErrors:i}=Hf(t),n=new Of.Parser(r?.addNewLine),a=new $f.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach(Ei.prettifyError(e,r)),s.warnings.forEach(Ei.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Df(e,t={}){let{lineCounter:r,prettyErrors:i}=Hf(t),n=new Of.Parser(r?.addNewLine),a=new $f.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 Ei.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(Ei.prettifyError(e,r)),o.warnings.forEach(Ei.prettifyError(e,r))),o}function _N(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=Df(e,r);if(!n)return null;if(n.warnings.forEach(a=>CN.warn(n.options.logLevel,a)),n.errors.length>0){if(n.options.logLevel!=="silent")throw n.errors[0];n.errors=[]}return n.toJS(Object.assign({reviver:i},r))}function IN(e,t,r){let i=null;if(typeof t=="function"||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r=="string"&&(r=r.length),typeof r=="number"){let n=Math.round(r);r=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=r??t??{};if(!n)return}return PN.isDocument(e)&&!i?e.toString(r):new xN.Document(e,i,r).toString(r)}xi.parse=_N;xi.parseAllDocuments=AN;xi.parseDocument=Df;xi.stringify=IN});var kr=S($=>{"use strict";var TN=Xs(),jN=vi(),$N=Is(),fc=yi(),ON=ei(),It=A(),HN=Ct(),DN=G(),BN=Rt(),LN=At(),VN=la(),MN=sc(),FN=lc(),qN=dc(),pa=Bf(),Lf=Yr();$.Composer=TN.Composer;$.Document=jN.Document;$.Schema=$N.Schema;$.YAMLError=fc.YAMLError;$.YAMLParseError=fc.YAMLParseError;$.YAMLWarning=fc.YAMLWarning;$.Alias=ON.Alias;$.isAlias=It.isAlias;$.isCollection=It.isCollection;$.isDocument=It.isDocument;$.isMap=It.isMap;$.isNode=It.isNode;$.isPair=It.isPair;$.isScalar=It.isScalar;$.isSeq=It.isSeq;$.Pair=HN.Pair;$.Scalar=DN.Scalar;$.YAMLMap=BN.YAMLMap;$.YAMLSeq=LN.YAMLSeq;$.CST=VN;$.Lexer=MN.Lexer;$.LineCounter=FN.LineCounter;$.Parser=qN.Parser;$.parse=pa.parse;$.parseAllDocuments=pa.parseAllDocuments;$.parseDocument=pa.parseDocument;$.stringify=pa.stringify;$.visit=Lf.visit;$.visitAsync=Lf.visitAsync});var fl=Kr(kr(),1);import{promises as xh}from"node:fs";import Te from"node:path";import{execFileSync as WN}from"child_process";import Ci from"path";function Tt(e,t){return WN("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function zN(e,t){let r=Ci.normalize(e),i=Ci.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function z(e){try{let t=Ci.resolve(Tt(e,["rev-parse","--show-toplevel"])),i=Tt(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?Ci.resolve(i.slice(9)):t,a=null;try{a=Tt(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!zN(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function ha(e){try{Tt(e,["rev-parse","--is-inside-work-tree"]);let t=Tt(e,["worktree","list","--porcelain"]).split(/\r?\n/u),r=[],i=null;for(let n of t)n.startsWith("worktree ")?(i&&r.push(i),i={root:Ci.resolve(n.slice(9)),branch:null,detached:!1}):i&&n.startsWith("branch refs/heads/")?i.branch=n.slice(18):i&&n==="detached"&&(i.detached=!0);return i&&r.push(i),r}catch{return[]}}function Zt(e){return ha(e).map(t=>t.root)}function Sr(e,t){try{return Tt(e,["check-ref-format","--branch",t]),Tt(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function Er(e,t){try{let r=Tt(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}import{execFileSync as JN}from"node:child_process";var GN=3e4,UN=8*1024*1024,pc=class extends Error{constructor(r,i,n){super(`git ${i.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=r;this.args=i;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr};function KN(e,t){try{return JN("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:GN,maxBuffer:UN,windowsHide:!0})}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new pc(e,t,i)}}function I(e,t){return KN(e,t).trim()}function ut(e){return I(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function hc(e,t){I(e,["check-ref-format","--branch",t])}import{createHash as ZN}from"node:crypto";import{promises as He}from"node:fs";import Pe from"node:path";import{TextDecoder as eb}from"node:util";var YN=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),XN=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function QN(e){return e.toLowerCase().startsWith(".env")}function Pi(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>QN(i))?"environment-file":r.some(i=>XN.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>YN.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}function jt(e){return e!==0&&e!==0n&&e!=="0"}function Ke(e,t){return jt(e.dev)&&jt(t.dev)&&jt(e.ino)&&jt(t.ino)}function M(e,t){let r=jt(e.dev)&&jt(t.dev);if(r&&e.dev!==t.dev)return!1;let i=jt(e.ino)&&jt(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var va=1024*1024;function mc(e,t){let r=Pe.relative(e,t);return r===""||!Pe.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Pe.sep}`)}function tb(e){let t=Pe.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})||Pe.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let r=e.toLowerCase(),i=Pi(e);if(i||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${i??"native-runtime"}): ${e}`);return e}function rb(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function ib(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ma(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Ke(r,i)?M(r,i):M(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Vf(e){let t=await He.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await He.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function nb(e,t){let r=Pe.resolve(e),i=Pe.resolve(t);if(!mc(r,i))throw new Error("Native artifact path is outside its root");let n=[await Vf(r)],a=r;for(let o of Pe.relative(r,i).split(Pe.sep).filter(Boolean)){a=Pe.join(a,o);let s=await Vf(a);if(!mc(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function Mf(e){for(let t of e){let r=await He.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!ib(t,r)||await He.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function Y(e){let t=tb(e.ref),r=e.maxBytes===null?null:rb(e.maxBytes??va),i=Pe.resolve(e.root,...t.split("/")),n=await nb(e.root,Pe.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await He.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(r!==null&&a.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);let o=await He.realpath(i);if(!mc(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await He.open(i,"r");try{let[c,l,f]=await Promise.all([s.stat(),He.lstat(i),He.realpath(i)]);if(await Mf(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||f!==o||!ma(a,c)||!ma(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let u=[],d=0,m=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let y=r===null?m.length:r+1-d,b=await s.read(m,0,Math.min(m.length,y),null);if(b.bytesRead===0)break;if(d+=b.bytesRead,r!==null&&d>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);u.push(Buffer.from(m.subarray(0,b.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,h,p]=await Promise.all([s.stat(),He.lstat(i),He.realpath(i)]);if(await Mf(n),!h.isFile()||h.isSymbolicLink()||p!==o||!ma(c,v)||!ma(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let w=Buffer.concat(u,d),g;try{g=new eb("utf-8",{fatal:!0}).decode(w)}catch(y){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:y})}return{ref:t,size:d,hash:e.includeHash===!1?null:ZN("sha256").update(w).digest("hex"),text:g}}finally{await s.close()}}import{createHash as ab}from"crypto";function De(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function ob(e,t){t.has(e)&&De("cyclic structures are not supported"),t.add(e);try{let r=Object.keys(e);for(let i=0;i<e.length;i+=1)Object.prototype.hasOwnProperty.call(e,i)||De("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&De("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&De("symbol properties are not supported"),`[${e.map(i=>vc(i,t)).join(",")}]`}finally{t.delete(e)}}function sb(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&De("only plain objects are supported"),t.has(e)&&De("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&De("symbol properties are not supported"),t.add(e);try{let i=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=i[o];return(!s||!("value"in s))&&De("accessor properties are not supported"),`${JSON.stringify(o)}:${vc(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function vc(e,t){if(e===null)return"null";switch(typeof e){case"boolean":return e?"true":"false";case"string":return JSON.stringify(e);case"number":return Number.isFinite(e)||De("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?ob(e,t):sb(e,t);case"bigint":case"function":case"symbol":case"undefined":return De(`${typeof e} values are not supported`)}return De("unsupported value type")}function gc(e){return vc(e,new Set)}function X(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 ab("sha256").update(`${e}
143
+ ${gc(t)}`).digest("hex")}import zb from"path";var Ai=Kr(kr(),1);import $t from"path";var _i=64*1024,ga=1024,wa=64,Ff=1024,qf=64,yc=5,Ri={learning:!0,retrieval:!0},Nc={provider:"local"},cb=12e4,Wf=6e5,lb=[".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/**"],ub=["**/.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"],db=[...lb,...ub].sort((e,t)=>e.localeCompare(t,"en"));var ke={include:["**/*"],exclude:[...db],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},xr={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it.
144
144
  # ambient_resume: true | false`,memory:"# Project policy for automatic personal-memory learning and retrieval.","memory.learning":`# Allows workflow events in this project to form new personal memories automatically.
145
145
  # learning: true | false`,"memory.retrieval":`# Allows personal memories to be injected into Agent context for this project.
146
146
  # retrieval: true | false`,knowledge:"# Project knowledge retrieval provider used by ordinary Comet tasks.","knowledge.provider":`# Provider for project knowledge.
@@ -164,24 +164,24 @@ ${gc(t)}`).digest("hex")}import qb from"path";var Ai=Kr(kr(),1);import $t from"p
164
164
  # 可选值:en | zh-CN`,"classic.context_compression":`# 新建 Classic change 是否启用 beta 上下文压缩。
165
165
  # 可选值:off | beta`,"classic.review_mode":`# 新建 Classic change 默认使用的审查深度。
166
166
  # 可选值:off | standard | thorough`,"classic.auto_transition":`# Classic 阶段通过后是否自动进入下一阶段。
167
- # 可选值:true | false`}};function Jf(e,t){return xr[t][e]}function ub(e,t,r,i){let n=/^(\s*)([a-z_]+):/u.exec(e);if(!n)return null;let a=n[1].length,o=n[2];if(a===0&&o in xr.en)return o;if(a===2&&t){let s=`${t}.${o}`;if(s in xr.en)return s}if(a===4&&t==="knowledge"&&i==="remote"){let s=`knowledge.remote.${o}`;if(s in xr.en)return s}if(a===4&&t==="knowledge"&&i==="local"){let s=`knowledge.local.${o}`;if(s in xr.en)return s}if(a===2&&t===null&&o==="hook")return"hook";if(a===2&&t==="hook"&&o==="allow_paths")return"hook.allow_paths";if(a===4&&t==="native"&&r==="snapshot"){let s=`native.snapshot.${o}`;if(s in xr.en)return s}return null}function Ii(e,t){let r=[],i=null,n=null,a=null;for(let o of(0,Ai.stringify)(e).trimEnd().split(`
168
- `)){let s=ub(o,i,n,a);if(s){let c=o.match(/^\s*/u)?.[0]??"";for(let l of Jf(s,t).split(`
167
+ # 可选值:true | false`}};function Jf(e,t){return xr[t][e]}function fb(e,t,r,i){let n=/^(\s*)([a-z_]+):/u.exec(e);if(!n)return null;let a=n[1].length,o=n[2];if(a===0&&o in xr.en)return o;if(a===2&&t){let s=`${t}.${o}`;if(s in xr.en)return s}if(a===4&&t==="knowledge"&&i==="remote"){let s=`knowledge.remote.${o}`;if(s in xr.en)return s}if(a===4&&t==="knowledge"&&i==="local"){let s=`knowledge.local.${o}`;if(s in xr.en)return s}if(a===2&&t===null&&o==="hook")return"hook";if(a===2&&t==="hook"&&o==="allow_paths")return"hook.allow_paths";if(a===4&&t==="native"&&r==="snapshot"){let s=`native.snapshot.${o}`;if(s in xr.en)return s}return null}function Ii(e,t){let r=[],i=null,n=null,a=null;for(let o of(0,Ai.stringify)(e).trimEnd().split(`
168
+ `)){let s=fb(o,i,n,a);if(s){let c=o.match(/^\s*/u)?.[0]??"";for(let l of Jf(s,t).split(`
169
169
  `))r.push(`${c}${l}`)}r.push(o),/^[a-z_]+:/u.test(o)?(o.startsWith("native:")?i="native":o.startsWith("classic:")?i="classic":o.startsWith("hook:")?i="hook":o.startsWith("memory:")?i="memory":o.startsWith("knowledge:")?i="knowledge":i=null,n=null,a=null):/^ {2}[a-z_]+:/u.test(o)&&(i==="native"&&(n=o.startsWith(" snapshot:")?"snapshot":null),i==="knowledge"&&(a=o.startsWith(" local:")?"local":o.startsWith(" remote:")?"remote":null))}return r.push(""),r.join(`
170
- `)}function db(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||$t.posix.isAbsolute(r)||$t.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be a project-relative path`);if(r===".")return[];let i=r.replaceAll("\\","/").split("/");if(i.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(i.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return i}function er(e){let t=db(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Gf(e,t="docs"){let r=e??t;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function ya(e,t,r=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim().replaceAll("\\","/");if(i.length===0||$t.posix.isAbsolute(i)||$t.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be relative to its declared path base`);let n=i.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!r&&/[*?]/u.test(i))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function dt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Uf(e,t,r){let i=e??t;if(i!=="en"&&i!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return i}function bc(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>ga)throw new Error(`${t} exceeds ${ga} characters`);let r=0;for(let i=0;i<e.length;i+=1)e[i]==="?"?r+=1:e[i]==="*"&&(r+=1,e[i+1]==="*"&&(i+=1));if(r>wa)throw new Error(`${t} contains more than ${wa} wildcard tokens`);return e}function zf(e,t,r){if(e===void 0)return[...r];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(i=>bc(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function wc(e,t,r){let i=e??t;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${r} must be a positive integer`);return i}function fb(e){if(e===void 0)return{...ke,include:[...ke.include],exclude:[...ke.exclude]};let t=dt(e,"native.snapshot");return{include:zf(t.include,"native.snapshot.include",ke.include),exclude:zf(t.exclude,"native.snapshot.exclude",ke.exclude),max_files:wc(t.max_files,ke.max_files,"native.snapshot.max_files"),max_total_bytes:wc(t.max_total_bytes,ke.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:wc(t.max_duration_ms,ke.max_duration_ms,"native.snapshot.max_duration_ms")}}function pb(e){if(e===void 0)return;let t=dt(e,"native.pending_root_move"),r=t.id,i=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof r!="string"||!/^[a-f0-9-]{8,}$/u.test(r))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=dt(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,f=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof f!="string"||!/^[a-f0-9]{64}$/u.test(f))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:f}}return{id:r,fromArtifactRoot:er(i),toArtifactRoot:er(n),stage:a,...o?{cleanup:o}:{}}}function hb(e){if(e===void 0)return;let t=dt(e,"native.finish");if(t.pull_request===void 0)return{};let r=dt(t.pull_request,"native.finish.pull_request");if(r.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(r.command)||r.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(r.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let i=r.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if($t.posix.isAbsolute(i[0])||$t.win32.isAbsolute(i[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=r.timeout_ms??ob;if(!Number.isSafeInteger(n)||n<1||n>Wf)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Wf}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function mb(e,t={}){let r=dt(e,"native"),i=r.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let n=r.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=r.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=r.max_verify_failures??yc;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=pb(r.pending_root_move),c=hb(r.finish);return{artifact_root:er(i),language:Uf(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:fb(r.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function vb(e){let t=dt(e,"classic"),r=t.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let i=t.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:Gf(t.artifact_layout),language:Uf(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n}}function gb(e){let r=dt(e,"hook").allow_paths??[];if(!Array.isArray(r))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(r.map((i,n)=>ya(i,`hook.allow_paths[${n}]`)))]}}function wb(e){if(e===void 0)return{...Ri};let t=dt(e,"memory"),r=t.learning??Ri.learning,i=t.retrieval??Ri.retrieval;if(typeof r!="boolean")throw new Error("memory.learning must be true or false");if(typeof i!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:r,retrieval:i}}function kc(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function yb(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||r.includes("\\")||r.includes("\0")||$t.posix.isAbsolute(r)||$t.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!r.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(r.length>Ff)throw new Error(`${t} exceeds ${Ff} characters`);let i=0;for(let n=0;n<r.length;n+=1)r[n]==="?"?i+=1:r[n]==="*"&&(i+=1,r[n+1]==="*"&&(n+=1));if(i>qf)throw new Error(`${t} contains more than ${qf} wildcard tokens`);return r}function Nb(e){let r=kc(e,"knowledge.local").include??[];if(!Array.isArray(r))throw new Error("knowledge.local.include must be an array");return{include:[...new Set(r.map((i,n)=>yb(i,`knowledge.local.include[${n}]`)))]}}function bb(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let r=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),i=r==="localhost"||r==="127.0.0.1"||r==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&i))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function kb(e){let t=kc(e,"knowledge.remote"),r=bb(t.endpoint),i=t.token_env;if(i!==void 0&&(typeof i!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(i)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:r,...i===void 0?{}:{token_env:i},...n===void 0?{}:{scope:n},timeout_ms:a}}function Sb(e){if(e===void 0)return{...Nc};let t=kc(e,"knowledge"),r=t.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let i=t.local===void 0?void 0:Nb(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:kb(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:r,...i?{local:i}:{},remote:n}}function Eb(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function xb(e,t,r,i,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let f=e.workflows??[e.default_workflow];if(!Array.isArray(f)||f.length===0||f.some(d=>d!=="native"&&d!=="classic"))throw new Error("workflows must contain native and/or classic");let u=[...new Set(f)];if(!u.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(u.includes("native")&&!n)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:u,ambient_resume:o,...t?{hook:t}:{},memory:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function Cr(e,t={}){let r=(0,Ai.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${r.errors[0].message}`);let i=r.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=i,a=Eb(n.ambient_resume),o=n.hook===void 0?void 0:gb(n.hook),s=wb(n.memory),c=Sb(n.knowledge),l=n.native===void 0?void 0:mb(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),f=n.classic===void 0?void 0:vb(n.classic),u=xb(n,o,s,c,l,f,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:u,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...f?{classic:f}:{}}}function Kf(e){return{id:e.id,from_artifact_root:e.fromArtifactRoot,to_artifact_root:e.toArtifactRoot,stage:e.stage,...e.cleanup?{cleanup:{kind:e.cleanup.kind,state:e.cleanup.state,manifest_hash:e.cleanup.manifestHash}}:{}}}function Yf(e){let t=e.knowledge??{...Nc};return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,memory:e.memory??{...Ri},knowledge:{provider:t.provider,...t.local&&t.local.include.length>0?{local:{include:[...t.local.include]}}:{},...t.remote?{remote:{endpoint:t.remote.endpoint,timeout_ms:t.remote.timeout_ms,...t.remote.token_env===void 0?{}:{token_env:t.remote.token_env},...t.remote.scope===void 0?{}:{scope:t.remote.scope}}}:{}},...e.hook?{hook:{allow_paths:[...e.hook.allow_paths]}}:{},...e.native?{native:{artifact_root:e.native.artifact_root,language:e.native.language,clarification_mode:e.native.clarification_mode,archive_confirmation:e.native.archive_confirmation,max_verify_failures:e.native.max_verify_failures,...e.native.finish?.pull_request?{finish:{pull_request:{provider:e.native.finish.pull_request.provider,command:[...e.native.finish.pull_request.command],timeout_ms:e.native.finish.pull_request.timeout_ms}}}:{},...e.native.pending_root_move?{pending_root_move:Kf(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition}}:{}}}function be(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Ti(e,t){let r=Yf(t),i=Cr((0,Ai.stringify)(r)).config;if(!i)throw new Error("Unsupported Comet project schema");let n={...e,schema:i.schema,default_workflow:i.default_workflow,workflows:i.workflows,ambient_resume:i.ambient_resume};if(i.hook&&(n.hook={...be(e.hook),allow_paths:[...i.hook.allow_paths]}),i.memory){let a=be(e.memory);n.memory={...a,learning:i.memory.learning,retrieval:i.memory.retrieval}}if(i.knowledge){let a=be(e.knowledge),o={...a,provider:i.knowledge.provider};if(i.knowledge.local&&i.knowledge.local.include.length>0?o.local={...be(a.local),include:[...i.knowledge.local.include]}:delete o.local,i.knowledge.remote){let c={...be(a.remote),endpoint:i.knowledge.remote.endpoint,timeout_ms:i.knowledge.remote.timeout_ms,...i.knowledge.remote.token_env===void 0?{}:{token_env:i.knowledge.remote.token_env},...i.knowledge.remote.scope===void 0?{}:{scope:i.knowledge.remote.scope}};i.knowledge.remote.token_env===void 0&&delete c.token_env,i.knowledge.remote.scope===void 0&&delete c.scope,o.remote=c}else delete o.remote;n.knowledge=o}if(i.native){let a=be(e.native),o={...a,artifact_root:i.native.artifact_root,language:i.native.language,clarification_mode:i.native.clarification_mode,archive_confirmation:i.native.archive_confirmation,max_verify_failures:i.native.max_verify_failures};if(i.native.finish?.pull_request){let s=be(a.finish);o.finish={...s,pull_request:{...be(s.pull_request),provider:i.native.finish.pull_request.provider,command:[...i.native.finish.pull_request.command],timeout_ms:i.native.finish.pull_request.timeout_ms}}}else{let s={...be(a.finish)};delete s.pull_request,Object.keys(s).length>0?o.finish=s:delete o.finish}if(delete o.snapshot,i.native.pending_root_move){let s=be(a.pending_root_move),c=Kf(i.native.pending_root_move),l=be(s.cleanup),f=be(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...f}}:{}}}else delete o.pending_root_move;n.native=o}return i.classic&&(n.classic={...be(e.classic),artifact_layout:i.classic.artifact_layout,language:i.classic.language,context_compression:i.classic.context_compression,review_mode:i.classic.review_mode,auto_transition:i.classic.auto_transition}),n}function Na(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...Ri},knowledge:{...Nc},native:{artifact_root:er(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:yc,snapshot:{...ke,include:[...ke.include],exclude:[...ke.exclude]}}}}import{createHash as Pb}from"crypto";import{promises as Sa}from"fs";import Ot from"path";import{constants as ba,promises as tr}from"fs";var Be=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}};function Sc(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Xf(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function ji(e){return{dev:e.dev,ino:e.ino,birthtime:Sc(e)}}function ka(e,t){let r=ji(e),i=ji(t);return Ke(r,i)?M(r,i):M(r,i)&&Sc(e)===Sc(t)&&Xf(e)===Xf(t)&&e.size===t.size}async function Pr(e,t,r={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let i=r.label??"file",n=r.bigint===!0,a=await tr.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Be("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Be("too-large",`${i} exceeds ${t} bytes`);let o=await tr.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:ji(a)});let s=process.platform==="win32"?ba.O_RDONLY:ba.O_RDONLY|ba.O_NOFOLLOW|ba.O_NONBLOCK,c;try{c=await tr.open(e,s)}catch(l){throw l.code==="ELOOP"?new Be("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,f,u]=await Promise.all([c.stat({bigint:n}),tr.lstat(e,{bigint:n}),tr.realpath(e)]);if(!l.isFile()||!f.isFile()||f.isSymbolicLink()||u!==o||!ka(a,l)||!ka(a,f))throw new Be("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:u,identity:ji(l)}),await r.hooks?.afterOpen?.();let d=[],m=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let g=t+1-m,{bytesRead:y}=await c.read(v,0,Math.min(v.length,g),null);if(y===0)break;if(m+=y,m>t)throw new Be("too-large",`${i} exceeds ${t} bytes`);d.push(Buffer.from(v.subarray(0,y)))}await r.hooks?.beforeFinalCheck?.();let[h,p,w]=await Promise.all([c.stat({bigint:n}),tr.lstat(e,{bigint:n}),tr.realpath(e)]);if(!p.isFile()||p.isSymbolicLink()||w!==o||!ka(a,h)||!ka(a,p))throw new Be("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:w,identity:ji(h)}),{bytes:Buffer.concat(d,m),stat:h,realPath:w}}finally{await c.close()}}function Cb(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Ec(e,t){let r=Ot.relative(e,t);return r===""||!Ot.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ot.sep}`)}async function Qf(e,t){let r=Ot.resolve(e),i=await Sa.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return Sa.realpath(r)}async function Zf(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=Ot.join(n,r[a]);let o;try{o=await Sa.lstat(n)}catch(f){if(Cb(f))return{exists:!1,kind:"missing"};throw f}let s=Ot.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${i.label} crosses a symbolic link or junction at ${s}`);let c=a===r.length-1;if(!c&&!o.isDirectory())throw new Error(`${i.label} ancestor ${s} must be a real directory`);if(c&&(i.expected==="file"&&!o.isFile()||i.expected==="directory"&&!o.isDirectory()||i.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${i.label} must be a real ${i.expected}`);let l=await Sa.realpath(n);if(!Ec(t,l))throw new Error(`${i.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function Rr(e,t,r){let i=ya(t,r.label),n=Ot.resolve(e),a=await Qf(n,r.label),o=i.split("/"),s=Ot.resolve(n,...o);if(!Ec(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await Zf(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function Ht(e,t,r,i){let n=await Rr(e,t,{label:i.label,expected:"file"});if(!n.exists){let o=new Error(`${i.label} does not exist`);throw o.code="ENOENT",o}let a=await Qf(n.projectRoot,i.label);return Pr(n.target,r,{...i,verify:async(o,s)=>{if(!Ec(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Zf(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var $i=".comet/config.yaml";function xc(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function Rb(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Ea(e,t={}){return(await Oi(e,t)).document}async function ep(e){try{return(await Ht(e,$i,_i,{label:$i})).bytes}catch(t){if(Rb(t))return null;throw t}}function tp(e){return e?{exists:!0,sha256:Pb("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function xa(e){return tp(await ep(e))}async function Oi(e,t={}){let r=await ep(e);return{document:r?Cr(r.toString("utf8"),t):null,identity:tp(r)}}async function Cc(e){return(await Ea(e))?.config??null}var cA=16*1024;async function Pc(e,t){if(!t)return;let r=await xa(e);if(!xc(r,t))throw new Error("Project config changed before commit; rerun the operation")}import{randomUUID as Tb}from"crypto";import{promises as te}from"fs";import Le from"path";function Ca(e,t){let r=Le.relative(e,t);return r===""||!Le.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Le.sep}`)}function jb(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Pa(e,t){return M({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function $b(e,t){return Pa(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function rp(e){let t=await te.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 te.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Ar(e){for(let t of e){let r=await te.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!jb(t,r)||await te.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function Ob(e,t,r){let[i,n]=await Promise.all([te.lstat(e),te.realpath(e),r?Ar(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!Pa(i,t)||r&&!Ca(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function Hb(e,t){let r=Le.resolve(e),i=Le.resolve(t);if(!Ca(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await rp(r)],a=Le.relative(r,i).split(Le.sep).filter(Boolean),o=r;for(let s of a){await Ar(n),o=Le.join(o,s);try{await te.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await rp(o);if(!Ca(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Ar(n),n}async function Db(e){let t;try{t=await te.open(e,"r"),await t.sync()}catch(r){let i=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw r}finally{await t?.close()}}async function Bb(e,t,r={}){let i=Le.dirname(e),n=r.containedRoot?await Hb(r.containedRoot,i):null;n||await te.mkdir(i,{recursive:!0});let a=Le.join(i,`.${Le.basename(e)}.${Tb()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await te.open(a,"wx"),s=await o.stat(),n){let[l,f]=await Promise.all([te.lstat(a),te.realpath(a)]);if(await Ar(n),!l.isFile()||l.isSymbolicLink()||!Pa(s,l)||!Ca(n[0].realPath,f))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),c=await o.stat(),!Pa(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Native atomic write temporary file was not written");if(c=await Ob(a,c,n),await r.beforeCommit?.(),n){await Ar(n);let l=await te.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!$b(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await te.link(a,e),await te.unlink(a)):await te.rename(a,e),await Db(i)}catch(l){if(await o?.close(),!n)await te.rm(a,{force:!0});else try{await Ar(n),await te.rm(a,{force:!0})}catch{}throw l}}async function Re(e,t,r={}){await Bb(e,t,r)}async function ye(e,t,r={}){await Re(e,JSON.stringify(t,null,2)+`
171
- `,r)}import{existsSync as ip,promises as rr}from"fs";import O from"path";import Lb from"os";var Di=".comet/config.yaml",Vb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function Rc(e){try{return await rr.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Mb(e){try{let t=await rr.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Ir(e,t){let r=O.relative(e,t);return r===""||!O.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${O.sep}`)}async function _r(e){let t=[],r=e;for(;!await Rc(r);){let n=O.dirname(r);if(n===r)break;t.push(O.basename(r)),r=n}let i=await rr.realpath(r);return O.resolve(i,...t.reverse())}async function Ac(e){try{return(await rr.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Ra(e){let t=O.resolve(e);try{(await rr.stat(t)).isDirectory()||(t=O.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=O.resolve(Lb.homedir());for(;;){if(!(t===i&&r!==i)){let o=O.join(t,...Di.split("/")),s=t===r||await Mb(o);if(await Rc(o)&&s)return t}if(await Rc(O.join(t,".git")))return t;let a=O.dirname(t);if(a===t)return r;t=a}}function Aa(e){return er(e)}async function Fb(e,t){let r=Aa(t),i=O.resolve(e,...r.split("/")),n=await rr.realpath(e),a=await _r(i);if(!Ir(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function Dt(e,t){let r=Aa(t),i=await Fb(e,r),n=O.join(i,"comet");if(await Ac(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([_r(i),_r(n)]);if(!Ir(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=O.resolve(e),c=O.join(s,".comet","runtime","native");if(await Ac(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,f]=await Promise.all([rr.realpath(s),_r(c)]);if(!Ir(l,f))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:O.join(e,...Di.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:O.join(n,"specs"),changesDir:O.join(n,"changes"),archiveDir:O.join(n,"archive"),runtimeDir:c,changesRuntimeDir:O.join(c,"changes"),locksDir:O.join(c,"locks"),transactionsDir:O.join(c,"transactions")}}function np(e){if(!Vb.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Ve(e,t){np(t);let r=O.join(e.changesRuntimeDir,t);if(!ue(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function _c(e,t){np(t);let r=O.join(e.changesDir,t,"runtime");if(!ue(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function Ye(e,t){let r=Ve(e,t);if(ip(r))return r;let i=_c(e,t);return ip(i)?i:r}function Xe(e,t){let r=O.resolve(t);if(ue(e.runtimeDir,r))return e.runtimeDir;if(ue(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function ue(e,t){return Ir(O.resolve(e),O.resolve(t))}async function J(e,t){let r=O.resolve(e),i=O.resolve(t);if(!Ir(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await Ac(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([_r(r),_r(i)]);if(!Ir(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}function Wb(e="docs",t="en"){return Na(e,t)}async function Ne(e){let t=(await Ea(e))?.config??null;return t?.native?t:null}async function _a(e){let t=await Ne(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 Ia(e,t,r={}){let i=await Oi(e,{allowPartialProject:!0}),n=Ti(i.document?.value??{},t),a=qb.join(e,...Di.split("/"));await Re(a,Ii(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await r.beforeCommit?.(),await Pc(e,i.identity)}})}async function ap(e){let t=await Ra(e.startPath),r=await Ne(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${Di} was not found`);if(r?.native.pending_root_move)throw new Error(`Native root move ${r.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let i=e.explicitArtifactRoot?Aa(e.explicitArtifactRoot):void 0;if(r&&i&&i!==r.native.artifact_root)throw new Error(`Configured Native artifact root is ${r.native.artifact_root}; refusing conflicting root ${i}`);let n=r??Wb(i??"docs"),a=await Dt(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}var Oa=Kr(kr(),1);import{promises as zb}from"node:fs";var Tr="comet.native.v4",Bi="comet.native.local-execution.v4";var Ta=["multi-session","single-session"];function Ic(){return{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}}}var Jb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Gb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Ub=/^A[1-9][0-9]*$/u,Kb=/^[a-f0-9]{64}$/u,Yb=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"]),$a=class extends Error{constructor(r,i){super(`Native state version conflict: expected ${r}, got ${i}`);this.expectedStateVersion=r;this.actualStateVersion=i;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};function de(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function fe(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function re(e,t,r){if(typeof e!="string"||!r?.empty&&e.length===0)throw new Error(`${t} must be ${r?.empty?"a string":"a non-empty string"}`);return e}function jc(e,t){return e===null?null:re(e,t)}function op(e,t){let r=re(e,t);if(!Kb.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function jr(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function q(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function Xb(e,t){return e===null?null:q(e,t,Number.MIN_SAFE_INTEGER)}function U(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Qe(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function Ha(e,t){return Qe(e,t,(r,i)=>re(r,`${t}[${i}]`))}function ir(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function $r(e,t){let r=re(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function $c(e,t,r=!1){let i=re(e,t);if(i.includes("\\")||i.startsWith("/")||/^[A-Za-z]:/u.test(i)||i.split("/").includes("..")||!r&&(i==="."||i.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return i}function Ae(e,t){let r=de(e,t);return fe(r,new Set(["text","truncated"]),t),{text:re(r.text,`${t}.text`,{empty:!0}),truncated:jr(r.truncated,`${t}.truncated`)}}function Qb(e,t){let r=`Native spec_changes[${t}]`,i=de(e,r);fe(i,new Set(["capability","operation","source"]),r);let n=re(i.capability,`${r}.capability`);if(!Gb.test(n))throw new Error(`${r}.capability is invalid`);let a=U(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:$c(i.source,`${r}.source`);if(a==="remove"&&o!==null)throw new Error(`${r} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${r} ${a} requires a source`);return{capability:n,operation:a,source:o}}function Zb(e){let t="Native workspace",r=de(e,t);fe(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=U(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=jc(r.change_branch,`${t}.change_branch`),a=jc(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:U(r.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(i==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(i==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(i!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:i,change_branch:n,target_branch:a,finish:o}}function ek(e){let t="Native loop",r=de(e,t);fe(r,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let i=Ha(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);ir(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:U(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:U(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:q(r.goal_cycle,`${t}.goal_cycle`,1),iteration:q(r.iteration,`${t}.iteration`),attempt:q(r.attempt,`${t}.attempt`),retry_epoch:q(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:q(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:q(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:q(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:jc(r.next_action,`${t}.next_action`)}}function tk(e,t){let r=`Native acceptance[${t}]`,i=de(e,r);fe(i,new Set(["id","source","text","result","reason"]),r);let n=re(i.id,`${r}.id`);if(!Ub.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:$c(i.source,`${r}.source`),text:re(i.text,`${r}.text`),result:U(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:Ae(i.reason,`${r}.reason`)}}function rk(e,t){let r=`Native builder_handoff.checks[${t}]`,i=de(e,r);return fe(i,new Set(["name","result","note"]),r),{name:Ae(i.name,`${r}.name`),result:U(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:Ae(i.note,`${r}.note`)}}function ik(e){let t="Native builder_handoff",r=de(e,t);fe(r,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let i=Ha(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);ir(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:de(r.review,`${t}.review`);return n&&fe(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:re(r.candidate_id,`${t}.candidate_id`),identity_provider:re(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:re(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:q(r.iteration,`${t}.iteration`,1),summary:Ae(r.summary,`${t}.summary`),addressed_acceptance_ids:i,checks:Qe(r.checks,`${t}.checks`,rk),checks_truncated:jr(r.checks_truncated,`${t}.checks_truncated`),known_limits:Qe(r.known_limits,`${t}.known_limits`,(a,o)=>Ae(a,`${t}.known_limits[${o}]`)),known_limits_truncated:jr(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:U(n.status,["passed"],`${t}.review.status`),summary:Ae(n.summary,`${t}.review.summary`),reviewer_execution_ref:re(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:$r(r.submitted_at,`${t}.submitted_at`)}}function nk(e,t){let r=`Native blockers[${t}]`,i=de(e,r);fe(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=Ha(i.acceptance_ids,`${r}.acceptance_ids`);return ir(n,`${r}.acceptance_ids`),{owner:U(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:Ae(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:U(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function ak(e,t){let r=`Native verification.checks[${t}]`,i=de(e,r);return fe(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:re(i.id,`${r}.id`),name:Ae(i.name,`${r}.name`),argv_display:Qe(i.argv_display,`${r}.argv_display`,(n,a)=>Ae(n,`${r}.argv_display[${a}]`)),argv_truncated:jr(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:$c(i.cwd_ref,`${r}.cwd_ref`,!0),status:U(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:Xb(i.exit_code,`${r}.exit_code`),duration_ms:q(i.duration_ms,`${r}.duration_ms`)}}function ok(e){let t="Native verification",r=de(e,t);fe(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=Qe(r.checks,`${t}.checks`,ak);ir(i.map(a=>a.id),`${t}.checks IDs`);let n=re(r.identity_provider,`${t}.identity_provider`);return{candidate_id:re(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:re(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:q(r.iteration,`${t}.iteration`,1),attempt:q(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":U(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:U(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:Ae(r.summary,`${t}.summary`),risks:Qe(r.risks,`${t}.risks`,(a,o)=>Ae(a,`${t}.risks[${o}]`)),risks_truncated:jr(r.risks_truncated,`${t}.risks_truncated`),completed_at:$r(r.completed_at,`${t}.completed_at`)}}function sp(e,t){let r=`Native history[${t}]`,i=de(e,r);fe(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=Ha(i.unresolved_ids,`${r}.unresolved_ids`);return ir(n,`${r}.unresolved_ids`),{goal_cycle:q(i.goal_cycle,`${r}.goal_cycle`,1),iteration:q(i.iteration,`${r}.iteration`),attempt:q(i.attempt,`${r}.attempt`),outcome:U(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:Ae(i.summary,`${r}.summary`),completed_at:$r(i.completed_at,`${r}.completed_at`)}}function sk(e){let t="Native history_overflow.outcome_counts",r=de(e,t),i=["pass","fail","blocked","execution-error","recovery"];return fe(r,new Set(i),t),{pass:q(r.pass,`${t}.pass`),fail:q(r.fail,`${t}.fail`),blocked:q(r.blocked,`${t}.blocked`),"execution-error":q(r["execution-error"],`${t}.execution-error`),recovery:q(r.recovery,`${t}.recovery`)}}function ck(e){let t="Native history_overflow",r=de(e,t);fe(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=q(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:$r(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:$r(r.last_dropped_at,`${t}.last_dropped_at`);if(i===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(i>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=sk(r.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==i)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:i,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function lk(e){let t=new Set(e.acceptance.map(r=>r.id));for(let r of e.loop.previous_unresolved_ids)if(!t.has(r))throw new Error(`Native loop references unknown acceptance ID ${r}`);for(let r of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(r))throw new Error(`Native builder handoff references unknown ID ${r}`);for(let r of e.blockers)for(let i of r.acceptance_ids)if(!t.has(i))throw new Error(`Native blocker references unknown ID ${i}`);if(e.builder_handoff){if(!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let i=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!i&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function uk(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let r=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(r!==null&&e.loop.stage!==r)throw new Error(`Native status ${e.status} requires loop stage ${r}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(i=>i.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(i=>i.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function C(e){let t=de(e,"Native portable state");if(fe(t,Yb,"Native portable state"),t.schema!==Tr)throw new Error(`Native portable state schema must be ${Tr}`);let r=re(t.name,"Native state name");if(!Jb.test(r))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let i=Qe(t.spec_changes,"Native spec_changes",Qb);ir(i.map(s=>s.capability),"Native spec change capabilities");let n=Qe(t.acceptance,"Native acceptance",tk);ir(n.map(s=>s.id),"Native acceptance IDs");let a=Qe(t.history,"Native history",sp);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Tr,name:r,language:U(t.language,["en","zh-CN"],"Native state language"),phase:U(t.phase,["shape","build","verify","archive"],"Native state phase"),status:U(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:q(t.state_version,"Native state_version",1),brief:"brief.md",...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:op(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:op(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:U(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:Zb(t.workspace),loop:ek(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:ik(t.builder_handoff),blockers:Qe(t.blockers,"Native blockers",nk),verification:t.verification===null?null:ok(t.verification),history:a,history_overflow:ck(t.history_overflow),verification_result:U(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:U(t.verification_report,["verification.md"],"Native verification_report"),archived:jr(t.archived,"Native archived"),created_at:$r(t.created_at,"Native created_at")};return lk(o),uk(o),o}function pe(e,t){let r=C(e),i=sp(t,r.history.length),n=[...r.history,i],a={...r.history_overflow,outcome_counts:{...r.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return C({...r,history:n,history_overflow:a})}function dk(e,t){let r=(0,Oa.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`${t} is invalid YAML: ${r.errors[0].message}`);return r.toJS({mapAsMap:!1})}async function Me(e){let t=await zb.readFile(e,"utf8");return C(dk(t,"Native portable state"))}async function Da(e,t,r={}){let i=C(t);await Re(e,(0,Oa.stringify)(i),r)}var ja=new Map;async function fk(e,t){let r=ja.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);ja.set(e,a),await r;try{return await t()}finally{i(),ja.get(e)===a&&ja.delete(e)}}async function Li(e){return fk(e.file,async()=>{let t=q(e.expectedStateVersion,"Native expected state version",1),r=C(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await Me(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new $a(t,i.state_version);return await Da(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Me(e.file);if(n.state_version!==t)throw new $a(t,n.state_version)}}),r})}import or from"node:path";import{randomUUID as aE}from"node:crypto";import{promises as sh}from"node:fs";import{promises as QS}from"fs";import ZS from"path";import{AsyncLocalStorage as pk}from"async_hooks";import{randomUUID as up}from"crypto";import{promises as _e}from"fs";import dp from"os";import ie from"path";var cp=16*1024,fp=".coordinator",hk=5e3,lp=new pk,Ba=new Map;function mk(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function vk(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let r=e;if(typeof r.id!="string"||r.id.length===0||typeof r.pid!="number"||!Number.isSafeInteger(r.pid)||r.pid<1||typeof r.hostname!="string"||r.hostname.length===0||typeof r.createdAt!="string"||r.createdAt.length===0||typeof r.operation!="string"||r.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return r}function pp(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 La(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Ke(r,i)?M(r,i):M(r,i)&&e.size===t.size}function Oc(e,t){return La(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function Ze(e){let t,r;try{let i=await Pr(e,cp,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof Be?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${cp} bytes: ${e}`,{cause:i}):i.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:i}):new Error(`Native lock changed while reading: ${e}`,{cause:i}):i}return{file:e,owner:vk(JSON.parse(t.toString("utf8")),e),identity:pp(r)}}async function gk(e){return(await Ze(e))?.owner??null}function hp(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==dp.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=Sk(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function wk(e,t){try{await _e.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await _e.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function Hc(e,t){let r=await Ze(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Oc(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await _e.mkdir(t,{recursive:!0});let i=ie.join(t,`${ie.basename(e.file)}.${e.owner.id}.${up()}.removed`);try{await _e.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await Ze(i);if(!n||n.owner.id!==e.owner.id||!La(n.identity,e.identity))throw await wk(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await _e.rm(i,{force:!0}),"removed"}function mp(e){return{id:up(),pid:process.pid,hostname:dp.hostname(),createdAt:new Date().toISOString(),operation:e}}async function vp(e,t){let r;try{r=await _e.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await gk(e);throw new Error(`Native lock is already held: ${e}${o?` by pid ${o.pid} for ${o.operation}`:""}`,{cause:a})}throw a}let i;try{await r.writeFile(JSON.stringify(t,null,2)+`
172
- `,"utf8"),await r.sync(),i=pp(await r.stat({bigint:!0}))}finally{await r.close()}let n=await Ze(e);if(!i||!n||n.owner.id!==t.id||!La(n.identity,i))throw new Error(`Native lock changed after write: ${e}`);return n.identity}async function yk(e,t){let r=await J(e.runtimeDir,e.locksDir);await _e.mkdir(r,{recursive:!0});let i=await J(e.runtimeDir,ie.join(r,fp));await _e.mkdir(i,{recursive:!0});let n=mp(t),a=ie.join(i,`.${n.id}.tmp`),o=ie.join(i,`${n.id}.claim`);try{let s=await vp(a,n);await _e.rename(a,o);let c=await Ze(o);if(!c||!La(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:r,owner:n,identity:c.identity}}finally{await _e.rm(a,{force:!0})}}async function Nk(e){let t=ie.dirname(e.file),r=!1,i=ie.basename(e.file);for(let n of await _e.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=ie.join(t,n.name);if(ie.resolve(a)!==ie.resolve(e.file))try{let o=await Ze(a),s=hp(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Hc(o,t);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function gp(e){let t=await Ze(e.file);if(t){if(t.owner.id!==e.owner.id||!Oc(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await Hc(t,ie.dirname(e.file))}}async function bk(e,t){let r=Date.now()+hk;for(;;){let i=await yk(e,t);if(!await Nk(i))return i;if(await gp(i),Date.now()>=r)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function kk(e){let t=Ba.get(e)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=t.then(()=>i);return Ba.set(e,n),await t,()=>{r(),Ba.get(e)===n&&Ba.delete(e)}}async function Dc(e,t,r){let i=ie.resolve(e.locksDir),n=lp.getStore();if(n?.has(i))return r();let a=await kk(i);try{let o=await bk(e,t),s=new Map(n??[]);return s.set(i,o),await lp.run(s,async()=>{try{return await r()}finally{await gp(o)}})}finally{a()}}async function wp(e,t,r){let i=[...new Map(e.map(a=>[ie.resolve(a.locksDir),a])).values()].sort((a,o)=>ie.resolve(a.locksDir).localeCompare(ie.resolve(o.locksDir))),n=async a=>{let o=i[a];return o?Dc(o,t,()=>n(a+1)):r()};return n(0)}async function Va(e,t,r){return Dc(e,`acquire ${t}`,async()=>{let i=await J(e.runtimeDir,e.locksDir);await _e.mkdir(i,{recursive:!0});let n=await J(e.runtimeDir,ie.join(i,mk(t))),a=mp(r),o=await vp(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:i,owner:a,identity:o}})}async function Ma(e){await Ze(e.file)&&await Dc({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${ie.basename(e.file)}`,async()=>{let t=await Ze(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Oc(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let r=ie.join(e.locksDir,fp);await Hc(t,r)})}function Sk(e){try{return process.kill(e,0),!0}catch(t){let r=t.code;return r==="ESRCH"?!1:r==="EPERM"?!0:null}}async function yp(e){return hp(await Ze(e))}import Zc from"node:path";import gS from"node:path";var Gc=Kr(kr(),1);import Dr from"path";var Bc={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:"验证预期"}},bp={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:"结论"}},kp={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:"结论"}},Sp=new Map,Np=new Map;for(let e of Object.keys(Bc)){for(let[t,r]of Object.entries(Bc[e]))Sp.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(bp[e]))Np.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(kp[e]))Np.set(r.toLocaleLowerCase("en-US"),t)}function Ek(e,t){return Bc[e][t]}function Lc(e,t){return bp[e][t]??kp[e][t]}function Vc(e){return Sp.get(e.trim().toLocaleLowerCase("en-US"))??null}function Fa(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(r=>`# ${Ek(e,r)}
170
+ `)}function pb(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||$t.posix.isAbsolute(r)||$t.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be a project-relative path`);if(r===".")return[];let i=r.replaceAll("\\","/").split("/");if(i.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(i.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return i}function er(e){let t=pb(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Gf(e,t="docs"){let r=e??t;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function ya(e,t,r=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim().replaceAll("\\","/");if(i.length===0||$t.posix.isAbsolute(i)||$t.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be relative to its declared path base`);let n=i.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!r&&/[*?]/u.test(i))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function dt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Uf(e,t,r){let i=e??t;if(i!=="en"&&i!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return i}function bc(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>ga)throw new Error(`${t} exceeds ${ga} characters`);let r=0;for(let i=0;i<e.length;i+=1)e[i]==="?"?r+=1:e[i]==="*"&&(r+=1,e[i+1]==="*"&&(i+=1));if(r>wa)throw new Error(`${t} contains more than ${wa} wildcard tokens`);return e}function zf(e,t,r){if(e===void 0)return[...r];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(i=>bc(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function wc(e,t,r){let i=e??t;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${r} must be a positive integer`);return i}function hb(e){if(e===void 0)return{...ke,include:[...ke.include],exclude:[...ke.exclude]};let t=dt(e,"native.snapshot");return{include:zf(t.include,"native.snapshot.include",ke.include),exclude:zf(t.exclude,"native.snapshot.exclude",ke.exclude),max_files:wc(t.max_files,ke.max_files,"native.snapshot.max_files"),max_total_bytes:wc(t.max_total_bytes,ke.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:wc(t.max_duration_ms,ke.max_duration_ms,"native.snapshot.max_duration_ms")}}function mb(e){if(e===void 0)return;let t=dt(e,"native.pending_root_move"),r=t.id,i=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof r!="string"||!/^[a-f0-9-]{8,}$/u.test(r))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=dt(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,f=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof f!="string"||!/^[a-f0-9]{64}$/u.test(f))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:f}}return{id:r,fromArtifactRoot:er(i),toArtifactRoot:er(n),stage:a,...o?{cleanup:o}:{}}}function vb(e){if(e===void 0)return;let t=dt(e,"native.finish");if(t.pull_request===void 0)return{};let r=dt(t.pull_request,"native.finish.pull_request");if(r.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(r.command)||r.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(r.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let i=r.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if($t.posix.isAbsolute(i[0])||$t.win32.isAbsolute(i[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=r.timeout_ms??cb;if(!Number.isSafeInteger(n)||n<1||n>Wf)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Wf}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function gb(e,t={}){let r=dt(e,"native"),i=r.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let n=r.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=r.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=r.max_verify_failures??yc;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=mb(r.pending_root_move),c=vb(r.finish);return{artifact_root:er(i),language:Uf(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:hb(r.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function wb(e){let t=dt(e,"classic"),r=t.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let i=t.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:Gf(t.artifact_layout),language:Uf(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n}}function yb(e){let r=dt(e,"hook").allow_paths??[];if(!Array.isArray(r))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(r.map((i,n)=>ya(i,`hook.allow_paths[${n}]`)))]}}function Nb(e){if(e===void 0)return{...Ri};let t=dt(e,"memory"),r=t.learning??Ri.learning,i=t.retrieval??Ri.retrieval;if(typeof r!="boolean")throw new Error("memory.learning must be true or false");if(typeof i!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:r,retrieval:i}}function kc(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function bb(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||r.includes("\\")||r.includes("\0")||$t.posix.isAbsolute(r)||$t.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!r.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(r.length>Ff)throw new Error(`${t} exceeds ${Ff} characters`);let i=0;for(let n=0;n<r.length;n+=1)r[n]==="?"?i+=1:r[n]==="*"&&(i+=1,r[n+1]==="*"&&(n+=1));if(i>qf)throw new Error(`${t} contains more than ${qf} wildcard tokens`);return r}function kb(e){let r=kc(e,"knowledge.local").include??[];if(!Array.isArray(r))throw new Error("knowledge.local.include must be an array");return{include:[...new Set(r.map((i,n)=>bb(i,`knowledge.local.include[${n}]`)))]}}function Sb(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let r=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),i=r==="localhost"||r==="127.0.0.1"||r==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&i))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function Eb(e){let t=kc(e,"knowledge.remote"),r=Sb(t.endpoint),i=t.token_env;if(i!==void 0&&(typeof i!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(i)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:r,...i===void 0?{}:{token_env:i},...n===void 0?{}:{scope:n},timeout_ms:a}}function xb(e){if(e===void 0)return{...Nc};let t=kc(e,"knowledge"),r=t.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let i=t.local===void 0?void 0:kb(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:Eb(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:r,...i?{local:i}:{},remote:n}}function Cb(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function Pb(e,t,r,i,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let f=e.workflows??[e.default_workflow];if(!Array.isArray(f)||f.length===0||f.some(d=>d!=="native"&&d!=="classic"))throw new Error("workflows must contain native and/or classic");let u=[...new Set(f)];if(!u.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(u.includes("native")&&!n)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:u,ambient_resume:o,...t?{hook:t}:{},memory:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function Cr(e,t={}){let r=(0,Ai.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${r.errors[0].message}`);let i=r.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=i,a=Cb(n.ambient_resume),o=n.hook===void 0?void 0:yb(n.hook),s=Nb(n.memory),c=xb(n.knowledge),l=n.native===void 0?void 0:gb(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),f=n.classic===void 0?void 0:wb(n.classic),u=Pb(n,o,s,c,l,f,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:u,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...f?{classic:f}:{}}}function Kf(e){return{id:e.id,from_artifact_root:e.fromArtifactRoot,to_artifact_root:e.toArtifactRoot,stage:e.stage,...e.cleanup?{cleanup:{kind:e.cleanup.kind,state:e.cleanup.state,manifest_hash:e.cleanup.manifestHash}}:{}}}function Yf(e){let t=e.knowledge??{...Nc};return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,memory:e.memory??{...Ri},knowledge:{provider:t.provider,...t.local&&t.local.include.length>0?{local:{include:[...t.local.include]}}:{},...t.remote?{remote:{endpoint:t.remote.endpoint,timeout_ms:t.remote.timeout_ms,...t.remote.token_env===void 0?{}:{token_env:t.remote.token_env},...t.remote.scope===void 0?{}:{scope:t.remote.scope}}}:{}},...e.hook?{hook:{allow_paths:[...e.hook.allow_paths]}}:{},...e.native?{native:{artifact_root:e.native.artifact_root,language:e.native.language,clarification_mode:e.native.clarification_mode,archive_confirmation:e.native.archive_confirmation,max_verify_failures:e.native.max_verify_failures,...e.native.finish?.pull_request?{finish:{pull_request:{provider:e.native.finish.pull_request.provider,command:[...e.native.finish.pull_request.command],timeout_ms:e.native.finish.pull_request.timeout_ms}}}:{},...e.native.pending_root_move?{pending_root_move:Kf(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition}}:{}}}function be(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Ti(e,t){let r=Yf(t),i=Cr((0,Ai.stringify)(r)).config;if(!i)throw new Error("Unsupported Comet project schema");let n={...e,schema:i.schema,default_workflow:i.default_workflow,workflows:i.workflows,ambient_resume:i.ambient_resume};if(i.hook&&(n.hook={...be(e.hook),allow_paths:[...i.hook.allow_paths]}),i.memory){let a=be(e.memory);n.memory={...a,learning:i.memory.learning,retrieval:i.memory.retrieval}}if(i.knowledge){let a=be(e.knowledge),o={...a,provider:i.knowledge.provider};if(i.knowledge.local&&i.knowledge.local.include.length>0?o.local={...be(a.local),include:[...i.knowledge.local.include]}:delete o.local,i.knowledge.remote){let c={...be(a.remote),endpoint:i.knowledge.remote.endpoint,timeout_ms:i.knowledge.remote.timeout_ms,...i.knowledge.remote.token_env===void 0?{}:{token_env:i.knowledge.remote.token_env},...i.knowledge.remote.scope===void 0?{}:{scope:i.knowledge.remote.scope}};i.knowledge.remote.token_env===void 0&&delete c.token_env,i.knowledge.remote.scope===void 0&&delete c.scope,o.remote=c}else delete o.remote;n.knowledge=o}if(i.native){let a=be(e.native),o={...a,artifact_root:i.native.artifact_root,language:i.native.language,clarification_mode:i.native.clarification_mode,archive_confirmation:i.native.archive_confirmation,max_verify_failures:i.native.max_verify_failures};if(i.native.finish?.pull_request){let s=be(a.finish);o.finish={...s,pull_request:{...be(s.pull_request),provider:i.native.finish.pull_request.provider,command:[...i.native.finish.pull_request.command],timeout_ms:i.native.finish.pull_request.timeout_ms}}}else{let s={...be(a.finish)};delete s.pull_request,Object.keys(s).length>0?o.finish=s:delete o.finish}if(delete o.snapshot,i.native.pending_root_move){let s=be(a.pending_root_move),c=Kf(i.native.pending_root_move),l=be(s.cleanup),f=be(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...f}}:{}}}else delete o.pending_root_move;n.native=o}return i.classic&&(n.classic={...be(e.classic),artifact_layout:i.classic.artifact_layout,language:i.classic.language,context_compression:i.classic.context_compression,review_mode:i.classic.review_mode,auto_transition:i.classic.auto_transition}),n}function Na(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...Ri},knowledge:{...Nc},native:{artifact_root:er(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:yc,snapshot:{...ke,include:[...ke.include],exclude:[...ke.exclude]}}}}import{createHash as Ab}from"crypto";import{promises as Sa}from"fs";import Ot from"path";import{constants as ba,promises as tr}from"fs";var Be=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}};function Sc(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Xf(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function ji(e){return{dev:e.dev,ino:e.ino,birthtime:Sc(e)}}function ka(e,t){let r=ji(e),i=ji(t);return Ke(r,i)?M(r,i):M(r,i)&&Sc(e)===Sc(t)&&Xf(e)===Xf(t)&&e.size===t.size}async function Pr(e,t,r={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let i=r.label??"file",n=r.bigint===!0,a=await tr.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Be("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Be("too-large",`${i} exceeds ${t} bytes`);let o=await tr.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:ji(a)});let s=process.platform==="win32"?ba.O_RDONLY:ba.O_RDONLY|ba.O_NOFOLLOW|ba.O_NONBLOCK,c;try{c=await tr.open(e,s)}catch(l){throw l.code==="ELOOP"?new Be("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,f,u]=await Promise.all([c.stat({bigint:n}),tr.lstat(e,{bigint:n}),tr.realpath(e)]);if(!l.isFile()||!f.isFile()||f.isSymbolicLink()||u!==o||!ka(a,l)||!ka(a,f))throw new Be("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:u,identity:ji(l)}),await r.hooks?.afterOpen?.();let d=[],m=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let g=t+1-m,{bytesRead:y}=await c.read(v,0,Math.min(v.length,g),null);if(y===0)break;if(m+=y,m>t)throw new Be("too-large",`${i} exceeds ${t} bytes`);d.push(Buffer.from(v.subarray(0,y)))}await r.hooks?.beforeFinalCheck?.();let[h,p,w]=await Promise.all([c.stat({bigint:n}),tr.lstat(e,{bigint:n}),tr.realpath(e)]);if(!p.isFile()||p.isSymbolicLink()||w!==o||!ka(a,h)||!ka(a,p))throw new Be("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:w,identity:ji(h)}),{bytes:Buffer.concat(d,m),stat:h,realPath:w}}finally{await c.close()}}function Rb(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Ec(e,t){let r=Ot.relative(e,t);return r===""||!Ot.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ot.sep}`)}async function Qf(e,t){let r=Ot.resolve(e),i=await Sa.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return Sa.realpath(r)}async function Zf(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=Ot.join(n,r[a]);let o;try{o=await Sa.lstat(n)}catch(f){if(Rb(f))return{exists:!1,kind:"missing"};throw f}let s=Ot.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${i.label} crosses a symbolic link or junction at ${s}`);let c=a===r.length-1;if(!c&&!o.isDirectory())throw new Error(`${i.label} ancestor ${s} must be a real directory`);if(c&&(i.expected==="file"&&!o.isFile()||i.expected==="directory"&&!o.isDirectory()||i.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${i.label} must be a real ${i.expected}`);let l=await Sa.realpath(n);if(!Ec(t,l))throw new Error(`${i.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function Rr(e,t,r){let i=ya(t,r.label),n=Ot.resolve(e),a=await Qf(n,r.label),o=i.split("/"),s=Ot.resolve(n,...o);if(!Ec(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await Zf(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function Ht(e,t,r,i){let n=await Rr(e,t,{label:i.label,expected:"file"});if(!n.exists){let o=new Error(`${i.label} does not exist`);throw o.code="ENOENT",o}let a=await Qf(n.projectRoot,i.label);return Pr(n.target,r,{...i,verify:async(o,s)=>{if(!Ec(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Zf(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var $i=".comet/config.yaml";function xc(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function _b(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Ea(e,t={}){return(await Oi(e,t)).document}async function ep(e){try{return(await Ht(e,$i,_i,{label:$i})).bytes}catch(t){if(_b(t))return null;throw t}}function tp(e){return e?{exists:!0,sha256:Ab("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function xa(e){return tp(await ep(e))}async function Oi(e,t={}){let r=await ep(e);return{document:r?Cr(r.toString("utf8"),t):null,identity:tp(r)}}async function Cc(e){return(await Ea(e))?.config??null}var lA=16*1024;async function Pc(e,t){if(!t)return;let r=await xa(e);if(!xc(r,t))throw new Error("Project config changed before commit; rerun the operation")}import{randomUUID as $b}from"crypto";import{promises as te}from"fs";import Le from"path";function Ca(e,t){let r=Le.relative(e,t);return r===""||!Le.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Le.sep}`)}function Ob(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Pa(e,t){return M({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function Hb(e,t){return Pa(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function rp(e){let t=await te.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 te.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Ar(e){for(let t of e){let r=await te.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!Ob(t,r)||await te.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function Db(e,t,r){let[i,n]=await Promise.all([te.lstat(e),te.realpath(e),r?Ar(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!Pa(i,t)||r&&!Ca(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function Bb(e,t){let r=Le.resolve(e),i=Le.resolve(t);if(!Ca(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await rp(r)],a=Le.relative(r,i).split(Le.sep).filter(Boolean),o=r;for(let s of a){await Ar(n),o=Le.join(o,s);try{await te.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await rp(o);if(!Ca(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Ar(n),n}async function Lb(e){let t;try{t=await te.open(e,"r"),await t.sync()}catch(r){let i=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw r}finally{await t?.close()}}async function Vb(e,t,r={}){let i=Le.dirname(e),n=r.containedRoot?await Bb(r.containedRoot,i):null;n||await te.mkdir(i,{recursive:!0});let a=Le.join(i,`.${Le.basename(e)}.${$b()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await te.open(a,"wx"),s=await o.stat(),n){let[l,f]=await Promise.all([te.lstat(a),te.realpath(a)]);if(await Ar(n),!l.isFile()||l.isSymbolicLink()||!Pa(s,l)||!Ca(n[0].realPath,f))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),c=await o.stat(),!Pa(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Native atomic write temporary file was not written");if(c=await Db(a,c,n),await r.beforeCommit?.(),n){await Ar(n);let l=await te.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!Hb(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await te.link(a,e),await te.unlink(a)):await te.rename(a,e),await Lb(i)}catch(l){if(await o?.close(),!n)await te.rm(a,{force:!0});else try{await Ar(n),await te.rm(a,{force:!0})}catch{}throw l}}async function Re(e,t,r={}){await Vb(e,t,r)}async function ye(e,t,r={}){await Re(e,JSON.stringify(t,null,2)+`
171
+ `,r)}import{existsSync as ip,promises as rr}from"fs";import O from"path";import Mb from"os";var Di=".comet/config.yaml",Fb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function Rc(e){try{return await rr.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function qb(e){try{let t=await rr.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Ir(e,t){let r=O.relative(e,t);return r===""||!O.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${O.sep}`)}async function _r(e){let t=[],r=e;for(;!await Rc(r);){let n=O.dirname(r);if(n===r)break;t.push(O.basename(r)),r=n}let i=await rr.realpath(r);return O.resolve(i,...t.reverse())}async function Ac(e){try{return(await rr.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Ra(e){let t=O.resolve(e);try{(await rr.stat(t)).isDirectory()||(t=O.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=O.resolve(Mb.homedir());for(;;){if(!(t===i&&r!==i)){let o=O.join(t,...Di.split("/")),s=t===r||await qb(o);if(await Rc(o)&&s)return t}if(await Rc(O.join(t,".git")))return t;let a=O.dirname(t);if(a===t)return r;t=a}}function Aa(e){return er(e)}async function Wb(e,t){let r=Aa(t),i=O.resolve(e,...r.split("/")),n=await rr.realpath(e),a=await _r(i);if(!Ir(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function Dt(e,t){let r=Aa(t),i=await Wb(e,r),n=O.join(i,"comet");if(await Ac(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([_r(i),_r(n)]);if(!Ir(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=O.resolve(e),c=O.join(s,".comet","runtime","native");if(await Ac(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,f]=await Promise.all([rr.realpath(s),_r(c)]);if(!Ir(l,f))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:O.join(e,...Di.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:O.join(n,"specs"),changesDir:O.join(n,"changes"),archiveDir:O.join(n,"archive"),runtimeDir:c,changesRuntimeDir:O.join(c,"changes"),locksDir:O.join(c,"locks"),transactionsDir:O.join(c,"transactions")}}function np(e){if(!Fb.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Ve(e,t){np(t);let r=O.join(e.changesRuntimeDir,t);if(!ue(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function _c(e,t){np(t);let r=O.join(e.changesDir,t,"runtime");if(!ue(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function Ye(e,t){let r=Ve(e,t);if(ip(r))return r;let i=_c(e,t);return ip(i)?i:r}function Xe(e,t){let r=O.resolve(t);if(ue(e.runtimeDir,r))return e.runtimeDir;if(ue(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function ue(e,t){return Ir(O.resolve(e),O.resolve(t))}async function J(e,t){let r=O.resolve(e),i=O.resolve(t);if(!Ir(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await Ac(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([_r(r),_r(i)]);if(!Ir(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}function Jb(e="docs",t="en"){return Na(e,t)}async function Ne(e){let t=(await Ea(e))?.config??null;return t?.native?t:null}async function _a(e){let t=await Ne(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 Ia(e,t,r={}){let i=await Oi(e,{allowPartialProject:!0}),n=Ti(i.document?.value??{},t),a=zb.join(e,...Di.split("/"));await Re(a,Ii(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await r.beforeCommit?.(),await Pc(e,i.identity)}})}async function ap(e){let t=await Ra(e.startPath),r=await Ne(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${Di} was not found`);if(r?.native.pending_root_move)throw new Error(`Native root move ${r.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let i=e.explicitArtifactRoot?Aa(e.explicitArtifactRoot):void 0;if(r&&i&&i!==r.native.artifact_root)throw new Error(`Configured Native artifact root is ${r.native.artifact_root}; refusing conflicting root ${i}`);let n=r??Jb(i??"docs"),a=await Dt(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}var Oa=Kr(kr(),1);import{promises as Gb}from"node:fs";var Tr="comet.native.v4",Bi="comet.native.local-execution.v4";var Ta=["multi-session","single-session"];function Ic(){return{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}}}var Ub=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Kb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Yb=/^A[1-9][0-9]*$/u,Xb=/^[a-f0-9]{64}$/u,Qb=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"]),$a=class extends Error{constructor(r,i){super(`Native state version conflict: expected ${r}, got ${i}`);this.expectedStateVersion=r;this.actualStateVersion=i;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};function de(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function fe(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function re(e,t,r){if(typeof e!="string"||!r?.empty&&e.length===0)throw new Error(`${t} must be ${r?.empty?"a string":"a non-empty string"}`);return e}function jc(e,t){return e===null?null:re(e,t)}function op(e,t){let r=re(e,t);if(!Xb.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function jr(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function q(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function Zb(e,t){return e===null?null:q(e,t,Number.MIN_SAFE_INTEGER)}function U(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Qe(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function Ha(e,t){return Qe(e,t,(r,i)=>re(r,`${t}[${i}]`))}function ir(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function $r(e,t){let r=re(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function $c(e,t,r=!1){let i=re(e,t);if(i.includes("\\")||i.startsWith("/")||/^[A-Za-z]:/u.test(i)||i.split("/").includes("..")||!r&&(i==="."||i.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return i}function Ae(e,t){let r=de(e,t);return fe(r,new Set(["text","truncated"]),t),{text:re(r.text,`${t}.text`,{empty:!0}),truncated:jr(r.truncated,`${t}.truncated`)}}function ek(e,t){let r=`Native spec_changes[${t}]`,i=de(e,r);fe(i,new Set(["capability","operation","source"]),r);let n=re(i.capability,`${r}.capability`);if(!Kb.test(n))throw new Error(`${r}.capability is invalid`);let a=U(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:$c(i.source,`${r}.source`);if(a==="remove"&&o!==null)throw new Error(`${r} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${r} ${a} requires a source`);return{capability:n,operation:a,source:o}}function tk(e){let t="Native workspace",r=de(e,t);fe(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=U(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=jc(r.change_branch,`${t}.change_branch`),a=jc(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:U(r.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(i==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(i==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(i!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:i,change_branch:n,target_branch:a,finish:o}}function rk(e){let t="Native loop",r=de(e,t);fe(r,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let i=Ha(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);ir(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:U(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:U(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:q(r.goal_cycle,`${t}.goal_cycle`,1),iteration:q(r.iteration,`${t}.iteration`),attempt:q(r.attempt,`${t}.attempt`),retry_epoch:q(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:q(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:q(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:q(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:jc(r.next_action,`${t}.next_action`)}}function ik(e,t){let r=`Native acceptance[${t}]`,i=de(e,r);fe(i,new Set(["id","source","text","result","reason"]),r);let n=re(i.id,`${r}.id`);if(!Yb.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:$c(i.source,`${r}.source`),text:re(i.text,`${r}.text`),result:U(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:Ae(i.reason,`${r}.reason`)}}function nk(e,t){let r=`Native builder_handoff.checks[${t}]`,i=de(e,r);return fe(i,new Set(["name","result","note"]),r),{name:Ae(i.name,`${r}.name`),result:U(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:Ae(i.note,`${r}.note`)}}function ak(e){let t="Native builder_handoff",r=de(e,t);fe(r,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let i=Ha(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);ir(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:de(r.review,`${t}.review`);return n&&fe(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:re(r.candidate_id,`${t}.candidate_id`),identity_provider:re(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:re(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:q(r.iteration,`${t}.iteration`,1),summary:Ae(r.summary,`${t}.summary`),addressed_acceptance_ids:i,checks:Qe(r.checks,`${t}.checks`,nk),checks_truncated:jr(r.checks_truncated,`${t}.checks_truncated`),known_limits:Qe(r.known_limits,`${t}.known_limits`,(a,o)=>Ae(a,`${t}.known_limits[${o}]`)),known_limits_truncated:jr(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:U(n.status,["passed"],`${t}.review.status`),summary:Ae(n.summary,`${t}.review.summary`),reviewer_execution_ref:re(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:$r(r.submitted_at,`${t}.submitted_at`)}}function ok(e,t){let r=`Native blockers[${t}]`,i=de(e,r);fe(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=Ha(i.acceptance_ids,`${r}.acceptance_ids`);return ir(n,`${r}.acceptance_ids`),{owner:U(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:Ae(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:U(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function sk(e,t){let r=`Native verification.checks[${t}]`,i=de(e,r);return fe(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:re(i.id,`${r}.id`),name:Ae(i.name,`${r}.name`),argv_display:Qe(i.argv_display,`${r}.argv_display`,(n,a)=>Ae(n,`${r}.argv_display[${a}]`)),argv_truncated:jr(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:$c(i.cwd_ref,`${r}.cwd_ref`,!0),status:U(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:Zb(i.exit_code,`${r}.exit_code`),duration_ms:q(i.duration_ms,`${r}.duration_ms`)}}function ck(e){let t="Native verification",r=de(e,t);fe(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=Qe(r.checks,`${t}.checks`,sk);ir(i.map(a=>a.id),`${t}.checks IDs`);let n=re(r.identity_provider,`${t}.identity_provider`);return{candidate_id:re(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:re(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:q(r.iteration,`${t}.iteration`,1),attempt:q(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":U(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:U(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:Ae(r.summary,`${t}.summary`),risks:Qe(r.risks,`${t}.risks`,(a,o)=>Ae(a,`${t}.risks[${o}]`)),risks_truncated:jr(r.risks_truncated,`${t}.risks_truncated`),completed_at:$r(r.completed_at,`${t}.completed_at`)}}function sp(e,t){let r=`Native history[${t}]`,i=de(e,r);fe(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=Ha(i.unresolved_ids,`${r}.unresolved_ids`);return ir(n,`${r}.unresolved_ids`),{goal_cycle:q(i.goal_cycle,`${r}.goal_cycle`,1),iteration:q(i.iteration,`${r}.iteration`),attempt:q(i.attempt,`${r}.attempt`),outcome:U(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:Ae(i.summary,`${r}.summary`),completed_at:$r(i.completed_at,`${r}.completed_at`)}}function lk(e){let t="Native history_overflow.outcome_counts",r=de(e,t),i=["pass","fail","blocked","execution-error","recovery"];return fe(r,new Set(i),t),{pass:q(r.pass,`${t}.pass`),fail:q(r.fail,`${t}.fail`),blocked:q(r.blocked,`${t}.blocked`),"execution-error":q(r["execution-error"],`${t}.execution-error`),recovery:q(r.recovery,`${t}.recovery`)}}function uk(e){let t="Native history_overflow",r=de(e,t);fe(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=q(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:$r(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:$r(r.last_dropped_at,`${t}.last_dropped_at`);if(i===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(i>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=lk(r.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==i)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:i,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function dk(e){let t=new Set(e.acceptance.map(r=>r.id));for(let r of e.loop.previous_unresolved_ids)if(!t.has(r))throw new Error(`Native loop references unknown acceptance ID ${r}`);for(let r of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(r))throw new Error(`Native builder handoff references unknown ID ${r}`);for(let r of e.blockers)for(let i of r.acceptance_ids)if(!t.has(i))throw new Error(`Native blocker references unknown ID ${i}`);if(e.builder_handoff){if(!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let i=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!i&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function fk(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let r=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(r!==null&&e.loop.stage!==r)throw new Error(`Native status ${e.status} requires loop stage ${r}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(i=>i.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(i=>i.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function C(e){let t=de(e,"Native portable state");if(fe(t,Qb,"Native portable state"),t.schema!==Tr)throw new Error(`Native portable state schema must be ${Tr}`);let r=re(t.name,"Native state name");if(!Ub.test(r))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let i=Qe(t.spec_changes,"Native spec_changes",ek);ir(i.map(s=>s.capability),"Native spec change capabilities");let n=Qe(t.acceptance,"Native acceptance",ik);ir(n.map(s=>s.id),"Native acceptance IDs");let a=Qe(t.history,"Native history",sp);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Tr,name:r,language:U(t.language,["en","zh-CN"],"Native state language"),phase:U(t.phase,["shape","build","verify","archive"],"Native state phase"),status:U(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:q(t.state_version,"Native state_version",1),brief:"brief.md",...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:op(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:op(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:U(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:tk(t.workspace),loop:rk(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:ak(t.builder_handoff),blockers:Qe(t.blockers,"Native blockers",ok),verification:t.verification===null?null:ck(t.verification),history:a,history_overflow:uk(t.history_overflow),verification_result:U(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:U(t.verification_report,["verification.md"],"Native verification_report"),archived:jr(t.archived,"Native archived"),created_at:$r(t.created_at,"Native created_at")};return dk(o),fk(o),o}function pe(e,t){let r=C(e),i=sp(t,r.history.length),n=[...r.history,i],a={...r.history_overflow,outcome_counts:{...r.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return C({...r,history:n,history_overflow:a})}function pk(e,t){let r=(0,Oa.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`${t} is invalid YAML: ${r.errors[0].message}`);return r.toJS({mapAsMap:!1})}async function Me(e){let t=await Gb.readFile(e,"utf8");return C(pk(t,"Native portable state"))}async function Da(e,t,r={}){let i=C(t);await Re(e,(0,Oa.stringify)(i),r)}var ja=new Map;async function hk(e,t){let r=ja.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);ja.set(e,a),await r;try{return await t()}finally{i(),ja.get(e)===a&&ja.delete(e)}}async function Li(e){return hk(e.file,async()=>{let t=q(e.expectedStateVersion,"Native expected state version",1),r=C(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await Me(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new $a(t,i.state_version);return await Da(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Me(e.file);if(n.state_version!==t)throw new $a(t,n.state_version)}}),r})}import or from"node:path";import{randomUUID as sE}from"node:crypto";import{promises as sh}from"node:fs";import{promises as eE}from"fs";import tE from"path";import{AsyncLocalStorage as mk}from"async_hooks";import{randomUUID as up}from"crypto";import{promises as _e}from"fs";import dp from"os";import ie from"path";var cp=16*1024,fp=".coordinator",vk=5e3,lp=new mk,Ba=new Map;function gk(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function wk(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let r=e;if(typeof r.id!="string"||r.id.length===0||typeof r.pid!="number"||!Number.isSafeInteger(r.pid)||r.pid<1||typeof r.hostname!="string"||r.hostname.length===0||typeof r.createdAt!="string"||r.createdAt.length===0||typeof r.operation!="string"||r.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return r}function pp(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 La(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Ke(r,i)?M(r,i):M(r,i)&&e.size===t.size}function Oc(e,t){return La(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function Ze(e){let t,r;try{let i=await Pr(e,cp,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof Be?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${cp} bytes: ${e}`,{cause:i}):i.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:i}):new Error(`Native lock changed while reading: ${e}`,{cause:i}):i}return{file:e,owner:wk(JSON.parse(t.toString("utf8")),e),identity:pp(r)}}async function yk(e){return(await Ze(e))?.owner??null}function hp(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==dp.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=xk(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function Nk(e,t){try{await _e.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await _e.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function Hc(e,t){let r=await Ze(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Oc(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await _e.mkdir(t,{recursive:!0});let i=ie.join(t,`${ie.basename(e.file)}.${e.owner.id}.${up()}.removed`);try{await _e.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await Ze(i);if(!n||n.owner.id!==e.owner.id||!La(n.identity,e.identity))throw await Nk(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await _e.rm(i,{force:!0}),"removed"}function mp(e){return{id:up(),pid:process.pid,hostname:dp.hostname(),createdAt:new Date().toISOString(),operation:e}}async function vp(e,t){let r;try{r=await _e.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await yk(e);throw new Error(`Native lock is already held: ${e}${o?` by pid ${o.pid} for ${o.operation}`:""}`,{cause:a})}throw a}let i;try{await r.writeFile(JSON.stringify(t,null,2)+`
172
+ `,"utf8"),await r.sync(),i=pp(await r.stat({bigint:!0}))}finally{await r.close()}let n=await Ze(e);if(!i||!n||n.owner.id!==t.id||!La(n.identity,i))throw new Error(`Native lock changed after write: ${e}`);return n.identity}async function bk(e,t){let r=await J(e.runtimeDir,e.locksDir);await _e.mkdir(r,{recursive:!0});let i=await J(e.runtimeDir,ie.join(r,fp));await _e.mkdir(i,{recursive:!0});let n=mp(t),a=ie.join(i,`.${n.id}.tmp`),o=ie.join(i,`${n.id}.claim`);try{let s=await vp(a,n);await _e.rename(a,o);let c=await Ze(o);if(!c||!La(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:r,owner:n,identity:c.identity}}finally{await _e.rm(a,{force:!0})}}async function kk(e){let t=ie.dirname(e.file),r=!1,i=ie.basename(e.file);for(let n of await _e.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=ie.join(t,n.name);if(ie.resolve(a)!==ie.resolve(e.file))try{let o=await Ze(a),s=hp(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Hc(o,t);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function gp(e){let t=await Ze(e.file);if(t){if(t.owner.id!==e.owner.id||!Oc(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await Hc(t,ie.dirname(e.file))}}async function Sk(e,t){let r=Date.now()+vk;for(;;){let i=await bk(e,t);if(!await kk(i))return i;if(await gp(i),Date.now()>=r)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function Ek(e){let t=Ba.get(e)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=t.then(()=>i);return Ba.set(e,n),await t,()=>{r(),Ba.get(e)===n&&Ba.delete(e)}}async function Dc(e,t,r){let i=ie.resolve(e.locksDir),n=lp.getStore();if(n?.has(i))return r();let a=await Ek(i);try{let o=await Sk(e,t),s=new Map(n??[]);return s.set(i,o),await lp.run(s,async()=>{try{return await r()}finally{await gp(o)}})}finally{a()}}async function wp(e,t,r){let i=[...new Map(e.map(a=>[ie.resolve(a.locksDir),a])).values()].sort((a,o)=>ie.resolve(a.locksDir).localeCompare(ie.resolve(o.locksDir))),n=async a=>{let o=i[a];return o?Dc(o,t,()=>n(a+1)):r()};return n(0)}async function Va(e,t,r){return Dc(e,`acquire ${t}`,async()=>{let i=await J(e.runtimeDir,e.locksDir);await _e.mkdir(i,{recursive:!0});let n=await J(e.runtimeDir,ie.join(i,gk(t))),a=mp(r),o=await vp(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:i,owner:a,identity:o}})}async function Ma(e){await Ze(e.file)&&await Dc({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${ie.basename(e.file)}`,async()=>{let t=await Ze(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Oc(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let r=ie.join(e.locksDir,fp);await Hc(t,r)})}function xk(e){try{return process.kill(e,0),!0}catch(t){let r=t.code;return r==="ESRCH"?!1:r==="EPERM"?!0:null}}async function yp(e){return hp(await Ze(e))}import Zc from"node:path";import yS from"node:path";var Gc=Kr(kr(),1);import Dr from"path";var Bc={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:"验证预期"}},bp={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:"结论"}},kp={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:"结论"}},Sp=new Map,Np=new Map;for(let e of Object.keys(Bc)){for(let[t,r]of Object.entries(Bc[e]))Sp.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(bp[e]))Np.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(kp[e]))Np.set(r.toLocaleLowerCase("en-US"),t)}function Ck(e,t){return Bc[e][t]}function Lc(e,t){return bp[e][t]??kp[e][t]}function Vc(e){return Sp.get(e.trim().toLocaleLowerCase("en-US"))??null}function Fa(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(r=>`# ${Ck(e,r)}
173
173
  `).join(`
174
- `)}function Fe(e,t,r){return e==="zh-CN"?r:t}import{createHash as xk}from"node:crypto";import{constants as qa,promises as qe}from"node:fs";import We from"node:path";function za(e,t){let r=We.relative(e,t);return r===""||!We.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${We.sep}`)}function Ck(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function Pk(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Rk(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Wa(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Mc(e,t){let r=await qe.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await qe.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function Ak(e,t,r){let i=We.resolve(e),n=We.resolve(t);if(!za(i,n))throw new Error(`${r} is outside its managed root`);let a=[await Mc(i,r)],o=i;for(let s of We.relative(i,n).split(We.sep).filter(Boolean)){await nr(a,r),o=We.join(o,s);let c=await Mc(o,r);if(!za(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await nr(a,r),a}async function nr(e,t){for(let r of e){let i=await qe.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!Pk(r,i)||await qe.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function _k(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function Or(e){let t=Ck(e.maxBytes),r=We.resolve(e.file),i=await Ak(e.root,We.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(f=>Mc(We.resolve(f),e.label)));await e.hooks?.afterParentChainCaptured?.(),await nr(i,e.label);let a=await qe.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=Rk(a),s=await qe.realpath(r);if(!za(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(f=>za(f.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?qa.O_RDONLY:qa.O_RDONLY|qa.O_NOFOLLOW|qa.O_NONBLOCK,l=await qe.open(r,c);try{let f=await l.stat();await e.hooks?.afterOpen?.();let[u,d]=await Promise.all([qe.lstat(r),qe.realpath(r)]);if(await nr(i,e.label),await nr(n,e.label),!f.isFile()||!u.isFile()||u.isSymbolicLink()||d!==s||!Wa(o,f)||!Wa(o,u))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let m=await _k(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,h,p]=await Promise.all([l.stat(),qe.lstat(r),qe.realpath(r)]);if(await nr(i,e.label),await nr(n,e.label),!h.isFile()||h.isSymbolicLink()||p!==s||!Wa(o,v)||!Wa(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:m,hash:xk("sha256").update(m).digest("hex"),size:m.length}}finally{await l.close()}}import{createHash as Ik}from"crypto";function Ie(e){return Ik("sha256").update(e).digest("hex")}var m_={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024};var v_=8*1024*1024;var g_=64*1024,w_=64*1024;var y_={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},N_={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};var b_=(1n<<256n)-1n;var Bk=Kr(kr(),1);var D_=4*1024*1024;var Lk=null;function Vk(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function Ep(e,t){return(...r)=>{let i=Lk;if(i===null)return t(...r);let n=Vk(`async:${e}`,r),a=i.entries.get(n);if(a)return a.value;let o=t(...r).catch(s=>{throw i.entries.delete(n),s});return i.entries.set(n,{value:o}),o}}var F_=Ep("hookWritePolicy",async e=>(await Cc(e))?.hook??{allow_paths:[]});var DI=256*1024;var YI={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};import Hr from"node:path";var Vi=/^[a-f0-9]{64}$/u,Cp=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,Fk=16*1024,dT=process.platform;function qk(e,t){let r=Hr.relative(e,t);return Hr.isAbsolute(r)||r===".."||r.startsWith(`..${Hr.sep}`)?null:r.replaceAll("\\","/")||"."}function Pp(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function Rp(e,t){if(e.length===0||Pp(e)||e.includes("\\")||Hr.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let r=Hr.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function Wk(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 Fc(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||Pp(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function zk(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Fc(e.changeBranch,"Native workspace change branch"),Fc(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 Jk(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,r=new Set(["provider","baseCommit","targetBranch","targetCommit"]),i=Object.keys(t).filter(n=>!r.has(n));if(i.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${i.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!Cp.test(t.baseCommit)||typeof t.targetCommit!="string"||!Cp.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");Fc(t.targetBranch,"Native workspace Git target branch")}function Gk(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,r=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),i=Object.keys(t).filter(o=>!r.has(o));if(i.length>0)throw new Error(`Native workspace identity has unknown field(s): ${i.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!Vi.test(String(t.projectRootId))||!Vi.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");Wk(t.capturedAt),Rp(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&&!Vi.test(String(t.projectRootPathId))||a&&!Vi.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Vi.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&Jk(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(zk(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 Uk(e,t){return Hr.join(Ye(e,t),"workspace.json")}function Kk(e,t){let r=Uk(e,t),i=Xe(e,r),n=qk(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:Rp(n,"Native workspace file ref")}}async function Yk(e,t){try{let r=Kk(e,t),i=await Y({root:r.root,ref:r.ref,maxBytes:Fk});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Mi(e,t){let r=await Yk(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(Gk(r),r)}var ft="comet.native.v3",et="comet.native.v2",tt="comet.native.v1";var Ap=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],Qk=new Set(Ap),_p=new Set([...Ap,"minimum_runtime_version","revision"]),Zk=new Set([..._p,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),eS=new Set(["capability","operation","source","base_hash"]),tS=new Set(["shape","build","verify","archive"]),rS=new Set(["implicit","confirmed"]),iS=new Set(["pending","pass","fail"]),ar="comet-state.yaml",Wc=/^[a-f0-9]{64}$/u,Ip=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,nS=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,zc=class extends Error{constructor(r,i){super(`Native change ${r} uses ${i}; run comet native doctor ${r} --repair before mutating it`);this.change=r;this.schema=i;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},Br=class extends Error{constructor(r,i){super(r!==ft||i===null?`Unsupported Native change schema ${r} for runtime protocol ${3}`:`Native change ${r} requires runtime protocol ${i}; current protocol is ${3}`);this.schema=r;this.minimumRuntimeVersion=i;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},Ja=class extends Error{constructor(r,i,n){super(`Native change ${r} revision conflict: expected ${i}, actual ${n}`);this.change=r;this.expectedRevision=i;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},Fi=class extends Error{constructor(r,i){super(`Native working directory already contains active change${i.length===1?"":"s"} ${i.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=r;this.activeChanges=i;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},Ga=class extends Error{constructor(r,i,n,a,o,s=null,c=null){super(`Native change ${r} baseline is incomplete (${i} omitted entr${i===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=r;this.omittedCount=i;this.omittedByReason=n;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},BT=Fa("en");function Wi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Tp(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Uc(e){if(!Ip.test(e))throw new Error(`Invalid Native change name: ${e}`)}function aS(e){if(!Ip.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function jp(e,t){if(e.length===0||Dr.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function oS(e,t){let r=Wi(e,`spec_changes[${t}]`);if(Tp(r,eS,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(aS(r.capability),r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`Invalid spec operation for ${r.capability}`);let i=r.source,n=r.base_hash;if(i!==void 0&&typeof i!="string")throw new Error(`Spec source for ${r.capability} must be a string`);if(typeof i=="string"&&jp(i,`Spec source for ${r.capability}`),r.operation==="create"){if(!i)throw new Error(`Create spec ${r.capability} requires source`);if(n!==null)throw new Error(`Create spec ${r.capability} requires null base_hash`)}else if(r.operation==="replace"){if(!i)throw new Error(`Replace spec ${r.capability} requires source`);if(typeof n!="string"||!Wc.test(n))throw new Error(`Replace spec ${r.capability} requires a SHA-256 base_hash`)}else{if(i!==void 0)throw new Error(`Remove spec ${r.capability} forbids source`);if(typeof n!="string"||!Wc.test(n))throw new Error(`Remove spec ${r.capability} requires a SHA-256 base_hash`)}return{capability:r.capability,operation:r.operation,...typeof i=="string"?{source:i}:{},base_hash:n}}function sS(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 Kc(e,t){if(Tp(e,t,ar),typeof e.name!="string")throw new Error("Native change name is required");if(Uc(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"||!tS.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&&!rS.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let r=e.spec_changes.map(oS),i=r.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(i.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(i)].join(", ")}`);if(typeof e.verification_result!="string"||!iS.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"&&jp(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!sS(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:r,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function zi(e){let t=Wi(e,ar);if(t.schema!==tt)throw new Error(`Expected ${tt}`);return{schema:tt,...Kc(t,Qk)}}function qi(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function qc(e,t,r){if(e===null)return null;let i=typeof e=="string"?nS.exec(e):null;if(!i||i[1]!==r)throw new Error(`${t} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return e}function cS(e){if(e==null)return null;if(typeof e!="string"||!Wc.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function lS(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 Ji(e){let t=Wi(e,ar);if(t.schema!==et)throw new Error(`Expected ${et}`);if(qi(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${et} minimum_runtime_version must be 2`);return{schema:et,minimum_runtime_version:2,revision:qi(t.revision,"Native v2 revision"),...Kc(t,_p)}}function Gi(e){let t=Wi(e,ar);if(t.schema!==ft){if(t.schema===tt||t.schema===et){let o=t.schema===tt?zi(t):Ji(t);throw new zc(o.name,o.schema)}throw new Br(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=qi(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new Br(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=qi(t.revision,"Native revision"),n=Kc(t,Zk),a=cS(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:ft,minimum_runtime_version:3,revision:i,verification_protocol:lS(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:qc(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:qc(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:qc(t.partial_allowance,"Native partial_allowance","allowances")}}function uS(e){let t=Wi(e,ar);if(t.schema===tt){let n=zi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${ft}`}}if(t.schema===et){let n=Ji(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${ft}`}}if(t.schema!==ft){let n=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new Br(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=qi(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new Br(t.schema,r).message};let i=Gi(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}function rt(e,t){Uc(t);let r=Dr.join(e.changesDir,t);if(!ue(e.changesDir,r))throw new Error("Native change path escaped");return r}async function dS(e,t=Dr.dirname(e)){let r=Dr.relative(t,e).split(Dr.sep).join("/"),i=await Y({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,Gc.parseDocument)(i.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function $p(e,t){let r=Dr.join(rt(e,t),ar);await J(e.nativeRoot,r);let i=uS(await dS(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}import Vp from"node:path";var fS="comet.native.acceptance.v1";var FT=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Ka=Object.freeze({maxCriteria:1024});function Dp(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 Op(e,t){let r=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!r)return t;let i=r[1][0];return t===null?{marker:i,length:r[1].length}:i===t.marker&&r[1].length>=t.length&&r[2].trim().length===0?null:t}function Hp(e){return e.includes("-->")||e.includes("--!>")}function*Ua(e){let t=null,r=!1,i=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
174
+ `)}function Fe(e,t,r){return e==="zh-CN"?r:t}import{createHash as Pk}from"node:crypto";import{constants as qa,promises as qe}from"node:fs";import We from"node:path";function za(e,t){let r=We.relative(e,t);return r===""||!We.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${We.sep}`)}function Rk(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function Ak(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function _k(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Wa(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Mc(e,t){let r=await qe.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await qe.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function Ik(e,t,r){let i=We.resolve(e),n=We.resolve(t);if(!za(i,n))throw new Error(`${r} is outside its managed root`);let a=[await Mc(i,r)],o=i;for(let s of We.relative(i,n).split(We.sep).filter(Boolean)){await nr(a,r),o=We.join(o,s);let c=await Mc(o,r);if(!za(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await nr(a,r),a}async function nr(e,t){for(let r of e){let i=await qe.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!Ak(r,i)||await qe.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function Tk(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function Or(e){let t=Rk(e.maxBytes),r=We.resolve(e.file),i=await Ik(e.root,We.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(f=>Mc(We.resolve(f),e.label)));await e.hooks?.afterParentChainCaptured?.(),await nr(i,e.label);let a=await qe.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=_k(a),s=await qe.realpath(r);if(!za(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(f=>za(f.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?qa.O_RDONLY:qa.O_RDONLY|qa.O_NOFOLLOW|qa.O_NONBLOCK,l=await qe.open(r,c);try{let f=await l.stat();await e.hooks?.afterOpen?.();let[u,d]=await Promise.all([qe.lstat(r),qe.realpath(r)]);if(await nr(i,e.label),await nr(n,e.label),!f.isFile()||!u.isFile()||u.isSymbolicLink()||d!==s||!Wa(o,f)||!Wa(o,u))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let m=await Tk(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,h,p]=await Promise.all([l.stat(),qe.lstat(r),qe.realpath(r)]);if(await nr(i,e.label),await nr(n,e.label),!h.isFile()||h.isSymbolicLink()||p!==s||!Wa(o,v)||!Wa(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:m,hash:Pk("sha256").update(m).digest("hex"),size:m.length}}finally{await l.close()}}import{createHash as jk}from"crypto";function Ie(e){return jk("sha256").update(e).digest("hex")}var v_={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024};var g_=8*1024*1024;var w_=64*1024,y_=64*1024;var N_={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},b_={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};var k_=(1n<<256n)-1n;var Vk=Kr(kr(),1);var B_=4*1024*1024;var Mk=null;function Fk(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function Ep(e,t){return(...r)=>{let i=Mk;if(i===null)return t(...r);let n=Fk(`async:${e}`,r),a=i.entries.get(n);if(a)return a.value;let o=t(...r).catch(s=>{throw i.entries.delete(n),s});return i.entries.set(n,{value:o}),o}}var q_=Ep("hookWritePolicy",async e=>(await Cc(e))?.hook??{allow_paths:[]});var BI=256*1024;var XI={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};import Hr from"node:path";var Vi=/^[a-f0-9]{64}$/u,Cp=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,Wk=16*1024,fT=process.platform;function zk(e,t){let r=Hr.relative(e,t);return Hr.isAbsolute(r)||r===".."||r.startsWith(`..${Hr.sep}`)?null:r.replaceAll("\\","/")||"."}function Pp(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function Rp(e,t){if(e.length===0||Pp(e)||e.includes("\\")||Hr.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let r=Hr.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function Jk(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 Fc(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||Pp(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function Gk(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Fc(e.changeBranch,"Native workspace change branch"),Fc(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 Uk(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,r=new Set(["provider","baseCommit","targetBranch","targetCommit"]),i=Object.keys(t).filter(n=>!r.has(n));if(i.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${i.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!Cp.test(t.baseCommit)||typeof t.targetCommit!="string"||!Cp.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");Fc(t.targetBranch,"Native workspace Git target branch")}function Kk(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,r=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),i=Object.keys(t).filter(o=>!r.has(o));if(i.length>0)throw new Error(`Native workspace identity has unknown field(s): ${i.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!Vi.test(String(t.projectRootId))||!Vi.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");Jk(t.capturedAt),Rp(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&&!Vi.test(String(t.projectRootPathId))||a&&!Vi.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Vi.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&Uk(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(Gk(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 Yk(e,t){return Hr.join(Ye(e,t),"workspace.json")}function Xk(e,t){let r=Yk(e,t),i=Xe(e,r),n=zk(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:Rp(n,"Native workspace file ref")}}async function Qk(e,t){try{let r=Xk(e,t),i=await Y({root:r.root,ref:r.ref,maxBytes:Wk});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Mi(e,t){let r=await Qk(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(Kk(r),r)}var ft="comet.native.v3",et="comet.native.v2",tt="comet.native.v1";var Ap=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],eS=new Set(Ap),_p=new Set([...Ap,"minimum_runtime_version","revision"]),tS=new Set([..._p,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),rS=new Set(["capability","operation","source","base_hash"]),iS=new Set(["shape","build","verify","archive"]),nS=new Set(["implicit","confirmed"]),aS=new Set(["pending","pass","fail"]),ar="comet-state.yaml",Wc=/^[a-f0-9]{64}$/u,Ip=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,oS=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,zc=class extends Error{constructor(r,i){super(`Native change ${r} uses ${i}; run comet native doctor ${r} --repair before mutating it`);this.change=r;this.schema=i;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},Br=class extends Error{constructor(r,i){super(r!==ft||i===null?`Unsupported Native change schema ${r} for runtime protocol ${3}`:`Native change ${r} requires runtime protocol ${i}; current protocol is ${3}`);this.schema=r;this.minimumRuntimeVersion=i;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},Ja=class extends Error{constructor(r,i,n){super(`Native change ${r} revision conflict: expected ${i}, actual ${n}`);this.change=r;this.expectedRevision=i;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},Fi=class extends Error{constructor(r,i){super(`Native working directory already contains active change${i.length===1?"":"s"} ${i.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=r;this.activeChanges=i;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},Ga=class extends Error{constructor(r,i,n,a,o,s=null,c=null){super(`Native change ${r} baseline is incomplete (${i} omitted entr${i===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=r;this.omittedCount=i;this.omittedByReason=n;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},LT=Fa("en");function Wi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Tp(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Uc(e){if(!Ip.test(e))throw new Error(`Invalid Native change name: ${e}`)}function sS(e){if(!Ip.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function jp(e,t){if(e.length===0||Dr.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function cS(e,t){let r=Wi(e,`spec_changes[${t}]`);if(Tp(r,rS,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(sS(r.capability),r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`Invalid spec operation for ${r.capability}`);let i=r.source,n=r.base_hash;if(i!==void 0&&typeof i!="string")throw new Error(`Spec source for ${r.capability} must be a string`);if(typeof i=="string"&&jp(i,`Spec source for ${r.capability}`),r.operation==="create"){if(!i)throw new Error(`Create spec ${r.capability} requires source`);if(n!==null)throw new Error(`Create spec ${r.capability} requires null base_hash`)}else if(r.operation==="replace"){if(!i)throw new Error(`Replace spec ${r.capability} requires source`);if(typeof n!="string"||!Wc.test(n))throw new Error(`Replace spec ${r.capability} requires a SHA-256 base_hash`)}else{if(i!==void 0)throw new Error(`Remove spec ${r.capability} forbids source`);if(typeof n!="string"||!Wc.test(n))throw new Error(`Remove spec ${r.capability} requires a SHA-256 base_hash`)}return{capability:r.capability,operation:r.operation,...typeof i=="string"?{source:i}:{},base_hash:n}}function lS(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 Kc(e,t){if(Tp(e,t,ar),typeof e.name!="string")throw new Error("Native change name is required");if(Uc(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"||!iS.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&&!nS.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let r=e.spec_changes.map(cS),i=r.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(i.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(i)].join(", ")}`);if(typeof e.verification_result!="string"||!aS.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"&&jp(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!lS(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:r,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function zi(e){let t=Wi(e,ar);if(t.schema!==tt)throw new Error(`Expected ${tt}`);return{schema:tt,...Kc(t,eS)}}function qi(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function qc(e,t,r){if(e===null)return null;let i=typeof e=="string"?oS.exec(e):null;if(!i||i[1]!==r)throw new Error(`${t} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return e}function uS(e){if(e==null)return null;if(typeof e!="string"||!Wc.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function dS(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 Ji(e){let t=Wi(e,ar);if(t.schema!==et)throw new Error(`Expected ${et}`);if(qi(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${et} minimum_runtime_version must be 2`);return{schema:et,minimum_runtime_version:2,revision:qi(t.revision,"Native v2 revision"),...Kc(t,_p)}}function Gi(e){let t=Wi(e,ar);if(t.schema!==ft){if(t.schema===tt||t.schema===et){let o=t.schema===tt?zi(t):Ji(t);throw new zc(o.name,o.schema)}throw new Br(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=qi(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new Br(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=qi(t.revision,"Native revision"),n=Kc(t,tS),a=uS(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:ft,minimum_runtime_version:3,revision:i,verification_protocol:dS(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:qc(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:qc(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:qc(t.partial_allowance,"Native partial_allowance","allowances")}}function fS(e){let t=Wi(e,ar);if(t.schema===tt){let n=zi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${ft}`}}if(t.schema===et){let n=Ji(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${ft}`}}if(t.schema!==ft){let n=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new Br(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=qi(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new Br(t.schema,r).message};let i=Gi(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}function rt(e,t){Uc(t);let r=Dr.join(e.changesDir,t);if(!ue(e.changesDir,r))throw new Error("Native change path escaped");return r}async function pS(e,t=Dr.dirname(e)){let r=Dr.relative(t,e).split(Dr.sep).join("/"),i=await Y({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,Gc.parseDocument)(i.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function $p(e,t){let r=Dr.join(rt(e,t),ar);await J(e.nativeRoot,r);let i=fS(await pS(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}import Vp from"node:path";var hS="comet.native.acceptance.v1";var qT=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Ka=Object.freeze({maxCriteria:1024});function Dp(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 Op(e,t){let r=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!r)return t;let i=r[1][0];return t===null?{marker:i,length:r[1].length}:i===t.marker&&r[1].length>=t.length&&r[2].trim().length===0?null:t}function Hp(e){return e.includes("-->")||e.includes("--!>")}function*Ua(e){let t=null,r=!1,i=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
175
175
  `),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
176
- `,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!r&&i===null,index:s},s+=1,t!==null)t=Op(l,t);else if(r)Hp(l)&&(r=!1);else if(i!==null)new RegExp(`</${i}\\s*>`,"iu").test(l)&&(i=null);else{let u=Op(l,null);if(u!==null)t=u;else{let d=l.trimStart();if(d.startsWith("<!--")&&!Hp(d))r=!0;else{let m=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(d);m&&n.has(m[1].toLowerCase())&&!d.startsWith("</")&&!d.endsWith("/>")&&!new RegExp(`</${m[1]}\\s*>`,"iu").test(d)&&(i=m[1])}}}if(c===-1)break;o=c+1}}function Ui(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function Bp(e,t,r,i=[],n="content-hash"){let a=Ui(r),o=t.replaceAll("\\","/").trim(),s=i.map(Ui);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-${X(fS,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function Lp(e,t,r="content-hash"){let i=new Set;for(let n of e){let a=r==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(i.has(a))throw new Error(`${t} contains duplicate acceptance criteria`);i.add(a)}return e}function pS(e){let t=null,r=null,i=0,n=0;for(let{line:a,body:o,index:s}of Ua(e)){n=s+1;let c=o?Dp(a):null;c?.level===1&&(Vc(c.text)==="acceptanceExamples"?(i+=1,i===1&&(t=s+1)):t!==null&&r===null&&(r=s))}if(i===0||t===null)return null;if(i!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:r??n}}function Yc(e,t="brief.md",r=Ka.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let n=pS(e);if(n===null)return[];let a=null;for(let{line:l,body:f,index:u}of Ua(e)){if(u<n.start||u>=n.end)continue;let d=f?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(d===null)continue;let m=d[1].length;a=a===null?m:Math.min(a,m)}let o=[],s=null,c=()=>{if(s!==null){if(o.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);o.push(s)}};for(let{line:l,body:f,index:u}of Ua(e)){if(u<n.start||u>=n.end)continue;let d=f?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;d&&d[1].length===a?(c(),s=[d[2]]):s!==null&&s.push(l)}return c(),Lp(o.map(l=>Bp("brief-example",t,l.join(`
176
+ `,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!r&&i===null,index:s},s+=1,t!==null)t=Op(l,t);else if(r)Hp(l)&&(r=!1);else if(i!==null)new RegExp(`</${i}\\s*>`,"iu").test(l)&&(i=null);else{let u=Op(l,null);if(u!==null)t=u;else{let d=l.trimStart();if(d.startsWith("<!--")&&!Hp(d))r=!0;else{let m=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(d);m&&n.has(m[1].toLowerCase())&&!d.startsWith("</")&&!d.endsWith("/>")&&!new RegExp(`</${m[1]}\\s*>`,"iu").test(d)&&(i=m[1])}}}if(c===-1)break;o=c+1}}function Ui(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function Bp(e,t,r,i=[],n="content-hash"){let a=Ui(r),o=t.replaceAll("\\","/").trim(),s=i.map(Ui);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-${X(hS,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function Lp(e,t,r="content-hash"){let i=new Set;for(let n of e){let a=r==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(i.has(a))throw new Error(`${t} contains duplicate acceptance criteria`);i.add(a)}return e}function mS(e){let t=null,r=null,i=0,n=0;for(let{line:a,body:o,index:s}of Ua(e)){n=s+1;let c=o?Dp(a):null;c?.level===1&&(Vc(c.text)==="acceptanceExamples"?(i+=1,i===1&&(t=s+1)):t!==null&&r===null&&(r=s))}if(i===0||t===null)return null;if(i!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:r??n}}function Yc(e,t="brief.md",r=Ka.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let n=mS(e);if(n===null)return[];let a=null;for(let{line:l,body:f,index:u}of Ua(e)){if(u<n.start||u>=n.end)continue;let d=f?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(d===null)continue;let m=d[1].length;a=a===null?m:Math.min(a,m)}let o=[],s=null,c=()=>{if(s!==null){if(o.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);o.push(s)}};for(let{line:l,body:f,index:u}of Ua(e)){if(u<n.start||u>=n.end)continue;let d=f?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;d&&d[1].length===a?(c(),s=[d[2]]):s!==null&&s.push(l)}return c(),Lp(o.map(l=>Bp("brief-example",t,l.join(`
177
177
  `),[],i)),"Brief",i)}function Xc(e,t="spec.md",r=Ka.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=()=>{if(o!==null){if(n.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);n.push(Bp("spec-scenario",t,[o.title,...o.body].join(`
178
- `),o.context,i)),o=null}};for(let{line:c,body:l}of Ua(e)){let f=l?Dp(c):null,u=f?/^Scenario\s*:\s*(.*)$/iu.exec(f.text):null;if(u){for(s();a.at(-1)&&a.at(-1).level>=f.level;)a.pop();let d=Ui(u[1]);if(d.length===0)throw new Error("Scenario title must not be empty");o={level:f.level,title:d,body:[],context:a.map(m=>m.text)}}else if(f){for(o!==null&&f.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f)}else o!==null&&l&&o.body.push(c)}return s(),Lp(n,"Specification",i)}var hS=/^A[1-9]\d*$/u;function Mp(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||Vp.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||Vp.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function mS(e,t){return e.localeCompare(t,"en")}function Ya(e){let t=Mp(e.briefSource??"brief.md","Native brief source"),r=[...e.specs??[]].sort((a,o)=>mS(a.capability,o.capability));if(new Set(r.map(a=>a.capability)).size!==r.length)throw new Error("Native acceptance sources contain duplicate capabilities");let i=Yc(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of r){let o=Mp(a.source,`Native spec source for ${a.capability}`);i.push(...Xc(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})))}let n=new Set;for(let a of i){a.text=Ui(a.text);let o=`${a.source}\0${a.text}`;if(n.has(o))throw new Error(`Native acceptance contains a duplicate criterion: ${a.text}`);n.add(o)}if(i.length===0)throw new Error("Native change must define at least one acceptance criterion");return i.map((a,o)=>({id:`A${o+1}`,source:a.source,text:a.text}))}function Fp(e){let t=e.map(({id:r})=>r);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let r=0;r<t.length;r+=1)if(!hS.test(t[r])||t[r]!==`A${r+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function qp(e,t){return e.length===t.length&&e.every((r,i)=>r.source===t[i]?.source&&r.text===t[i]?.text)}function vS(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function H(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(vS(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let r="",i=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(i+a>t)break;r+=n,i+=a}return{text:r,truncated:!0}}var Xa="comet.native.portable-migration.v1",wS=new Set(["schema","id","change","fromSchema","status","createdAt"]),yS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,NS=/^[a-z0-9][a-z0-9-]{7,127}$/u,bS=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),kS=new Set([tt,et,ft]);function SS(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ES(e,t){let r=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(r.valueOf()))throw new Error(`${t} must be a valid timestamp`);return r.toISOString()}function xS(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function CS(e){return e.schema===tt?zi(e):e.schema===et?Ji(e):Gi(e)}function PS(e){return gS.posix.normalize(e.replaceAll("\\","/"))}function RS(e){return e.spec_changes.map(t=>t.operation==="remove"?{capability:t.capability,operation:"remove",source:null}:{capability:t.capability,operation:t.operation==="replace"?"modify":"create",source:PS(t.source)})}function AS(e){return e==="shape"?"shape":"build"}function _S(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function IS(e,t,r){return e==="zh-CN"?`从旧版 ${t} ${r} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${r} state; prior Loop, verification results, and execution records were not inherited.`}function Wp(e){let t=CS(e.state);Fp(e.acceptance);let r=AS(t.phase),i=r==="shape"?0:1,n=ES(e.migratedAt??`${t.created_at}T00:00:00.000Z`,"Native portable migration time"),a=e.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return C({schema:Tr,name:t.name,language:t.language,phase:r,status:"active",state_version:1,brief:"brief.md",spec_changes:RS(t),workspace:e.workspace,loop:{stage:r==="shape"?"shape":"building",goal_cycle:1,iteration:i,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:_S(t.language,r)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:i,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:H(IS(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:Ic(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function Qc(e){let t=SS(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!wS.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==Xa)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!NS.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!yS.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!kS.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!bS.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Xa,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:xS(t.createdAt,"Native portable migration transaction createdAt")}}function zp(e){switch(Qc(e).status){case"prepared":return{action:"commit-portable-yaml",fromStatus:"prepared",nextStatus:"yaml-committed"};case"yaml-committed":return{action:"cleanup-legacy-runtime",fromStatus:"yaml-committed",nextStatus:"legacy-cleanup"};case"legacy-cleanup":return{action:"commit-transaction",fromStatus:"legacy-cleanup",nextStatus:"committed"};case"committed":return{action:"done",fromStatus:"committed",nextStatus:null}}}var Jp="comet.native.archive-transaction.v4",Gp="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",TS=new RegExp(`^portable-archive-(${Gp})\\.json$`,"u"),jS=new RegExp(`^portable-migration-(${Gp})\\.json$`,"u"),$S=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,OS=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,HS=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),DS=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),BS=new Set(["capability","operation","source","content"]),Up=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Kp(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Yp(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`);if(Object.keys(e).length!==t.size)throw new Error(`${r} fields are invalid`)}function LS(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=Kp(e,r);if(Yp(i,BS,r),typeof i.capability!="string"||!Up.test(i.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(i.operation)))throw new Error(`${r}.operation is invalid`);let n=i.operation;if(n==="remove"){if(i.source!==null||i.content!==null)throw new Error(`${r} remove requires source and content null`);return{capability:i.capability,operation:n,source:null,content:null}}if(typeof i.source!="string"||i.source.length===0||i.source.includes("\\")||i.source.startsWith("/")||/^[A-Za-z]:/u.test(i.source)||i.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${r}.${n} source is invalid`);if(typeof i.content!="string")throw new Error(`${r}.${n} content is invalid`);return{capability:i.capability,operation:n,source:i.source,content:i.content}}function VS(e){let t=Kp(e,"Native portable Archive transaction");if(Yp(t,DS,"Native portable Archive transaction"),t.schema!==Jp)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!$S.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Up.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"||!OS.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"||!HS.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let r=t.spec_changes.map(LS);if(new Set(r.map(({capability:n})=>n)).size!==r.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>r.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let i=new Date(t.created_at);if(Number.isNaN(i.valueOf())||i.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:Jp,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:r,created_at:t.created_at}}function Qa(e){let t=TS.exec(e);if(t)return{kind:"archive",change:t[1]};let r=jS.exec(e);return r?{kind:"migration",change:r[1]}:null}function Za(e,t){let r=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,i=Qa(r);if(!i||i.kind!==t.kind||i.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return Zc.join(e.transactionsDir,r)}async function el(e,t){let r=Qa(t);if(!r)return null;let i=await Y({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=Zc.join(e.transactionsDir,t);if(r.kind==="archive"){let s=VS(n);if(s.change!==r.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:r.change,file:a,journal:s}}let o=Qc(n);if(o.change!==r.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:r.change,file:a,journal:o}}async function eo(e,t){let r=Za(e,t);try{return await el(e,Zc.basename(r))}catch(i){if(i.code==="ENOENT")return null;throw i}}function Xp(e){return e.kind==="archive"||e.journal.status!=="committed"}import pt from"path";import{TextDecoder as FS}from"util";var qS=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),WS=new Set(["id","type","source","target","staged","backup"]),zS=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),JS=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var eh=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var GS=256*1024,pj=1024*1024,hj=16*1024;var mj=64*1024*1024;var US=new FS("utf-8",{fatal:!0});function ro(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function io(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function th(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function tl(e,t){if(typeof e!="string"||e.length===0||pt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function to(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function Qp(e,t){if(tl(e,t),e.includes("\\")||e!==pt.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function KS(e,t){let r=ro(e,`transaction operations[${t}]`);if(io(r,WS,`transaction operations[${t}]`),typeof r.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.id))throw new Error(`transaction operations[${t}].id is invalid`);if(r.type!=="write"&&r.type!=="remove"&&r.type!=="move")throw new Error(`transaction operation ${r.id} has an invalid type`);tl(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&tl(r[i],`transaction operation ${r.id} ${i}`);if(r.type==="write"){if(r.staged===void 0||r.source!==void 0)throw new Error(`write operation ${r.id} requires staged and forbids source`)}else if(r.type==="remove"){if(r.source!==void 0||r.staged!==void 0)throw new Error(`remove operation ${r.id} forbids source and staged`)}else if(r.source===void 0||r.staged!==void 0||r.backup!==void 0)throw new Error(`move operation ${r.id} requires source and forbids staged and backup`);return r}function rh(e){let t=ro(e,"Native Archive transaction journal");if(io(t,zS,"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"||!eh.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!th(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(to(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let r=t.operations.map((s,c)=>{let l=ro(s,`Archive transaction operations[${c}]`);if(io(l,JS,`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`);Qp(l.target,`Archive transaction operation ${l.id} target`);for(let f of["source","staged","backup"])l[f]!==void 0&&Qp(l[f],`Archive transaction operation ${l.id} ${f}`);if(l.expectedTargetHash!==null&&to(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(to(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`);to(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),i=r.map(s=>s.id);if(new Set(i).size!==i.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=r.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||r.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of r.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:r}}function YS(e){let t=ro(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return rh(t);if(io(t,qS,"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"||!eh.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!pt.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!pt.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!th(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let r=t.operations.map(KS),i=r.map(n=>n.id);if(new Set(i).size!==i.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:r}}function XS(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return pt.join(e.transactionsDir,t)}function ih(e,t){let r=XS(e,t);return{directory:r,journal:pt.join(r,"transaction.json"),events:pt.join(r,"events.jsonl"),staged:pt.join(r,"staged"),backups:pt.join(r,"backups")}}async function rl(e,t){let r=ih(e,t);return await Promise.all(Object.values(r).map(i=>J(e.runtimeDir,i))),r}async function il(e,t,r={}){let i=await rl(e,t),n=await Or({root:e.runtimeDir,file:i.journal,maxBytes:GS,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(US.decode(n.bytes)),o=YS(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function eE(e,t,r){let i;try{i=await QS.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await il(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of i)if(Qa(n.name))try{let a=await el(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(Xp(a))return!0}catch{return!0}return!1}async function tE(e,t){let r=Date.now()+5e3,i=ZS.join(e.locksDir,"root-move.lock");for(;;)try{return await Va(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await yp(i);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=r)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function x(e,t,r,i){let n=await tE(e,t);try{if(await _a(e.projectRoot),await eE(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{await Ma(n)}}import{promises as Ki}from"node:fs";import le from"node:path";var Lt=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};function nl(e,t){let r=le.normalize(e),i=le.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function oh(e,t){let r=le.relative(e,t);return r===""||!le.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${le.sep}`)}function nh(e){return JSON.stringify(e.native)}async function no(e,t){let r=await Ne(e);if(r&&t){if(nh(r)!==nh(t))throw new Error(`Native worktree configuration differs from the source project: ${le.join(e,".comet","config.yaml")}`);return!1}return!r&&t?(await Ia(e,t),!0):!1}async function rE(e,t){if(!oh(e,t))return!1;let i=`/${le.relative(e,t).replaceAll("\\","/").replace(/\/+$/u,"")}/`,n=I(e,["rev-parse","--git-common-dir"]),a=le.resolve(e,n),o=le.join(a,"info","exclude"),s="";try{s=await Ki.readFile(o,"utf8")}catch(l){if(l.code!=="ENOENT")throw l}if(s.split(/\r?\n/u).includes(i))return!1;await Ki.mkdir(le.dirname(o),{recursive:!0});let c=s.length===0||s.endsWith(`
178
+ `),o.context,i)),o=null}};for(let{line:c,body:l}of Ua(e)){let f=l?Dp(c):null,u=f?/^Scenario\s*:\s*(.*)$/iu.exec(f.text):null;if(u){for(s();a.at(-1)&&a.at(-1).level>=f.level;)a.pop();let d=Ui(u[1]);if(d.length===0)throw new Error("Scenario title must not be empty");o={level:f.level,title:d,body:[],context:a.map(m=>m.text)}}else if(f){for(o!==null&&f.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f)}else o!==null&&l&&o.body.push(c)}return s(),Lp(n,"Specification",i)}var vS=/^A[1-9]\d*$/u;function Mp(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||Vp.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||Vp.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function gS(e,t){return e.localeCompare(t,"en")}function Ya(e){let t=Mp(e.briefSource??"brief.md","Native brief source"),r=[...e.specs??[]].sort((a,o)=>gS(a.capability,o.capability));if(new Set(r.map(a=>a.capability)).size!==r.length)throw new Error("Native acceptance sources contain duplicate capabilities");let i=Yc(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of r){let o=Mp(a.source,`Native spec source for ${a.capability}`);i.push(...Xc(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})))}let n=new Set;for(let a of i){a.text=Ui(a.text);let o=`${a.source}\0${a.text}`;if(n.has(o))throw new Error(`Native acceptance contains a duplicate criterion: ${a.text}`);n.add(o)}if(i.length===0)throw new Error("Native change must define at least one acceptance criterion");return i.map((a,o)=>({id:`A${o+1}`,source:a.source,text:a.text}))}function Fp(e){let t=e.map(({id:r})=>r);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let r=0;r<t.length;r+=1)if(!vS.test(t[r])||t[r]!==`A${r+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function qp(e,t){return e.length===t.length&&e.every((r,i)=>r.source===t[i]?.source&&r.text===t[i]?.text)}function wS(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function H(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(wS(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let r="",i=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(i+a>t)break;r+=n,i+=a}return{text:r,truncated:!0}}var Xa="comet.native.portable-migration.v1",NS=new Set(["schema","id","change","fromSchema","status","createdAt"]),bS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,kS=/^[a-z0-9][a-z0-9-]{7,127}$/u,SS=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),ES=new Set([tt,et,ft]);function xS(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function CS(e,t){let r=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(r.valueOf()))throw new Error(`${t} must be a valid timestamp`);return r.toISOString()}function PS(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function RS(e){return e.schema===tt?zi(e):e.schema===et?Ji(e):Gi(e)}function AS(e){return yS.posix.normalize(e.replaceAll("\\","/"))}function _S(e){return e.spec_changes.map(t=>t.operation==="remove"?{capability:t.capability,operation:"remove",source:null}:{capability:t.capability,operation:t.operation==="replace"?"modify":"create",source:AS(t.source)})}function IS(e){return e==="shape"?"shape":"build"}function TS(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function jS(e,t,r){return e==="zh-CN"?`从旧版 ${t} ${r} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${r} state; prior Loop, verification results, and execution records were not inherited.`}function Wp(e){let t=RS(e.state);Fp(e.acceptance);let r=IS(t.phase),i=r==="shape"?0:1,n=CS(e.migratedAt??`${t.created_at}T00:00:00.000Z`,"Native portable migration time"),a=e.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return C({schema:Tr,name:t.name,language:t.language,phase:r,status:"active",state_version:1,brief:"brief.md",spec_changes:_S(t),workspace:e.workspace,loop:{stage:r==="shape"?"shape":"building",goal_cycle:1,iteration:i,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:TS(t.language,r)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:i,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:H(jS(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:Ic(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function Qc(e){let t=xS(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!NS.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==Xa)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!kS.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!bS.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!ES.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!SS.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Xa,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:PS(t.createdAt,"Native portable migration transaction createdAt")}}function zp(e){switch(Qc(e).status){case"prepared":return{action:"commit-portable-yaml",fromStatus:"prepared",nextStatus:"yaml-committed"};case"yaml-committed":return{action:"cleanup-legacy-runtime",fromStatus:"yaml-committed",nextStatus:"legacy-cleanup"};case"legacy-cleanup":return{action:"commit-transaction",fromStatus:"legacy-cleanup",nextStatus:"committed"};case"committed":return{action:"done",fromStatus:"committed",nextStatus:null}}}var Jp="comet.native.archive-transaction.v4",Gp="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",$S=new RegExp(`^portable-archive-(${Gp})\\.json$`,"u"),OS=new RegExp(`^portable-migration-(${Gp})\\.json$`,"u"),HS=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,DS=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,BS=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),LS=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),VS=new Set(["capability","operation","source","content"]),Up=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Kp(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Yp(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`);if(Object.keys(e).length!==t.size)throw new Error(`${r} fields are invalid`)}function MS(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=Kp(e,r);if(Yp(i,VS,r),typeof i.capability!="string"||!Up.test(i.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(i.operation)))throw new Error(`${r}.operation is invalid`);let n=i.operation;if(n==="remove"){if(i.source!==null||i.content!==null)throw new Error(`${r} remove requires source and content null`);return{capability:i.capability,operation:n,source:null,content:null}}if(typeof i.source!="string"||i.source.length===0||i.source.includes("\\")||i.source.startsWith("/")||/^[A-Za-z]:/u.test(i.source)||i.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${r}.${n} source is invalid`);if(typeof i.content!="string")throw new Error(`${r}.${n} content is invalid`);return{capability:i.capability,operation:n,source:i.source,content:i.content}}function FS(e){let t=Kp(e,"Native portable Archive transaction");if(Yp(t,LS,"Native portable Archive transaction"),t.schema!==Jp)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!HS.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Up.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"||!DS.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"||!BS.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let r=t.spec_changes.map(MS);if(new Set(r.map(({capability:n})=>n)).size!==r.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>r.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let i=new Date(t.created_at);if(Number.isNaN(i.valueOf())||i.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:Jp,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:r,created_at:t.created_at}}function Qa(e){let t=$S.exec(e);if(t)return{kind:"archive",change:t[1]};let r=OS.exec(e);return r?{kind:"migration",change:r[1]}:null}function Za(e,t){let r=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,i=Qa(r);if(!i||i.kind!==t.kind||i.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return Zc.join(e.transactionsDir,r)}async function el(e,t){let r=Qa(t);if(!r)return null;let i=await Y({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=Zc.join(e.transactionsDir,t);if(r.kind==="archive"){let s=FS(n);if(s.change!==r.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:r.change,file:a,journal:s}}let o=Qc(n);if(o.change!==r.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:r.change,file:a,journal:o}}async function eo(e,t){let r=Za(e,t);try{return await el(e,Zc.basename(r))}catch(i){if(i.code==="ENOENT")return null;throw i}}function Xp(e){return e.kind==="archive"||e.journal.status!=="committed"}import pt from"path";import{TextDecoder as WS}from"util";var zS=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),JS=new Set(["id","type","source","target","staged","backup"]),GS=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),US=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var eh=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var KS=256*1024,hj=1024*1024,mj=16*1024;var vj=64*1024*1024;var YS=new WS("utf-8",{fatal:!0});function ro(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function io(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function th(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function tl(e,t){if(typeof e!="string"||e.length===0||pt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function to(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function Qp(e,t){if(tl(e,t),e.includes("\\")||e!==pt.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function XS(e,t){let r=ro(e,`transaction operations[${t}]`);if(io(r,JS,`transaction operations[${t}]`),typeof r.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.id))throw new Error(`transaction operations[${t}].id is invalid`);if(r.type!=="write"&&r.type!=="remove"&&r.type!=="move")throw new Error(`transaction operation ${r.id} has an invalid type`);tl(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&tl(r[i],`transaction operation ${r.id} ${i}`);if(r.type==="write"){if(r.staged===void 0||r.source!==void 0)throw new Error(`write operation ${r.id} requires staged and forbids source`)}else if(r.type==="remove"){if(r.source!==void 0||r.staged!==void 0)throw new Error(`remove operation ${r.id} forbids source and staged`)}else if(r.source===void 0||r.staged!==void 0||r.backup!==void 0)throw new Error(`move operation ${r.id} requires source and forbids staged and backup`);return r}function rh(e){let t=ro(e,"Native Archive transaction journal");if(io(t,GS,"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"||!eh.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!th(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(to(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let r=t.operations.map((s,c)=>{let l=ro(s,`Archive transaction operations[${c}]`);if(io(l,US,`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`);Qp(l.target,`Archive transaction operation ${l.id} target`);for(let f of["source","staged","backup"])l[f]!==void 0&&Qp(l[f],`Archive transaction operation ${l.id} ${f}`);if(l.expectedTargetHash!==null&&to(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(to(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`);to(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),i=r.map(s=>s.id);if(new Set(i).size!==i.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=r.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||r.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of r.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:r}}function QS(e){let t=ro(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return rh(t);if(io(t,zS,"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"||!eh.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!pt.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!pt.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!th(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let r=t.operations.map(XS),i=r.map(n=>n.id);if(new Set(i).size!==i.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:r}}function ZS(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return pt.join(e.transactionsDir,t)}function ih(e,t){let r=ZS(e,t);return{directory:r,journal:pt.join(r,"transaction.json"),events:pt.join(r,"events.jsonl"),staged:pt.join(r,"staged"),backups:pt.join(r,"backups")}}async function rl(e,t){let r=ih(e,t);return await Promise.all(Object.values(r).map(i=>J(e.runtimeDir,i))),r}async function il(e,t,r={}){let i=await rl(e,t),n=await Or({root:e.runtimeDir,file:i.journal,maxBytes:KS,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(YS.decode(n.bytes)),o=QS(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function rE(e,t,r){let i;try{i=await eE.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await il(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of i)if(Qa(n.name))try{let a=await el(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(Xp(a))return!0}catch{return!0}return!1}async function iE(e,t){let r=Date.now()+5e3,i=tE.join(e.locksDir,"root-move.lock");for(;;)try{return await Va(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await yp(i);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=r)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function x(e,t,r,i){let n=await iE(e,t);try{if(await _a(e.projectRoot),await rE(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{await Ma(n)}}import{promises as Ki}from"node:fs";import le from"node:path";var Lt=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};function nl(e,t){let r=le.normalize(e),i=le.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function oh(e,t){let r=le.relative(e,t);return r===""||!le.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${le.sep}`)}function nh(e){return JSON.stringify(e.native)}async function no(e,t){let r=await Ne(e);if(r&&t){if(nh(r)!==nh(t))throw new Error(`Native worktree configuration differs from the source project: ${le.join(e,".comet","config.yaml")}`);return!1}return!r&&t?(await Ia(e,t),!0):!1}async function nE(e,t){if(!oh(e,t))return!1;let i=`/${le.relative(e,t).replaceAll("\\","/").replace(/\/+$/u,"")}/`,n=I(e,["rev-parse","--git-common-dir"]),a=le.resolve(e,n),o=le.join(a,"info","exclude"),s="";try{s=await Ki.readFile(o,"utf8")}catch(l){if(l.code!=="ENOENT")throw l}if(s.split(/\r?\n/u).includes(i))return!1;await Ki.mkdir(le.dirname(o),{recursive:!0});let c=s.length===0||s.endsWith(`
179
179
  `)?"":`
180
180
  `;return await Ki.appendFile(o,`${c}${i}
181
- `,"utf8"),!0}function iE(e,t,r){let i=le.resolve(e,r??le.join(".worktrees",t)),n=le.resolve(e,I(e,["rev-parse","--git-common-dir"]));if(oh(n,i))throw new Error("Native worktree path cannot be inside the Git common directory");if(Zt(e).some(a=>nl(a,i)))throw new Error(`Native worktree path is already registered: ${i}`);return i}async function nE(e){try{throw await Ki.lstat(e),new Error(`Native worktree path already exists: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t}}async function ah(e){try{return await Ki.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function al(e){let t=le.resolve(e.projectRoot);if(e.isolation==="current"){if(e.changeBranch||e.targetBranch||e.worktreePath)throw new Error("Native current isolation does not accept --change-branch, --target-branch, or --worktree-path");let i=z(t);if(i.isGitWorktree&&i.currentBranch===null)throw new Error("Native workspace binding requires a branch; detached HEAD is not supported");return{projectRoot:t,binding:{isolation:"current",changeBranch:i.currentBranch,targetBranch:i.currentBranch},preparation:{isolation:"current",projectRoot:t,changeBranch:i.currentBranch,targetBranch:i.currentBranch,worktreePath:null,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1}}}let r=await Dt(t,e.sourceConfig?.native.artifact_root??"docs");return wp([{runtimeDir:r.runtimeDir,locksDir:r.locksDir}],`prepare Native ${e.isolation} workspace`,async()=>{let i=z(t);if(!i.isGitWorktree||i.currentBranch===null||i.primaryWorktreeRoot===null||i.currentWorktreeRoot===null)throw new Error("Native branch and worktree isolation require an attached Git branch");let n=e.changeBranch??`comet/${e.name}`;hc(t,n);let a=i.currentBranch===n,o=e.targetBranch??(a?void 0:i.currentBranch);if(!o)throw new Error("Native isolated workspace already on its change branch requires --target-branch");if(hc(t,o),!Sr(t,o))throw new Error(`Native target branch is not a verified local branch: ${o}`);if(e.isolation==="branch"){if(e.worktreePath)throw new Error("--worktree-path is only valid with --isolation worktree");let m=!1;if(!a){if(!ut(t))throw new Error("Native branch isolation requires a clean current working directory");if(Sr(t,n))throw new Error(`Native change branch already exists: ${n}`);I(t,["switch","-c",n,o]),m=!0}let v;try{v=await no(t,e.sourceConfig)}catch(h){throw new Lt(`Native branch preparation is incomplete: ${h.message}`,{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:m,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:t,binding:{isolation:"branch",changeBranch:n,targetBranch:o},preparation:{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:m,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}if(a){if(!i.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree");let m=e.worktreePath?le.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(m&&!nl(m,i.currentWorktreeRoot))throw new Error(`Native worktree path ${m} does not match the current worktree ${i.currentWorktreeRoot}`);let v;try{v=await no(t,e.sourceConfig)}catch(h){throw new Lt(`Native worktree preparation is incomplete: ${h.message}`,{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:t,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}let s=ha(i.primaryWorktreeRoot),c=s.find(m=>m.branch===n);if(c&&await ah(c.root)){let m=e.worktreePath?le.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(m&&!nl(m,c.root))throw new Error(`Native worktree branch ${n} is already checked out at ${c.root}`);let v;try{v=await no(c.root,e.sourceConfig)}catch(h){throw new Lt(`Native worktree preparation is incomplete: ${h.message}`,{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:c.root,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}c&&!await ah(c.root)&&(I(i.primaryWorktreeRoot,["worktree","prune"]),s=ha(i.primaryWorktreeRoot));let l=Sr(t,n);if(s.some(m=>m.branch===n))throw new Error(`Native change branch ${n} is already registered to a worktree`);let f=iE(i.primaryWorktreeRoot,e.name,e.worktreePath);await nE(f);let u=await rE(i.primaryWorktreeRoot,f),d={isolation:"worktree",projectRoot:f,changeBranch:n,targetBranch:o,worktreePath:f,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:u,configInitialized:!1};try{I(i.primaryWorktreeRoot,l?["worktree","add",f,n]:["worktree","add","-b",n,f,o]),d.createdBranch=!l,d.createdWorktree=!0,d.configInitialized=await no(f,e.sourceConfig)}catch(m){throw new Lt(`Native worktree preparation is incomplete: ${m.message}`,d,{cause:m})}return{projectRoot:f,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:d}})}var ol="comet.native.supervisor.v2",oE=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function ch(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native Supervisor parent name: ${e}`);return`comet/supervisor/${e}/integration`}async function lh(e){let t=or.join(".worktrees",`${e.parent}-integration`);return al({projectRoot:e.projectRoot,name:`${e.parent}-integration`,isolation:"worktree",changeBranch:ch(e.parent),targetBranch:e.targetBranch,worktreePath:t,sourceConfig:e.sourceConfig})}async function sE(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.parent)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.child))throw new Error("Native Supervisor parent and child names are invalid");return al({projectRoot:e.projectRoot,name:`${e.parent}-${e.child}`,isolation:"worktree",changeBranch:`comet/supervisor/${e.parent}/${e.child}`,targetBranch:e.targetBranch,worktreePath:or.join(".worktrees",`${e.parent}-${e.child}`),sourceConfig:e.sourceConfig})}function cE(e,t){return or.join(Ve(e,t),"supervisor")}function Lr(e,t){return or.join(cE(e,t),"state.json")}function uh(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!==ol)throw new Error(`Native Supervisor state schema must be ${ol}`);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(Vt(t.integration.targetCommit,"Native Supervisor target commit"),Vt(t.integration.headCommit,"Native Supervisor integration head commit"),!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let r=new Set,i=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(r.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(r.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.projectRoot!==void 0&&n.projectRoot!==null&&(typeof n.projectRoot!="string"||n.projectRoot.length===0))throw new Error(`Native Supervisor child ${n.name} projectRoot is invalid`);for(let[a,o]of[["base",n.baseCommit],["candidate",n.candidateCommit],["verified",n.verifiedCommit],["integration",n.integrationCommit]])o!==null&&Vt(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(Vt(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),i.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(i.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.role==="builder"&&n.status!=="active"||n.task.role==="verifier"&&!["active","needs-reverify"].includes(n.status))throw new Error(`Native Supervisor child ${n.name} task status is invalid`)}}}async function W(e,t){try{let r=await sh.readFile(Lr(e,t),"utf8"),i=JSON.parse(r);return uh(i),i}catch(r){if(r.code==="ENOENT")return null;throw r}}async function ne(e,t){uh(t),await sh.mkdir(e.changesRuntimeDir,{recursive:!0}),await ye(Lr(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function Vt(e,t){if(!oE.test(e))throw new Error(`${t} must be a Git commit`)}function ze(e){return structuredClone(e)}function it(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function lE(e,t){for(let r of t.dependsOn){let i=e.children.find(({name:n})=>n===r);if(!i||i.status!=="integrated")throw new Error(`Native Supervisor child ${t.name} dependency ${r} is not integrated`)}}function uE(e){let t=new Set(e.children.map(({name:i})=>i)),r=[];for(;t.size>0;){let i=e.children.find(n=>t.has(n.name)&&n.dependsOn.every(a=>!t.has(a)));if(!i)throw new Error("Native Supervisor Child dependencies contain a cycle");r.push(i),t.delete(i.name)}return r}function sl(e){Vt(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:i})=>i)),r=e.contract.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.depends_on],status:i.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null}));for(let i of r)for(let n of i.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${i.name} depends on unknown child ${n}`);return{schema:ol,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:r,history:[],finalVerification:{status:"pending",summary:null}}}async function ao(e){let t=ch(e.parent),r=Er(e.paths.projectRoot,t);if(!r)return null;let i=Er(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=Zt(e.paths.projectRoot).map(o=>or.resolve(o)).find(o=>z(o).currentBranch===t);if(!n)return null;let a=sl({parent:e.parent,targetBranch:e.targetBranch,targetCommit:i,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(r!==i){for(let o of a.children)o.status=o.dependsOn.length===0?"blocked":"pending",o.blocker=o.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;a.integration.headCommit=r}return it(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function dh(e){let t=ze(e.state),r=new Map(e.contract.children.map(n=>[n.name,n])),i=new Map(t.children.map(n=>[n.name,n]));for(let n of t.children){let a=r.get(n.name);if(!a){if(n.status!=="archived")throw new Error(`Native Supervisor child ${n.name} cannot be removed before Archive`);continue}if((n.status==="integrated"||n.status==="archived")&&(a.summary!==n.summary||a.depends_on.join("\0")!==n.dependsOn.join("\0")))throw new Error(`Native Supervisor integrated child ${n.name} history is immutable`);n.summary=a.summary,n.dependsOn=[...a.depends_on]}for(let n of e.contract.children)i.has(n.name)||t.children.push({name:n.name,summary:n.summary,dependsOn:[...n.depends_on],status:n.depends_on.every(a=>t.children.some(({name:o,status:s})=>o===a&&s==="integrated"))?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null});return t.stateVersion+=1,t}function cl(e,t){if(!t.projectRoot.trim()||!t.runId.trim())throw new Error("Native Supervisor task projectRoot and runId are required");let r=ze(e),i=r.children.find(({name:o})=>o===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(i.task)throw new Error(`Native Supervisor child ${t.child} already has an active task`);let n;if(t.role==="builder"){if(i.status!=="ready")throw new Error(`Native Supervisor child ${t.child} is not ready for a Builder task`);lE(r,i),n=r.integration.headCommit,i.status="active"}else{if(i.status!=="active"&&i.status!=="needs-reverify"||!i.candidateCommit)throw new Error(`Native Supervisor child ${t.child} is not ready for a Verifier task`);n=i.candidateCommit}let a={...t,baseCommit:n};return i.projectRoot=t.projectRoot,i.task=a,i.blocker=null,it(r,{kind:"task-dispatched",child:i.name,runId:a.runId,summary:`${a.role} task dispatched`}),r.stateVersion+=1,{state:r,task:a}}function dE(e,t){let r=e.children.find(({name:i})=>i===t.child);if(!r?.task||r.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return structuredClone(r.task)}function fh(e,t){let r=dE(e,t),i=ze(e);return it(i,{kind:"task-reconnected",child:t.child,runId:t.runId,summary:"existing task reconnected"}),i.stateVersion+=1,{state:i,task:r}}function fE(e,t,r){let i=z(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor child worktree identity is not ${t}`);if(!ut(e))throw new Error(`Native Supervisor child worktree is not clean: ${e}`);let n=I(e,["rev-parse","HEAD"]);if(n===r)return;if(!(()=>{try{return I(e,["merge-base","--is-ancestor",n,r]),!0}catch{return!1}})())throw new Error(`Native Supervisor child worktree ${e} cannot be refreshed from integration HEAD`);if((()=>{try{return I(e,["merge-base","--is-ancestor",r,n]),!0}catch{return!1}})())throw new Error(`Native Supervisor child worktree ${e} contains unintegrated commits`);if(I(e,["merge","--ff-only",r]),I(e,["rev-parse","HEAD"])!==r)throw new Error("Native Supervisor child worktree did not reach integration HEAD")}function ll(e){if(!ut(e.integration.worktree))throw new Error("Native Supervisor integration worktree must be clean");let t=I(e.integration.worktree,["rev-parse","--show-toplevel"]);if(or.resolve(t)!==or.resolve(e.integration.worktree))throw new Error("Native Supervisor integration worktree identity is invalid");let r=I(e.integration.worktree,["branch","--show-current"]);if(r!==e.integration.branch)throw new Error(`Native Supervisor integration branch mismatch: expected ${e.integration.branch}, got ${r||"(detached)"}`);return I(e.integration.worktree,["rev-parse","HEAD"])}function pE(e,t,r){let i=z(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor Verifier worktree identity is not ${t}`);if(!ut(e))throw new Error(`Native Supervisor Verifier worktree is not clean: ${e}`);if(I(e,["rev-parse","HEAD"])!==r)throw new Error("Native Supervisor Verifier worktree is not at its candidate commit")}function ul(e,t){if(t.reason.trim().length===0)throw new Error("Native Supervisor cancellation reason is required");let r=ze(e),i=r.children.find(({name:n})=>n===t.child);if(!i?.task||i.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return i.task.role==="builder"?(i.status="ready",i.candidateCommit=null):i.status="needs-reverify",i.task=null,i.blocker=t.reason,it(r,{kind:"task-cancelled",child:t.child,runId:t.runId,summary:t.reason}),r.stateVersion+=1,r}function oo(e,t){if(t.reason.trim().length===0)throw new Error("Native Supervisor blocker reason is required");let r=ze(e),i=r.children.find(({name:n})=>n===t.child);if(!i?.task||i.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return i.blocker=t.reason,it(r,{kind:"task-blocked",child:t.child,runId:t.runId,summary:t.reason}),r.stateVersion+=1,r}async function ph(e){return x(e.paths,`dispatch Native Supervisor children ${e.parent}`,async()=>{let t=await W(e.paths,e.parent);if(!t)throw new Error(`Native Supervisor state is missing for ${e.parent}`);let r=e.maxParallel??2;if(!Number.isSafeInteger(r)||r<1)throw new Error("Native Supervisor maxParallel must be a positive integer");let i=t.children.filter(({task:l})=>l!==null).length,n=Math.max(0,r-i);if(n===0)return{state:t,tasks:[]};let a=await Ne(e.paths.projectRoot),o=t,s=[],c=!1;for(let l of t.children){if(s.length>=n)break;if(l.task!==null)continue;let f=l.status==="needs-reverify"&&l.candidateCommit!==null;if(l.status!=="ready"&&!f)continue;let u;try{u=await sE({projectRoot:e.paths.projectRoot,parent:t.parent,child:l.name,targetBranch:t.integration.branch,sourceConfig:a}),f?pE(u.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,l.candidateCommit):fE(u.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,t.integration.headCommit)}catch(m){let v=ze(o),h=v.children.find(({name:p})=>p===l.name);h&&(h.blocker=m.message,it(v,{kind:"task-blocked",child:l.name,runId:null,summary:h.blocker}),v.stateVersion+=1,o=v,c=!0);continue}let d=cl(o,{role:f?"verifier":"builder",child:l.name,projectRoot:u.projectRoot,runId:aE()});o=d.state,s.push(d.task)}return(s.length>0||c)&&await ne(e.paths,o),{state:o,tasks:s}})}function hh(e,t){Vt(t.candidateCommit,"Native Supervisor candidate commit");let r=ze(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(!i.task||i.task.role!=="builder"||i.task.runId!==t.runId)throw new Error(`Native Supervisor Builder result runId is not current for ${t.child}`);if(i.status!=="active")throw new Error(`Native Supervisor child ${t.child} is not active for Builder result`);return i.candidateCommit=t.candidateCommit,i.task=null,i.blocker=null,it(r,{kind:"builder-result",child:i.name,runId:t.runId,summary:"Builder candidate recorded"}),r.stateVersion+=1,r}function mh(e,t){if(t.evidence.summary.trim().length===0)throw new Error("Native Supervisor verification summary must not be empty");if(t.verdict==="pass"&&t.evidence.checks.length===0)throw new Error("Native Supervisor verification pass requires at least one check");let r=ze(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(!i.task||i.task.role!=="verifier"||i.task.runId!==t.runId)throw new Error(`Native Supervisor Verifier result runId is not current for ${t.child}`);if(i.status!=="active"&&i.status!=="needs-reverify"||!i.candidateCommit)throw new Error(`Native Supervisor child ${t.child} is not ready for Verifier result`);return i.verification={summary:t.evidence.summary,checks:[...t.evidence.checks]},i.task=null,t.verdict==="pass"?(i.status="verified",i.verifiedCommit=i.candidateCommit,i.blocker=null):(i.status="needs-reverify",i.blocker=t.evidence.summary),it(r,{kind:"verifier-result",child:i.name,runId:t.runId,summary:t.evidence.summary}),r.stateVersion+=1,r}function hE(e,t){Vt(t.integrationCommit,"Native Supervisor integration commit");let r=ze(e),i=r.children.find(({name:n})=>n===t.name);if(!i)throw new Error(`Native Supervisor child ${t.name} does not exist`);if(i.status!=="verified"||!i.verifiedCommit)throw new Error(`Native Supervisor child ${t.name} must be verified before integration`);if(t.checks.length===0||t.checks.some(({status:n})=>n!=="passed"))throw new Error(`Native Supervisor child ${t.name} integration checks are incomplete`);i.status="integrated",i.integrationCommit=t.integrationCommit,i.checks=structuredClone(t.checks),i.blocker=null,r.integration.headCommit=t.integrationCommit,it(r,{kind:"child-integrated",child:i.name,runId:null,summary:"Child integrated into the Supervisor branch"});for(let n of r.children)n.status==="pending"&&n.dependsOn.every(a=>r.children.some(({name:o,status:s})=>o===a&&s==="integrated"))&&(n.status="ready");return r.stateVersion+=1,r}async function vh(e){return x(e.paths,`integrate Native Supervisor child ${e.name}`,async()=>{let r=await W(e.paths,e.state.parent)??e.state;if(r.stateVersion!==e.state.stateVersion)throw new Error("Native Supervisor state changed before integration; reload status first");let i=r.children.find(({name:c})=>c===e.name);if(!i)throw new Error(`Native Supervisor child ${e.name} does not exist`);let n=uE(r).find(({status:c})=>c!=="integrated"&&c!=="archived");if(n&&n.name!==e.name)throw new Error(`Native Supervisor integration order requires ${n.name} before ${e.name}`);if(i.status!=="verified"||!i.verifiedCommit)throw new Error(`Native Supervisor child ${e.name} must be verified before integration`);let a=ll(r);if(a!==r.integration.headCommit){let c=(()=>{try{return I(r.integration.worktree,["merge-base","--is-ancestor",r.integration.headCommit,a]),!0}catch{return!1}})(),l=(()=>{try{return I(r.integration.worktree,["merge-base","--is-ancestor",i.verifiedCommit,a]),!0}catch{return!1}})();if(!c||!l)throw new Error(`Native Supervisor integration head drifted: expected ${r.integration.headCommit}, got ${a}`)}try{I(r.integration.worktree,["cat-file","-e",`${i.verifiedCommit}^{commit}`])}catch(c){throw new Error(`Native Supervisor verified commit is unavailable: ${i.verifiedCommit}`,{cause:c})}if(a===r.integration.headCommit){try{I(r.integration.worktree,["merge","--no-ff","--no-edit",i.verifiedCommit])}catch(c){throw new Error(`Native Supervisor integration conflict preserved in ${r.integration.worktree}`,{cause:c})}a=I(r.integration.worktree,["rev-parse","HEAD"])}let o=a,s=hE(r,{name:e.name,integrationCommit:o,checks:e.checks});return await ne(e.paths,s),s})}function mE(e,t){if(Vt(t.headCommit,"Native Supervisor final verification head commit"),t.summary.trim().length===0)throw new Error("Native Supervisor final verification summary must not be empty");let r=ze(e);if(t.headCommit!==r.integration.headCommit)throw new Error("Native Supervisor final verification head is stale");if(t.status==="passed"){if(r.children.some(({status:i})=>i!=="integrated"))throw new Error("Native Supervisor cannot pass final verification before all children integrate");if(t.layers.parentChecks.length===0)throw new Error("Native Supervisor parent verification requires executed parent checks");if(t.layers.childVerification!=="complete"||t.layers.parentIntegration!=="complete"||t.layers.incomplete.length>0)throw new Error("Native Supervisor final verification evidence is incomplete")}return r.finalVerification={status:t.status,summary:t.summary,layers:{childVerification:t.layers.childVerification,parentIntegration:t.layers.parentIntegration,parentChecks:[...t.layers.parentChecks],notRerun:[...t.layers.notRerun],incomplete:[...t.layers.incomplete]}},r.stateVersion+=1,r}function Yi(e){let t=ll(e);if(t===e.integration.headCommit)return e;try{I(e.integration.worktree,["merge-base","--is-ancestor",e.integration.headCommit,t])}catch{throw new Error("Native Supervisor integration head is not a descendant of the recorded integration head")}let r=ze(e);return r.integration.headCommit=t,it(r,{kind:"integration-head-reconciled",child:null,runId:null,summary:"Parent-level commits were included in final verification"}),r.stateVersion+=1,r}function Xi(e,t){let r=t.verification;if(r===null||t.verification_result==="pending")throw new Error("Native Supervisor final verification has no persisted Portable result");let i=ll(e),n=e.children.every(({status:o,verification:s})=>(o==="integrated"||o==="archived")&&s!==null),a=r.checks.length>0&&r.checks.every(({status:o})=>o==="passed");return mE(e,{status:t.verification_result==="pass"?"passed":t.verification_result==="blocked"?"incomplete":"failed",summary:r.summary.text,headCommit:i,layers:{childVerification:n?"complete":"incomplete",parentIntegration:a?"complete":"incomplete",parentChecks:r.checks.map(({name:o})=>o.text),notRerun:e.children.flatMap(({verification:o})=>o?.checks??[]),incomplete:r.checks.filter(({status:o})=>o!=="passed").map(({name:o})=>o.text)}})}function gh(e){let t=e.children.map(r=>({name:r.name,summary:r.summary,dependsOn:[...r.dependsOn],covers:[],status:r.status,phase:null,projectRoot:r.projectRoot??r.task?.projectRoot??null,message:r.blocker}));return{contractHash:null,confirmed:!0,parentBranch:e.integration.branch,children:t,readyChildren:t.filter(({status:r})=>r==="ready").map(({name:r})=>r),allDone:t.every(({status:r})=>r==="integrated"||r==="archived")}}var wh="children.yaml",Qi="comet.native.children.v1",Vr="comet.native.children.v2",Ch=Vr,vE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,yh=new Set(["schema","children"]),gE=new Set(["schema","acceptance_index","children"]),wE=new Set(["name","depends_on","covers"]),yE=new Set(["name","summary","depends_on"]),NE=new Set(["name","depends_on","covers"]);function co(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function so(e,t,r){let i=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(i.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...i.length>0?[`unexpected ${i.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${r} fields are invalid: ${a.join("; ")}`)}}function Nh(e,t){if(!Array.isArray(e)||!e.every(r=>typeof r=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((r,i)=>r.localeCompare(i,"en"))}function dl(e,t){let r=Te.normalize(Te.resolve(e)),i=Te.normalize(Te.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function bE(e){let t=new Map(e.map(a=>[a.name,a])),r=new Set,i=new Set,n=a=>{if(!i.has(a)){if(r.has(a))throw new Error(`Native children dependency cycle includes ${a}`);r.add(a);for(let o of t.get(a).depends_on)n(o);r.delete(a),i.add(a)}};for(let a of e)n(a.name)}function bh(e,t,r=t){let i=new Set(t);for(let o of e){let s=o.covers.filter(c=>!i.has(c));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=r.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function kE(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===Ch&&e.acceptance_index){let n=r.requiredAcceptanceIds??t??[],a=r.allowedAcceptanceIds??n,o=Object.keys(e.acceptance_index);i.missing=n.filter(l=>!(l in e.acceptance_index)),i.extra=o.filter(l=>!a.includes(l));let s=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of o){let f=s.get(l),u=e.acceptance_index[l];f&&u&&(u.source!==f.source||u.text!==f.text)&&i.mismatched.push(l)}let c=new Set(o);for(let l of e.children)i.unknownCovers.push(...l.covers.filter(f=>!c.has(f)));return i.uncovered=o.filter(l=>!kh(e.children,l)),Sh(i)?i:null}if(e.schema===Qi&&t){let n=new Set(t);for(let a of e.children)i.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return i.uncovered=t.filter(a=>!kh(e.children,a)),Sh(i)?i:null}return null}function kh(e,t){return e.some(r=>r.covers.includes(t))}function Sh(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function Mr(e){let t=new Set(e.acceptance.map(({id:n})=>n)),r=new Set(e.acceptance.filter(({source:n})=>n===e.brief).map(({id:n})=>n)),i=new Set(r);for(let n of e.history.filter(({outcome:a})=>a==="fail"))for(let a of n.unresolved_ids)t.has(a)&&i.add(a);if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let n=[...e.history].reverse().find(({outcome:a})=>a==="fail");for(let a of n?.unresolved_ids??[])r.add(a)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...r],allowedAcceptanceIds:[...i]}}function SE(e){let t=co(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),r={};for(let[i,n]of Object.entries(t)){let a=co(n,`Native children acceptance_index.${i}`);if(so(a,new Set(["source","text"]),`Native children acceptance_index.${i}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${i}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${i}.text must be a non-empty string`);r[i]={source:a.source,text:a.text}}return r}function EE(e,t,r){let i=r.requiredAcceptanceIds??t??[],n=r.allowedAcceptanceIds??i,a=Object.keys(e),o=i.filter(l=>!(l in e)),s=a.filter(l=>!n.includes(l));if(o.length>0||s.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${o.join(", ")||"none"}; extra ${s.join(", ")||"none"}`);let c=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of a){let f=c.get(l);if(!f)continue;let u=e[l];if(u.source!==f.source||u.text!==f.text){let d=["source","text"].filter(m=>u[m]!==f[m]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${d.join(", ")} exactly from the current acceptance catalog`)}}}function xE(e,t,r={}){let i=(0,fl.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=co(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==Qi&&a!==Vr)throw so(n,yh,"Native children contract"),new Error(`Native children schema must be ${Qi} or ${Vr}`);let o=a===Qi?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(so(n,o==="indexed-v2"?gE:yh,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let c=n.children.map((d,m)=>{let v=co(d,`Native child ${m}`);if(so(v,o==="indexed-v2"?NE:o==="summary-v2"?yE:wE,`Native ${s} child fields (child ${m})`),typeof v.name!="string"||!vE.test(v.name))throw new Error(`Native child ${m} 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:Nh(v.depends_on,`Native child ${v.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?Nh(v.covers,`Native child ${v.name} covers`):[]}}),l=c.map(({name:d})=>d);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let f=new Set(l);for(let d of c){let m=d.depends_on.filter(v=>!f.has(v));if(m.length>0)throw new Error(`Native child ${d.name} depends on unknown child: ${m.join(", ")}`)}bE(c);let u=r.policy==="advisory";if(a===Ch){if(o==="indexed-v2"){let d=SE(n.acceptance_index);u||EE(d,t,r);let m=Object.keys(d);return u||bh(c,m,m),{schema:Vr,acceptance_index:d,children:c}}return{schema:Vr,children:c}}return t&&!u&&bh(c,t),{schema:Qi,children:c}}async function Mt(e){let t=Te.join(e.changeDir,wh);try{await xh.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await Y({root:e.changeDir,ref:wh}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=xE(r.text,e.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?kE(a,e.acceptanceIds,e.validation??{}):null}}function CE(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let r=e.slice(t.index+t[0].length);return r.split(/^#\s+/mu,1)[0]??r}function PE(e){let t=CE(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let r=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),i=t.match(/\bChild\s+\d+\b/giu);return Math.max(r?.length??0,i?.length??0)>=2}async function lo(e){try{let t=await Y({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return PE(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Zi(e){return X("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:r,text:i})=>({id:t,source:r,text:i})),children:e.children})}async function RE(e){let t=Zt(e.projectRoot);t.some(i=>dl(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>Te.resolve(n)))]){let n=await Ne(i);n&&r.push({projectRoot:i,paths:await Dt(i,n.native.artifact_root),parent:dl(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function AE(e,t){let r=Te.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Me(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function _E(e,t){let r;try{r=await xh.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=Te.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await Me(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function IE(e,t,r){let i=Te.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${Te.sep}`))return null;let n=i.split(Te.sep).join("/");try{let a=(0,fl.parseDocument)(I(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:C(a.toJS({mapAsMap:!1}))}catch{return null}}function TE(e,t,r){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==r||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${r??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function Eh(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function nt(e){let t=Te.join(e.paths.changesDir,e.state.name),r=await lo(t),i=await Mt({changeDir:t,validation:Mr(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:p})=>p)}:{},policy:"advisory"});if(!i)return e.state.children_contract_hash?{...r?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:r?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null;let n=Zi({acceptance:e.state.acceptance,children:i.contract}),a=e.state.workspace.change_branch,o=e.state.phase!=="shape"&&e.state.children_contract_hash===n&&!i.drift;if(i.contract.schema===Vr){let p=await W(e.paths,e.state.name);if(!p){let y=e.state.workspace.target_branch??e.state.workspace.change_branch;if(y){let b=await ao({paths:e.paths,parent:e.state.name,targetBranch:y,contract:i.contract});b&&(p=b,await ne(e.paths,b))}}if(p){let y=gh(p);return e.state.children_contract_hash!==n||i.drift?{...y,schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:!1,readyChildren:[],allDone:!1,children:y.children.map(b=>({...b,message:i.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...y,schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o}}let w=new Map(i.contract.children.map(y=>[y.name,y])),g=i.contract.children.map(y=>({name:y.name,summary:y.summary,dependsOn:[...y.depends_on],covers:[],status:o&&y.depends_on.every(b=>i.contract.children.filter(({name:N})=>N!==y.name).every(({name:N})=>N!==b))?"ready":"pending",phase:null,projectRoot:null,message:o?null:"Parent Shape confirmation is required"}));for(let y of g){if(y.status!=="ready")continue;w.get(y.name).depends_on.length>0&&(y.status="pending")}return{schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:g,readyChildren:g.filter(({status:y})=>y==="ready").map(({name:y})=>y),allDone:!1}}let s=await RE(e.paths),c=new Set(i.contract.children.map(({name:p})=>p)),l=new Map,f=new Map;for(let p of s){let w=p.parent&&a?`refs/heads/${a}`:"HEAD";for(let g of await _E(p,c)){let y={...g,source:p,committedState:IE(p,g.file,w)};l.set(g.state.name,[...l.get(g.state.name)??[],y])}for(let g of c){let y=await AE(p,g);y&&f.set(g,[...f.get(g)??[],{source:p,state:y}])}}let u=new Map;for(let p of i.contract.children){let w=(l.get(p.name)??[]).find(({source:b,committedState:N})=>b.parent&&N?.name===p.name&&Eh(N,a));if(w){u.set(p.name,{kind:"done",phase:w.state.phase,projectRoot:w.source.projectRoot,message:null});continue}let g=l.get(p.name)?.[0];if(g){u.set(p.name,{kind:"blocked",phase:g.state.phase,projectRoot:g.source.projectRoot,message:`Native child ${p.name} is archived but not merged into parent branch ${a??"(missing)"}`});continue}let y=f.get(p.name)??[];y.length>1?u.set(p.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${p.name} has multiple active workspace owners`}):y[0]&&u.set(p.name,TE(y[0].state,y[0].source,a))}let d=new Map(i.contract.children.map(p=>[p.name,p])),m=new Map,v=p=>{let w=m.get(p);if(w)return w;let g=d.get(p),b=g.depends_on.map(v).every(({status:F})=>F==="done"),N=u.get(p),E=N?.kind==="active"&&b?g.depends_on.filter(F=>!(l.get(F)??[]).some(({source:ee,committedState:j})=>dl(ee.projectRoot,N.projectRoot)&&j?.name===F&&Eh(j,a))):[],P,k=N?.message??null;N?.kind==="done"?(P=b?"done":"blocked",b||(k=`Native child ${p} was merged before its dependencies`)):N?.kind==="active"?(P=b&&E.length===0?"active":"blocked",b?E.length>0&&(k=`Native child ${p} does not include merged dependencies: ${E.join(", ")}`):k=`Native child ${p} started before its dependencies merged`):N?.kind==="blocked"?P="blocked":(P=o&&b?"ready":"pending",o||(k="Parent Shape confirmation is required"));let T={name:p,summary:g.summary,dependsOn:[...g.depends_on],covers:[...g.covers],status:P,phase:N?.phase??null,projectRoot:N?.projectRoot??null,message:k};return m.set(p,T),T},h=i.contract.children.map(({name:p})=>v(p));return{schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:h,readyChildren:h.filter(({status:p})=>p==="ready").map(({name:p})=>p),allDone:h.every(({status:p})=>p==="done")}}function ht(e,t,r){return e.language==="zh-CN"?r:t}function jE(e,t){let r=i=>({required:!1,message:null,suggestedReply:null,agentInstruction:i});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:ht(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:ht(e,"Reply A or B","回复 A 或 B"),agentInstruction:ht(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 r(ht(e,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result")return r(ht(e,"Wait only while the dispatched Verifier task is still active. If the task did not start, failed, timed out, ended without a response, or was lost, immediately submit verifier-execution-error. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","仅在已派发的独立验收任务仍在运行时等待。如果任务未启动、执行失败、超时、结束后没有返回结果或已经丢失,立即提交 verifier-execution-error;只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。"));if(e.status==="blocked"&&e.blockers.some(({resolution_action:i})=>i==="retry-verifier"))return e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable")return e.language==="zh-CN"?{required:!0,message:"独立验收当前不可用,但你的代码和已经完成的检查都已安全保留。你可以直接重新尝试独立验收,也可以明确接受只有自动检查的结果。",suggestedReply:"重新尝试独立验收",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户选择。用户要求重试时执行 commandAlternatives 中的 retry-verifier;只有用户明确接受降级结果时才执行 confirm-verifier-unavailable。不要把“继续”视为接受降级结果,也不要要求用户处理文件、进程、服务或回调。"}:{required:!0,message:"Independent verification is currently unavailable, but your code and completed checks are safely preserved. You can retry independent verification directly or explicitly accept the automatic-check-only result.",suggestedReply:"Retry independent verification",agentInstruction:"Relay only message and suggestedReply, then wait for the user choice. If the user asks to retry, run retry-verifier from commandAlternatives; run confirm-verifier-unavailable only when the user explicitly accepts the degraded result. Do not treat “Continue” as accepting the degraded result, and do not ask the user to manage files, processes, services, or callbacks."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="resolve-verifier-blocker")return e.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="await-user"){let n=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",a=n?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。",o=n?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return e.language==="zh-CN"?{required:!0,message:a,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:o,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}return r(ht(e,"Follow the continuation action. Unless required is true, continue without asking the user to handle internal workflow state, and do not present machine fields as a user-facing explanation.","按 continuation 执行下一步。除非 required 为 true,否则继续推进,不要让用户处理内部工作流状态,也不要把机器字段作为面向用户的说明。"))}function $E(e){let t=e.workspace.change_branch??"<change-branch>",r=e.workspace.target_branch??"<target-branch>";return e.language==="zh-CN"?{required:!0,message:`当前 change 位于 ${t},目标分支为 ${r}。请选择一次工作区收尾方式:A) 保留工作区;B) 本地合并;C) 推送分支;D) 推送并创建 PR;E) 暂不归档。选择 A-D 后 Runtime 会先执行完整 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 ${r}. Choose one workspace finish: A) keep the workspace; B) merge locally; C) push the branch; D) push and create a PR; or E) defer Archive. For A-D, Runtime will run 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 OE(e){return[...[{finish:"keep",name:"keep-workspace",description:["保留当前分支和目录;完成归档提交,不合并、不推送、不创建 PR。","Keep the current branch and directory; create the archive commit without merging, pushing, or creating a PR."]},{finish:"merge",name:"merge-locally",description:["完成归档提交,并把 change 分支本地合并到目标分支;不推送、不创建 PR。","Create the archive commit and merge the change branch locally into the target branch without pushing or creating a PR."]},{finish:"push",name:"push-branch",description:["完成归档提交并推送 change 分支;不合并到目标分支、不创建 PR。","Create the archive commit and push the change branch without merging into the target branch or creating a PR."]},{finish:"pull-request",name:"push-pull-request",description:["完成归档提交、推送 change 分支,并以目标分支为基础创建 PR。","Create the archive commit, push the change branch, and create a PR against the target branch."]}].map(({finish:i,name:n,description:a})=>({name:n,stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","archive",e.name,"--dry-run","--finish",i],requiredInputs:[],inputOptions:[],description:ht(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:ht(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function Rh(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Fr(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function HE(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function Ph(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function DE(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function BE(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 Ft(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:Rh({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Fr("summary","--summary"),HE(e.name,e.flag)]}}function pl(e){return[Ft({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Ft({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function Q(e,t,r={}){let i=DE(t)&&e.coordination_mode===void 0,n=jE(e,i),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:[Fr("summary","--summary")],commandAlternatives:[Ft({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:[Fr("summary","--summary")],commandAlternatives:[Ft({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...pl({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:[Fr("summary","--summary")],commandAlternatives:[Ft({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),Ft({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:[Fr("summary","--summary")],commandAlternatives:[Ft({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...pl({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:[Fr("summary","--summary")],commandAlternatives:pl({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?Rh({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:i?"await-user":"continue",action:"prepare-shape-confirmation",commandArgs:BE({change:e.name,stateVersion:e.state_version,coordinationRequired:i}),requiredInputs:["summary",...i?["coordination-choice"]:[]],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},...i?[Ph("coordination-mode","--coordination-mode",Ta)]:[]],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} ${ht(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=r.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"?r.archiveBlockers&&r.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:[Ph("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...OE(e)],userCommunication:$E(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[Ft({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{randomUUID as Dx}from"node:crypto";import{promises as ln}from"node:fs";import Bx from"node:path";import{randomUUID as Il}from"node:crypto";import{promises as lr}from"node:fs";import oe from"node:path";var VE=["outcome","scope","nonGoals","acceptanceExamples"],d$=[...VE,"constraints","decisions","openQuestions","verificationExpectations"];function Ah(e){let t=new Set(["blocker","blocking","coverage","decision","open_question","question","requirement","requirements","source","source_coverage","state","status","决策","来源","覆盖","问题","状态","需求","阻塞"]),r=null;for(let i of e.split(/\r?\n/u)){let n=i.match(/^\s*(`{3,}|~{3,})/u);if(n){let s=n[1]?.[0];r===null?r=s:r===s&&(r=null);continue}if(r!==null)continue;let a=i.trim();if(/^(?:[-*+]\s+|\d+[.)]\s+)(?:\[[ xX]\]\s+)?\[blocking\](?=$|[\s::—-])/iu.test(a)||a.includes("|")&&a.split("|").some(s=>/^\s*\[blocking\](?=$|[\s::—-])/iu.test(s)))return!0;let o=a.match(/^([\p{L}\p{N}_./-]+)\s*[::]\s*\[blocking\](?=$|[\s::—-])/iu);if(o){let s=o[1]?.toLocaleLowerCase("en-US")??"";if(t.has(s)||/[./_-]/u.test(s))return!0}}return!1}import{createWriteStream as sx,promises as cx}from"node:fs";import Se from"node:path";import{spawn as hl}from"node:child_process";import{existsSync as _h}from"node:fs";import sr from"node:path";var ME=new Set([".bat",".cmd",".ps1"]),FE=new Set([".bat",".cmd"]),qE=/[&|<>()^%"!\r\n]/u,WE=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");function ml(e,t){let r=t.toLowerCase();return Object.entries(e).find(([i,n])=>i.toLowerCase()===r&&n!==void 0)?.[1]}function zE(e){let t=(ml(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function JE(e,t,r){let n=sr.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(ml(t,"PATH")??"").split(sr.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=sr.win32.extname(e)?[e]:zE(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(c=>s?sr.join(s,c):sr.resolve(r,c)))}function GE(e,t,r){return JE(e,t,r).find(i=>_h(i))??e}function UE(e){let t=ml(e,"SystemRoot");if(t){let r=sr.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe");if(_h(r))return r}return"powershell.exe"}function KE(e){if(e.some(t=>qE.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}function YE(e,t,r){let i=Buffer.from(JSON.stringify({command:e,arguments:[...t]}),"utf8").toString("base64"),n=Buffer.from(WE,"utf16le").toString("base64");return hl(UE(r.env),["-NoLogo","-NoProfile","-NonInteractive","-InputFormat","None","-OutputFormat","Text","-ExecutionPolicy","Bypass","-EncodedCommand",n],{cwd:r.cwd,env:{...r.env,COMET_COMMAND_PAYLOAD:i},shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}function vl(e,t,r){let i=r.env??process.env;if(process.platform!=="win32")return hl(e,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});let n=GE(e,i,r.cwd),a=sr.win32.extname(n).toLowerCase();return FE.has(a)&&KE(t),ME.has(a)?YE(n,t,{cwd:r.cwd,env:i}):hl(n,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}import{spawn as XE}from"node:child_process";import gl from"node:path";var QE=1e3,ZE=2;async function uo(e){let t=e.pid;if(t===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let r=process.env.SystemRoot??process.env.WINDIR,i=r&&gl.win32.isAbsolute(r)?gl.win32.resolve(r):"C:\\Windows",n=gl.win32.join(i,"System32","taskkill.exe"),a=()=>new Promise(o=>{let s=!1,c=null,l=null,f=(u,d=!1)=>{s||(s=!0,l&&clearTimeout(l),d&&c?.kill("SIGKILL"),o(u))};try{c=XE(n,["/pid",String(t),"/t","/f"],{stdio:"ignore",windowsHide:!0}),c.once("error",()=>f(!1)),c.once("close",u=>f(u===0)),l=setTimeout(()=>f(!1,!0),QE)}catch{f(!1)}});for(let o=0;o<ZE;o+=1)if(await a()){e.kill("SIGKILL");return}e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy();return}try{process.kill(-t,"SIGKILL")}catch(r){if(r.code!=="ESRCH")throw r}e.kill("SIGKILL")}var ex=/\b(Bearer|Basic)\s+[^\s"']+/giu,tx=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,rx=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,ix=/\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,nx=/("(?:[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,ax=/(["'])((?:[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,ox=/\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 qt(e){return e.replace(ex,"$1 [REDACTED]").replace(tx,"[REDACTED PRIVATE KEY]").replace(rx,"$1[REDACTED]@").replace(ix,"[REDACTED TOKEN]").replace(nx,'$1"[REDACTED]"').replace(ax,"$1$2$1$3$4[REDACTED]$4").replace(ox,"$1$2[REDACTED]")}function Ih(e,t){let r=Se.relative(e,t);return r===""||!Se.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Se.sep}`)}function Th(e,t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(e))throw new Error(`${t} is invalid`);return e}function fo(e,t){if(t.length===0||t.includes("\\")||Se.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||Se.posix.normalize(t)!==t)throw new Error("Native check cwd must be a normalized project-relative ref");let r=Se.resolve(e),i=Se.resolve(r,...t.split("/"));if(!Ih(r,i))throw new Error("Native check cwd escaped the project root");return i}function en(e){return JSON.stringify([e.executable,e.argv,e.cwdRef.replaceAll("\\","/"),e.timeoutMs,e.repeatable])}var lx=/^(?:-p|-u|--(?:[a-z0-9]+[-_])*(?:api[-_]?key|access[-_]?token|auth[-_]?token|client[-_]?secret|secret(?:[-_]?access)?[-_]?key|private[-_]?key|token|password|passwd|secret|authorization|cookie|set[-_]?cookie|user))$/iu;function wl(e){let t=!1;return e.map(r=>{if(t)return t=!1,"[REDACTED]";let i=qt(r);return lx.test(r)&&(t=!0),i})}function po(e,t){if(Th(t.id,"Native check ID"),t.name.trim().length===0||t.executable.trim().length===0)throw new Error("Native check name and executable must be non-empty");if(!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<1)throw new Error("Native check timeout must be a positive integer");return fo(e,t.cwdRef)}async function yl(e){let{plan:t}=e;Th(e.operationId,"Native check operation ID");let r=po(e.projectRoot,t),i=Se.join(e.runtimeDir,"logs","checks"),n=Se.join(i,`${e.operationId}-${t.id}.log`);if(!Ih(Se.resolve(e.runtimeDir),Se.resolve(n)))throw new Error("Native check log path escaped the Runtime root");await cx.mkdir(i,{recursive:!0});let a=(e.now??(()=>new Date))(),o=sx(n,{flags:"wx"});return new Promise((s,c)=>{let l;try{l=vl(t.executable,t.argv,{cwd:r,env:process.env})}catch(m){o.destroy(),c(m);return}let f=!1,u=null,d=setTimeout(()=>{f=!0,uo(l).catch(()=>l.kill("SIGKILL"))},t.timeoutMs);d.unref?.(),l.stdout.pipe(o,{end:!1}),l.stderr.pipe(o,{end:!1}),l.once("error",m=>{u=m,o.write(`
181
+ `,"utf8"),!0}function aE(e,t,r){let i=le.resolve(e,r??le.join(".worktrees",t)),n=le.resolve(e,I(e,["rev-parse","--git-common-dir"]));if(oh(n,i))throw new Error("Native worktree path cannot be inside the Git common directory");if(Zt(e).some(a=>nl(a,i)))throw new Error(`Native worktree path is already registered: ${i}`);return i}async function oE(e){try{throw await Ki.lstat(e),new Error(`Native worktree path already exists: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t}}async function ah(e){try{return await Ki.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function al(e){let t=le.resolve(e.projectRoot);if(e.isolation==="current"){if(e.changeBranch||e.targetBranch||e.worktreePath)throw new Error("Native current isolation does not accept --change-branch, --target-branch, or --worktree-path");let i=z(t);if(i.isGitWorktree&&i.currentBranch===null)throw new Error("Native workspace binding requires a branch; detached HEAD is not supported");return{projectRoot:t,binding:{isolation:"current",changeBranch:i.currentBranch,targetBranch:i.currentBranch},preparation:{isolation:"current",projectRoot:t,changeBranch:i.currentBranch,targetBranch:i.currentBranch,worktreePath:null,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1}}}let r=await Dt(t,e.sourceConfig?.native.artifact_root??"docs");return wp([{runtimeDir:r.runtimeDir,locksDir:r.locksDir}],`prepare Native ${e.isolation} workspace`,async()=>{let i=z(t);if(!i.isGitWorktree||i.currentBranch===null||i.primaryWorktreeRoot===null||i.currentWorktreeRoot===null)throw new Error("Native branch and worktree isolation require an attached Git branch");let n=e.changeBranch??`comet/${e.name}`;hc(t,n);let a=i.currentBranch===n,o=e.targetBranch??(a?void 0:i.currentBranch);if(!o)throw new Error("Native isolated workspace already on its change branch requires --target-branch");if(hc(t,o),!Sr(t,o))throw new Error(`Native target branch is not a verified local branch: ${o}`);if(e.isolation==="branch"){if(e.worktreePath)throw new Error("--worktree-path is only valid with --isolation worktree");let m=!1;if(!a){if(!ut(t))throw new Error("Native branch isolation requires a clean current working directory");if(Sr(t,n))throw new Error(`Native change branch already exists: ${n}`);I(t,["switch","-c",n,o]),m=!0}let v;try{v=await no(t,e.sourceConfig)}catch(h){throw new Lt(`Native branch preparation is incomplete: ${h.message}`,{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:m,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:t,binding:{isolation:"branch",changeBranch:n,targetBranch:o},preparation:{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:m,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}if(a){if(!i.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree");let m=e.worktreePath?le.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(m&&!nl(m,i.currentWorktreeRoot))throw new Error(`Native worktree path ${m} does not match the current worktree ${i.currentWorktreeRoot}`);let v;try{v=await no(t,e.sourceConfig)}catch(h){throw new Lt(`Native worktree preparation is incomplete: ${h.message}`,{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:t,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}let s=ha(i.primaryWorktreeRoot),c=s.find(m=>m.branch===n);if(c&&await ah(c.root)){let m=e.worktreePath?le.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(m&&!nl(m,c.root))throw new Error(`Native worktree branch ${n} is already checked out at ${c.root}`);let v;try{v=await no(c.root,e.sourceConfig)}catch(h){throw new Lt(`Native worktree preparation is incomplete: ${h.message}`,{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:c.root,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}c&&!await ah(c.root)&&(I(i.primaryWorktreeRoot,["worktree","prune"]),s=ha(i.primaryWorktreeRoot));let l=Sr(t,n);if(s.some(m=>m.branch===n))throw new Error(`Native change branch ${n} is already registered to a worktree`);let f=aE(i.primaryWorktreeRoot,e.name,e.worktreePath);await oE(f);let u=await nE(i.primaryWorktreeRoot,f),d={isolation:"worktree",projectRoot:f,changeBranch:n,targetBranch:o,worktreePath:f,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:u,configInitialized:!1};try{I(i.primaryWorktreeRoot,l?["worktree","add",f,n]:["worktree","add","-b",n,f,o]),d.createdBranch=!l,d.createdWorktree=!0,d.configInitialized=await no(f,e.sourceConfig)}catch(m){throw new Lt(`Native worktree preparation is incomplete: ${m.message}`,d,{cause:m})}return{projectRoot:f,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:d}})}var ol="comet.native.supervisor.v2",cE=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function ch(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native Supervisor parent name: ${e}`);return`comet/supervisor/${e}/integration`}async function lh(e){let t=or.join(".worktrees",`${e.parent}-integration`);return al({projectRoot:e.projectRoot,name:`${e.parent}-integration`,isolation:"worktree",changeBranch:ch(e.parent),targetBranch:e.targetBranch,worktreePath:t,sourceConfig:e.sourceConfig})}async function lE(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.parent)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.child))throw new Error("Native Supervisor parent and child names are invalid");return al({projectRoot:e.projectRoot,name:`${e.parent}-${e.child}`,isolation:"worktree",changeBranch:`comet/supervisor/${e.parent}/${e.child}`,targetBranch:e.targetBranch,worktreePath:or.join(".worktrees",`${e.parent}-${e.child}`),sourceConfig:e.sourceConfig})}function uE(e,t){return or.join(Ve(e,t),"supervisor")}function Lr(e,t){return or.join(uE(e,t),"state.json")}function uh(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!==ol)throw new Error(`Native Supervisor state schema must be ${ol}`);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(Vt(t.integration.targetCommit,"Native Supervisor target commit"),Vt(t.integration.headCommit,"Native Supervisor integration head commit"),!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let r=new Set,i=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(r.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(r.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.projectRoot!==void 0&&n.projectRoot!==null&&(typeof n.projectRoot!="string"||n.projectRoot.length===0))throw new Error(`Native Supervisor child ${n.name} projectRoot is invalid`);for(let[a,o]of[["base",n.baseCommit],["candidate",n.candidateCommit],["verified",n.verifiedCommit],["integration",n.integrationCommit]])o!==null&&Vt(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(Vt(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),i.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(i.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.role==="builder"&&n.status!=="active"||n.task.role==="verifier"&&!["active","needs-reverify"].includes(n.status))throw new Error(`Native Supervisor child ${n.name} task status is invalid`)}}}async function W(e,t){try{let r=await sh.readFile(Lr(e,t),"utf8"),i=JSON.parse(r);return uh(i),i}catch(r){if(r.code==="ENOENT")return null;throw r}}async function ne(e,t){uh(t),await sh.mkdir(e.changesRuntimeDir,{recursive:!0}),await ye(Lr(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function Vt(e,t){if(!cE.test(e))throw new Error(`${t} must be a Git commit`)}function ze(e){return structuredClone(e)}function it(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function dE(e,t){for(let r of t.dependsOn){let i=e.children.find(({name:n})=>n===r);if(!i||i.status!=="integrated")throw new Error(`Native Supervisor child ${t.name} dependency ${r} is not integrated`)}}function fE(e){let t=new Set(e.children.map(({name:i})=>i)),r=[];for(;t.size>0;){let i=e.children.find(n=>t.has(n.name)&&n.dependsOn.every(a=>!t.has(a)));if(!i)throw new Error("Native Supervisor Child dependencies contain a cycle");r.push(i),t.delete(i.name)}return r}function sl(e){Vt(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:i})=>i)),r=e.contract.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.depends_on],status:i.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null}));for(let i of r)for(let n of i.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${i.name} depends on unknown child ${n}`);return{schema:ol,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:r,history:[],finalVerification:{status:"pending",summary:null}}}async function ao(e){let t=ch(e.parent),r=Er(e.paths.projectRoot,t);if(!r)return null;let i=Er(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=Zt(e.paths.projectRoot).map(o=>or.resolve(o)).find(o=>z(o).currentBranch===t);if(!n)return null;let a=sl({parent:e.parent,targetBranch:e.targetBranch,targetCommit:i,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(r!==i){for(let o of a.children)o.status=o.dependsOn.length===0?"blocked":"pending",o.blocker=o.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;a.integration.headCommit=r}return it(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function dh(e){let t=ze(e.state),r=new Map(e.contract.children.map(n=>[n.name,n])),i=new Map(t.children.map(n=>[n.name,n]));for(let n of t.children){let a=r.get(n.name);if(!a){if(n.status!=="archived")throw new Error(`Native Supervisor child ${n.name} cannot be removed before Archive`);continue}if((n.status==="integrated"||n.status==="archived")&&(a.summary!==n.summary||a.depends_on.join("\0")!==n.dependsOn.join("\0")))throw new Error(`Native Supervisor integrated child ${n.name} history is immutable`);n.summary=a.summary,n.dependsOn=[...a.depends_on]}for(let n of e.contract.children)i.has(n.name)||t.children.push({name:n.name,summary:n.summary,dependsOn:[...n.depends_on],status:n.depends_on.every(a=>t.children.some(({name:o,status:s})=>o===a&&s==="integrated"))?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null});return t.stateVersion+=1,t}function cl(e,t){if(!t.projectRoot.trim()||!t.runId.trim())throw new Error("Native Supervisor task projectRoot and runId are required");let r=ze(e),i=r.children.find(({name:o})=>o===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(i.task)throw new Error(`Native Supervisor child ${t.child} already has an active task`);let n;if(t.role==="builder"){if(i.status!=="ready")throw new Error(`Native Supervisor child ${t.child} is not ready for a Builder task`);dE(r,i),n=r.integration.headCommit,i.status="active"}else{if(i.status!=="active"&&i.status!=="needs-reverify"||!i.candidateCommit)throw new Error(`Native Supervisor child ${t.child} is not ready for a Verifier task`);n=i.candidateCommit}let a={...t,baseCommit:n};return i.projectRoot=t.projectRoot,i.task=a,i.blocker=null,it(r,{kind:"task-dispatched",child:i.name,runId:a.runId,summary:`${a.role} task dispatched`}),r.stateVersion+=1,{state:r,task:a}}function pE(e,t){let r=e.children.find(({name:i})=>i===t.child);if(!r?.task||r.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return structuredClone(r.task)}function fh(e,t){let r=pE(e,t),i=ze(e);return it(i,{kind:"task-reconnected",child:t.child,runId:t.runId,summary:"existing task reconnected"}),i.stateVersion+=1,{state:i,task:r}}function hE(e,t,r){let i=z(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor child worktree identity is not ${t}`);if(!ut(e))throw new Error(`Native Supervisor child worktree is not clean: ${e}`);let n=I(e,["rev-parse","HEAD"]);if(n===r)return;if(!(()=>{try{return I(e,["merge-base","--is-ancestor",n,r]),!0}catch{return!1}})())throw new Error(`Native Supervisor child worktree ${e} cannot be refreshed from integration HEAD`);if((()=>{try{return I(e,["merge-base","--is-ancestor",r,n]),!0}catch{return!1}})())throw new Error(`Native Supervisor child worktree ${e} contains unintegrated commits`);if(I(e,["merge","--ff-only",r]),I(e,["rev-parse","HEAD"])!==r)throw new Error("Native Supervisor child worktree did not reach integration HEAD")}function ll(e){if(!ut(e.integration.worktree))throw new Error("Native Supervisor integration worktree must be clean");let t=I(e.integration.worktree,["rev-parse","--show-toplevel"]);if(or.resolve(t)!==or.resolve(e.integration.worktree))throw new Error("Native Supervisor integration worktree identity is invalid");let r=I(e.integration.worktree,["branch","--show-current"]);if(r!==e.integration.branch)throw new Error(`Native Supervisor integration branch mismatch: expected ${e.integration.branch}, got ${r||"(detached)"}`);return I(e.integration.worktree,["rev-parse","HEAD"])}function mE(e,t,r){let i=z(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor Verifier worktree identity is not ${t}`);if(!ut(e))throw new Error(`Native Supervisor Verifier worktree is not clean: ${e}`);if(I(e,["rev-parse","HEAD"])!==r)throw new Error("Native Supervisor Verifier worktree is not at its candidate commit")}function ul(e,t){if(t.reason.trim().length===0)throw new Error("Native Supervisor cancellation reason is required");let r=ze(e),i=r.children.find(({name:n})=>n===t.child);if(!i?.task||i.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return i.task.role==="builder"?(i.status="ready",i.candidateCommit=null):i.status="needs-reverify",i.task=null,i.blocker=t.reason,it(r,{kind:"task-cancelled",child:t.child,runId:t.runId,summary:t.reason}),r.stateVersion+=1,r}function oo(e,t){if(t.reason.trim().length===0)throw new Error("Native Supervisor blocker reason is required");let r=ze(e),i=r.children.find(({name:n})=>n===t.child);if(!i?.task||i.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return i.blocker=t.reason,it(r,{kind:"task-blocked",child:t.child,runId:t.runId,summary:t.reason}),r.stateVersion+=1,r}async function ph(e){return x(e.paths,`dispatch Native Supervisor children ${e.parent}`,async()=>{let t=await W(e.paths,e.parent);if(!t)throw new Error(`Native Supervisor state is missing for ${e.parent}`);let r=e.maxParallel??2;if(!Number.isSafeInteger(r)||r<1)throw new Error("Native Supervisor maxParallel must be a positive integer");let i=t.children.filter(({task:l})=>l!==null).length,n=Math.max(0,r-i);if(n===0)return{state:t,tasks:[]};let a=await Ne(e.paths.projectRoot),o=t,s=[],c=!1;for(let l of t.children){if(s.length>=n)break;if(l.task!==null)continue;let f=l.status==="needs-reverify"&&l.candidateCommit!==null;if(l.status!=="ready"&&!f)continue;let u;try{u=await lE({projectRoot:e.paths.projectRoot,parent:t.parent,child:l.name,targetBranch:t.integration.branch,sourceConfig:a}),f?mE(u.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,l.candidateCommit):hE(u.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,t.integration.headCommit)}catch(m){let v=ze(o),h=v.children.find(({name:p})=>p===l.name);h&&(h.blocker=m.message,it(v,{kind:"task-blocked",child:l.name,runId:null,summary:h.blocker}),v.stateVersion+=1,o=v,c=!0);continue}let d=cl(o,{role:f?"verifier":"builder",child:l.name,projectRoot:u.projectRoot,runId:sE()});o=d.state,s.push(d.task)}return(s.length>0||c)&&await ne(e.paths,o),{state:o,tasks:s}})}function hh(e,t){Vt(t.candidateCommit,"Native Supervisor candidate commit");let r=ze(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(!i.task||i.task.role!=="builder"||i.task.runId!==t.runId)throw new Error(`Native Supervisor Builder result runId is not current for ${t.child}`);if(i.status!=="active")throw new Error(`Native Supervisor child ${t.child} is not active for Builder result`);return i.candidateCommit=t.candidateCommit,i.task=null,i.blocker=null,it(r,{kind:"builder-result",child:i.name,runId:t.runId,summary:"Builder candidate recorded"}),r.stateVersion+=1,r}function mh(e,t){if(t.evidence.summary.trim().length===0)throw new Error("Native Supervisor verification summary must not be empty");if(t.verdict==="pass"&&t.evidence.checks.length===0)throw new Error("Native Supervisor verification pass requires at least one check");let r=ze(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(!i.task||i.task.role!=="verifier"||i.task.runId!==t.runId)throw new Error(`Native Supervisor Verifier result runId is not current for ${t.child}`);if(i.status!=="active"&&i.status!=="needs-reverify"||!i.candidateCommit)throw new Error(`Native Supervisor child ${t.child} is not ready for Verifier result`);return i.verification={summary:t.evidence.summary,checks:[...t.evidence.checks]},i.task=null,t.verdict==="pass"?(i.status="verified",i.verifiedCommit=i.candidateCommit,i.blocker=null):(i.status="needs-reverify",i.blocker=t.evidence.summary),it(r,{kind:"verifier-result",child:i.name,runId:t.runId,summary:t.evidence.summary}),r.stateVersion+=1,r}function vE(e,t){Vt(t.integrationCommit,"Native Supervisor integration commit");let r=ze(e),i=r.children.find(({name:n})=>n===t.name);if(!i)throw new Error(`Native Supervisor child ${t.name} does not exist`);if(i.status!=="verified"||!i.verifiedCommit)throw new Error(`Native Supervisor child ${t.name} must be verified before integration`);if(t.checks.length===0||t.checks.some(({status:n})=>n!=="passed"))throw new Error(`Native Supervisor child ${t.name} integration checks are incomplete`);i.status="integrated",i.integrationCommit=t.integrationCommit,i.checks=structuredClone(t.checks),i.blocker=null,r.integration.headCommit=t.integrationCommit,it(r,{kind:"child-integrated",child:i.name,runId:null,summary:"Child integrated into the Supervisor branch"});for(let n of r.children)n.status==="pending"&&n.dependsOn.every(a=>r.children.some(({name:o,status:s})=>o===a&&s==="integrated"))&&(n.status="ready");return r.stateVersion+=1,r}async function vh(e){return x(e.paths,`integrate Native Supervisor child ${e.name}`,async()=>{let r=await W(e.paths,e.state.parent)??e.state;if(r.stateVersion!==e.state.stateVersion)throw new Error("Native Supervisor state changed before integration; reload status first");let i=r.children.find(({name:c})=>c===e.name);if(!i)throw new Error(`Native Supervisor child ${e.name} does not exist`);let n=fE(r).find(({status:c})=>c!=="integrated"&&c!=="archived");if(n&&n.name!==e.name)throw new Error(`Native Supervisor integration order requires ${n.name} before ${e.name}`);if(i.status!=="verified"||!i.verifiedCommit)throw new Error(`Native Supervisor child ${e.name} must be verified before integration`);let a=ll(r);if(a!==r.integration.headCommit){let c=(()=>{try{return I(r.integration.worktree,["merge-base","--is-ancestor",r.integration.headCommit,a]),!0}catch{return!1}})(),l=(()=>{try{return I(r.integration.worktree,["merge-base","--is-ancestor",i.verifiedCommit,a]),!0}catch{return!1}})();if(!c||!l)throw new Error(`Native Supervisor integration head drifted: expected ${r.integration.headCommit}, got ${a}`)}try{I(r.integration.worktree,["cat-file","-e",`${i.verifiedCommit}^{commit}`])}catch(c){throw new Error(`Native Supervisor verified commit is unavailable: ${i.verifiedCommit}`,{cause:c})}if(a===r.integration.headCommit){try{I(r.integration.worktree,["merge","--no-ff","--no-edit",i.verifiedCommit])}catch(c){throw new Error(`Native Supervisor integration conflict preserved in ${r.integration.worktree}`,{cause:c})}a=I(r.integration.worktree,["rev-parse","HEAD"])}let o=a,s=vE(r,{name:e.name,integrationCommit:o,checks:e.checks});return await ne(e.paths,s),s})}function gE(e,t){if(Vt(t.headCommit,"Native Supervisor final verification head commit"),t.summary.trim().length===0)throw new Error("Native Supervisor final verification summary must not be empty");let r=ze(e);if(t.headCommit!==r.integration.headCommit)throw new Error("Native Supervisor final verification head is stale");if(t.status==="passed"){if(r.children.some(({status:i})=>i!=="integrated"))throw new Error("Native Supervisor cannot pass final verification before all children integrate");if(t.layers.parentChecks.length===0)throw new Error("Native Supervisor parent verification requires executed parent checks");if(t.layers.childVerification!=="complete"||t.layers.parentIntegration!=="complete"||t.layers.incomplete.length>0)throw new Error("Native Supervisor final verification evidence is incomplete")}return r.finalVerification={status:t.status,summary:t.summary,layers:{childVerification:t.layers.childVerification,parentIntegration:t.layers.parentIntegration,parentChecks:[...t.layers.parentChecks],notRerun:[...t.layers.notRerun],incomplete:[...t.layers.incomplete]}},r.stateVersion+=1,r}function Yi(e){let t=ll(e);if(t===e.integration.headCommit)return e;try{I(e.integration.worktree,["merge-base","--is-ancestor",e.integration.headCommit,t])}catch{throw new Error("Native Supervisor integration head is not a descendant of the recorded integration head")}let r=ze(e);return r.integration.headCommit=t,it(r,{kind:"integration-head-reconciled",child:null,runId:null,summary:"Parent-level commits were included in final verification"}),r.stateVersion+=1,r}function Xi(e,t){let r=t.verification;if(r===null||t.verification_result==="pending")throw new Error("Native Supervisor final verification has no persisted Portable result");let i=ll(e),n=e.children.every(({status:o,verification:s})=>(o==="integrated"||o==="archived")&&s!==null),a=r.checks.length>0&&r.checks.every(({status:o})=>o==="passed");return gE(e,{status:t.verification_result==="pass"?"passed":t.verification_result==="blocked"?"incomplete":"failed",summary:r.summary.text,headCommit:i,layers:{childVerification:n?"complete":"incomplete",parentIntegration:a?"complete":"incomplete",parentChecks:r.checks.map(({name:o})=>o.text),notRerun:e.children.flatMap(({verification:o})=>o?.checks??[]),incomplete:r.checks.filter(({status:o})=>o!=="passed").map(({name:o})=>o.text)}})}function gh(e){let t=e.children.map(r=>({name:r.name,summary:r.summary,dependsOn:[...r.dependsOn],covers:[],status:r.status,phase:null,projectRoot:r.projectRoot??r.task?.projectRoot??null,message:r.blocker}));return{contractHash:null,confirmed:!0,parentBranch:e.integration.branch,children:t,readyChildren:t.filter(({status:r})=>r==="ready").map(({name:r})=>r),allDone:t.every(({status:r})=>r==="integrated"||r==="archived")}}var wh="children.yaml",Qi="comet.native.children.v1",Vr="comet.native.children.v2",Ch=Vr,wE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,yh=new Set(["schema","children"]),yE=new Set(["schema","acceptance_index","children"]),NE=new Set(["name","depends_on","covers"]),bE=new Set(["name","summary","depends_on"]),kE=new Set(["name","depends_on","covers"]);function co(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function so(e,t,r){let i=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(i.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...i.length>0?[`unexpected ${i.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${r} fields are invalid: ${a.join("; ")}`)}}function Nh(e,t){if(!Array.isArray(e)||!e.every(r=>typeof r=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((r,i)=>r.localeCompare(i,"en"))}function dl(e,t){let r=Te.normalize(Te.resolve(e)),i=Te.normalize(Te.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function SE(e){let t=new Map(e.map(a=>[a.name,a])),r=new Set,i=new Set,n=a=>{if(!i.has(a)){if(r.has(a))throw new Error(`Native children dependency cycle includes ${a}`);r.add(a);for(let o of t.get(a).depends_on)n(o);r.delete(a),i.add(a)}};for(let a of e)n(a.name)}function bh(e,t,r=t){let i=new Set(t);for(let o of e){let s=o.covers.filter(c=>!i.has(c));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=r.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function EE(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===Ch&&e.acceptance_index){let n=r.requiredAcceptanceIds??t??[],a=r.allowedAcceptanceIds??n,o=Object.keys(e.acceptance_index);i.missing=n.filter(l=>!(l in e.acceptance_index)),i.extra=o.filter(l=>!a.includes(l));let s=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of o){let f=s.get(l),u=e.acceptance_index[l];f&&u&&(u.source!==f.source||u.text!==f.text)&&i.mismatched.push(l)}let c=new Set(o);for(let l of e.children)i.unknownCovers.push(...l.covers.filter(f=>!c.has(f)));return i.uncovered=o.filter(l=>!kh(e.children,l)),Sh(i)?i:null}if(e.schema===Qi&&t){let n=new Set(t);for(let a of e.children)i.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return i.uncovered=t.filter(a=>!kh(e.children,a)),Sh(i)?i:null}return null}function kh(e,t){return e.some(r=>r.covers.includes(t))}function Sh(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function Mr(e){let t=new Set(e.acceptance.map(({id:n})=>n)),r=new Set(e.acceptance.filter(({source:n})=>n===e.brief).map(({id:n})=>n)),i=new Set(r);for(let n of e.history.filter(({outcome:a})=>a==="fail"))for(let a of n.unresolved_ids)t.has(a)&&i.add(a);if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let n=[...e.history].reverse().find(({outcome:a})=>a==="fail");for(let a of n?.unresolved_ids??[])r.add(a)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...r],allowedAcceptanceIds:[...i]}}function xE(e){let t=co(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),r={};for(let[i,n]of Object.entries(t)){let a=co(n,`Native children acceptance_index.${i}`);if(so(a,new Set(["source","text"]),`Native children acceptance_index.${i}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${i}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${i}.text must be a non-empty string`);r[i]={source:a.source,text:a.text}}return r}function CE(e,t,r){let i=r.requiredAcceptanceIds??t??[],n=r.allowedAcceptanceIds??i,a=Object.keys(e),o=i.filter(l=>!(l in e)),s=a.filter(l=>!n.includes(l));if(o.length>0||s.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${o.join(", ")||"none"}; extra ${s.join(", ")||"none"}`);let c=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of a){let f=c.get(l);if(!f)continue;let u=e[l];if(u.source!==f.source||u.text!==f.text){let d=["source","text"].filter(m=>u[m]!==f[m]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${d.join(", ")} exactly from the current acceptance catalog`)}}}function PE(e,t,r={}){let i=(0,fl.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=co(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==Qi&&a!==Vr)throw so(n,yh,"Native children contract"),new Error(`Native children schema must be ${Qi} or ${Vr}`);let o=a===Qi?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(so(n,o==="indexed-v2"?yE:yh,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let c=n.children.map((d,m)=>{let v=co(d,`Native child ${m}`);if(so(v,o==="indexed-v2"?kE:o==="summary-v2"?bE:NE,`Native ${s} child fields (child ${m})`),typeof v.name!="string"||!wE.test(v.name))throw new Error(`Native child ${m} 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:Nh(v.depends_on,`Native child ${v.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?Nh(v.covers,`Native child ${v.name} covers`):[]}}),l=c.map(({name:d})=>d);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let f=new Set(l);for(let d of c){let m=d.depends_on.filter(v=>!f.has(v));if(m.length>0)throw new Error(`Native child ${d.name} depends on unknown child: ${m.join(", ")}`)}SE(c);let u=r.policy==="advisory";if(a===Ch){if(o==="indexed-v2"){let d=xE(n.acceptance_index);u||CE(d,t,r);let m=Object.keys(d);return u||bh(c,m,m),{schema:Vr,acceptance_index:d,children:c}}return{schema:Vr,children:c}}return t&&!u&&bh(c,t),{schema:Qi,children:c}}async function Mt(e){let t=Te.join(e.changeDir,wh);try{await xh.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await Y({root:e.changeDir,ref:wh}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=PE(r.text,e.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?EE(a,e.acceptanceIds,e.validation??{}):null}}function RE(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let r=e.slice(t.index+t[0].length);return r.split(/^#\s+/mu,1)[0]??r}function AE(e){let t=RE(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let r=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),i=t.match(/\bChild\s+\d+\b/giu);return Math.max(r?.length??0,i?.length??0)>=2}async function lo(e){try{let t=await Y({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return AE(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Zi(e){return X("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:r,text:i})=>({id:t,source:r,text:i})),children:e.children})}async function _E(e){let t=Zt(e.projectRoot);t.some(i=>dl(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>Te.resolve(n)))]){let n=await Ne(i);n&&r.push({projectRoot:i,paths:await Dt(i,n.native.artifact_root),parent:dl(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function IE(e,t){let r=Te.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Me(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function TE(e,t){let r;try{r=await xh.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=Te.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await Me(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function jE(e,t,r){let i=Te.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${Te.sep}`))return null;let n=i.split(Te.sep).join("/");try{let a=(0,fl.parseDocument)(I(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:C(a.toJS({mapAsMap:!1}))}catch{return null}}function $E(e,t,r){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==r||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${r??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function Eh(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function nt(e){let t=Te.join(e.paths.changesDir,e.state.name),r=await lo(t),i=await Mt({changeDir:t,validation:Mr(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:p})=>p)}:{},policy:"advisory"});if(!i)return e.state.children_contract_hash?{...r?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:r?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null;let n=Zi({acceptance:e.state.acceptance,children:i.contract}),a=e.state.workspace.change_branch,o=e.state.phase!=="shape"&&e.state.children_contract_hash===n&&!i.drift;if(i.contract.schema===Vr){let p=await W(e.paths,e.state.name);if(!p){let y=e.state.workspace.target_branch??e.state.workspace.change_branch;if(y){let b=await ao({paths:e.paths,parent:e.state.name,targetBranch:y,contract:i.contract});b&&(p=b,await ne(e.paths,b))}}if(p){let y=gh(p);return e.state.children_contract_hash!==n||i.drift?{...y,schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:!1,readyChildren:[],allDone:!1,children:y.children.map(b=>({...b,message:i.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...y,schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o}}let w=new Map(i.contract.children.map(y=>[y.name,y])),g=i.contract.children.map(y=>({name:y.name,summary:y.summary,dependsOn:[...y.depends_on],covers:[],status:o&&y.depends_on.every(b=>i.contract.children.filter(({name:N})=>N!==y.name).every(({name:N})=>N!==b))?"ready":"pending",phase:null,projectRoot:null,message:o?null:"Parent Shape confirmation is required"}));for(let y of g){if(y.status!=="ready")continue;w.get(y.name).depends_on.length>0&&(y.status="pending")}return{schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:g,readyChildren:g.filter(({status:y})=>y==="ready").map(({name:y})=>y),allDone:!1}}let s=await _E(e.paths),c=new Set(i.contract.children.map(({name:p})=>p)),l=new Map,f=new Map;for(let p of s){let w=p.parent&&a?`refs/heads/${a}`:"HEAD";for(let g of await TE(p,c)){let y={...g,source:p,committedState:jE(p,g.file,w)};l.set(g.state.name,[...l.get(g.state.name)??[],y])}for(let g of c){let y=await IE(p,g);y&&f.set(g,[...f.get(g)??[],{source:p,state:y}])}}let u=new Map;for(let p of i.contract.children){let w=(l.get(p.name)??[]).find(({source:b,committedState:N})=>b.parent&&N?.name===p.name&&Eh(N,a));if(w){u.set(p.name,{kind:"done",phase:w.state.phase,projectRoot:w.source.projectRoot,message:null});continue}let g=l.get(p.name)?.[0];if(g){u.set(p.name,{kind:"blocked",phase:g.state.phase,projectRoot:g.source.projectRoot,message:`Native child ${p.name} is archived but not merged into parent branch ${a??"(missing)"}`});continue}let y=f.get(p.name)??[];y.length>1?u.set(p.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${p.name} has multiple active workspace owners`}):y[0]&&u.set(p.name,$E(y[0].state,y[0].source,a))}let d=new Map(i.contract.children.map(p=>[p.name,p])),m=new Map,v=p=>{let w=m.get(p);if(w)return w;let g=d.get(p),b=g.depends_on.map(v).every(({status:F})=>F==="done"),N=u.get(p),E=N?.kind==="active"&&b?g.depends_on.filter(F=>!(l.get(F)??[]).some(({source:ee,committedState:j})=>dl(ee.projectRoot,N.projectRoot)&&j?.name===F&&Eh(j,a))):[],P,k=N?.message??null;N?.kind==="done"?(P=b?"done":"blocked",b||(k=`Native child ${p} was merged before its dependencies`)):N?.kind==="active"?(P=b&&E.length===0?"active":"blocked",b?E.length>0&&(k=`Native child ${p} does not include merged dependencies: ${E.join(", ")}`):k=`Native child ${p} started before its dependencies merged`):N?.kind==="blocked"?P="blocked":(P=o&&b?"ready":"pending",o||(k="Parent Shape confirmation is required"));let T={name:p,summary:g.summary,dependsOn:[...g.depends_on],covers:[...g.covers],status:P,phase:N?.phase??null,projectRoot:N?.projectRoot??null,message:k};return m.set(p,T),T},h=i.contract.children.map(({name:p})=>v(p));return{schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:h,readyChildren:h.filter(({status:p})=>p==="ready").map(({name:p})=>p),allDone:h.every(({status:p})=>p==="done")}}function ht(e,t,r){return e.language==="zh-CN"?r:t}function OE(e,t){let r=i=>({required:!1,message:null,suggestedReply:null,agentInstruction:i});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:ht(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:ht(e,"Reply A or B","回复 A 或 B"),agentInstruction:ht(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 r(ht(e,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result")return r(ht(e,"Wait only while the dispatched Verifier task is still active. If the task did not start, failed, timed out, ended without a response, or was lost, immediately submit verifier-execution-error. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","仅在已派发的独立验收任务仍在运行时等待。如果任务未启动、执行失败、超时、结束后没有返回结果或已经丢失,立即提交 verifier-execution-error;只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。"));if(e.status==="blocked"&&e.blockers.some(({resolution_action:i})=>i==="retry-verifier"))return e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable")return e.language==="zh-CN"?{required:!0,message:"独立验收当前不可用,但你的代码和已经完成的检查都已安全保留。你可以直接重新尝试独立验收,也可以明确接受只有自动检查的结果。",suggestedReply:"重新尝试独立验收",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户选择。用户要求重试时执行 commandAlternatives 中的 retry-verifier;只有用户明确接受降级结果时才执行 confirm-verifier-unavailable。不要把“继续”视为接受降级结果,也不要要求用户处理文件、进程、服务或回调。"}:{required:!0,message:"Independent verification is currently unavailable, but your code and completed checks are safely preserved. You can retry independent verification directly or explicitly accept the automatic-check-only result.",suggestedReply:"Retry independent verification",agentInstruction:"Relay only message and suggestedReply, then wait for the user choice. If the user asks to retry, run retry-verifier from commandAlternatives; run confirm-verifier-unavailable only when the user explicitly accepts the degraded result. Do not treat “Continue” as accepting the degraded result, and do not ask the user to manage files, processes, services, or callbacks."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="resolve-verifier-blocker")return e.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="await-user"){let n=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",a=n?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。",o=n?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return e.language==="zh-CN"?{required:!0,message:a,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:o,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}return r(ht(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 HE(e){let t=e.workspace.change_branch??"<change-branch>",r=e.workspace.target_branch??"<target-branch>";return e.language==="zh-CN"?{required:!0,message:`当前 change 位于 ${t},目标分支为 ${r}。请选择一次工作区收尾方式:A) 保留工作区;B) 本地合并;C) 推送分支;D) 推送并创建 PR;E) 暂不归档。选择 A-D 后 Runtime 会先执行完整 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 ${r}. Choose one workspace finish: A) keep the workspace; B) merge locally; C) push the branch; D) push and create a PR; or E) defer Archive. For A-D, Runtime will run 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 DE(e){return[...[{finish:"keep",name:"keep-workspace",description:["保留当前分支和目录;完成归档提交,不合并、不推送、不创建 PR。","Keep the current branch and directory; create the archive commit without merging, pushing, or creating a PR."]},{finish:"merge",name:"merge-locally",description:["完成归档提交,并把 change 分支本地合并到目标分支;不推送、不创建 PR。","Create the archive commit and merge the change branch locally into the target branch without pushing or creating a PR."]},{finish:"push",name:"push-branch",description:["完成归档提交并推送 change 分支;不合并到目标分支、不创建 PR。","Create the archive commit and push the change branch without merging into the target branch or creating a PR."]},{finish:"pull-request",name:"push-pull-request",description:["完成归档提交、推送 change 分支,并以目标分支为基础创建 PR。","Create the archive commit, push the change branch, and create a PR against the target branch."]}].map(({finish:i,name:n,description:a})=>({name:n,stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","archive",e.name,"--dry-run","--finish",i],requiredInputs:[],inputOptions:[],description:ht(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:ht(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function Rh(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Fr(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function BE(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function Ph(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function LE(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function VE(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 Ft(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:Rh({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Fr("summary","--summary"),BE(e.name,e.flag)]}}function pl(e){return[Ft({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Ft({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function Q(e,t,r={}){let i=LE(t)&&e.coordination_mode===void 0,n=OE(e,i),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:[Fr("summary","--summary")],commandAlternatives:[Ft({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:[Fr("summary","--summary")],commandAlternatives:[Ft({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...pl({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:[Fr("summary","--summary")],commandAlternatives:[Ft({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),Ft({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:[Fr("summary","--summary")],commandAlternatives:[Ft({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...pl({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:[Fr("summary","--summary")],commandAlternatives:pl({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?Rh({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:i?"await-user":"continue",action:"prepare-shape-confirmation",commandArgs:VE({change:e.name,stateVersion:e.state_version,coordinationRequired:i}),requiredInputs:["summary",...i?["coordination-choice"]:[]],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},...i?[Ph("coordination-mode","--coordination-mode",Ta)]:[]],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} ${ht(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=r.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"?r.archiveBlockers&&r.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:[Ph("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...DE(e)],userCommunication:HE(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[Ft({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{randomUUID as Lx}from"node:crypto";import{promises as ln}from"node:fs";import Vx from"node:path";import{randomUUID as Il}from"node:crypto";import{promises as lr}from"node:fs";import oe from"node:path";var FE=["outcome","scope","nonGoals","acceptanceExamples"],f$=[...FE,"constraints","decisions","openQuestions","verificationExpectations"];function Ah(e){let t=new Set(["blocker","blocking","coverage","decision","open_question","question","requirement","requirements","source","source_coverage","state","status","决策","来源","覆盖","问题","状态","需求","阻塞"]),r=null;for(let i of e.split(/\r?\n/u)){let n=i.match(/^\s*(`{3,}|~{3,})/u);if(n){let s=n[1]?.[0];r===null?r=s:r===s&&(r=null);continue}if(r!==null)continue;let a=i.trim();if(/^(?:[-*+]\s+|\d+[.)]\s+)(?:\[[ xX]\]\s+)?\[blocking\](?=$|[\s::—-])/iu.test(a)||a.includes("|")&&a.split("|").some(s=>/^\s*\[blocking\](?=$|[\s::—-])/iu.test(s)))return!0;let o=a.match(/^([\p{L}\p{N}_./-]+)\s*[::]\s*\[blocking\](?=$|[\s::—-])/iu);if(o){let s=o[1]?.toLocaleLowerCase("en-US")??"";if(t.has(s)||/[./_-]/u.test(s))return!0}}return!1}import{createWriteStream as lx,promises as ux}from"node:fs";import Se from"node:path";import{spawn as hl}from"node:child_process";import{existsSync as _h}from"node:fs";import sr from"node:path";var qE=new Set([".bat",".cmd",".ps1"]),WE=new Set([".bat",".cmd"]),zE=/[&|<>()^%"!\r\n]/u,JE=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");function ml(e,t){let r=t.toLowerCase();return Object.entries(e).find(([i,n])=>i.toLowerCase()===r&&n!==void 0)?.[1]}function GE(e){let t=(ml(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function UE(e,t,r){let n=sr.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(ml(t,"PATH")??"").split(sr.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=sr.win32.extname(e)?[e]:GE(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(c=>s?sr.join(s,c):sr.resolve(r,c)))}function KE(e,t,r){return UE(e,t,r).find(i=>_h(i))??e}function YE(e){let t=ml(e,"SystemRoot");if(t){let r=sr.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe");if(_h(r))return r}return"powershell.exe"}function XE(e){if(e.some(t=>zE.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}function QE(e,t,r){let i=Buffer.from(JSON.stringify({command:e,arguments:[...t]}),"utf8").toString("base64"),n=Buffer.from(JE,"utf16le").toString("base64");return hl(YE(r.env),["-NoLogo","-NoProfile","-NonInteractive","-InputFormat","None","-OutputFormat","Text","-ExecutionPolicy","Bypass","-EncodedCommand",n],{cwd:r.cwd,env:{...r.env,COMET_COMMAND_PAYLOAD:i},shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}function vl(e,t,r){let i=r.env??process.env;if(process.platform!=="win32")return hl(e,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});let n=KE(e,i,r.cwd),a=sr.win32.extname(n).toLowerCase();return WE.has(a)&&XE(t),qE.has(a)?QE(n,t,{cwd:r.cwd,env:i}):hl(n,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}import{spawn as ZE}from"node:child_process";import gl from"node:path";var ex=1e3,tx=2;async function uo(e){let t=e.pid;if(t===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let r=process.env.SystemRoot??process.env.WINDIR,i=r&&gl.win32.isAbsolute(r)?gl.win32.resolve(r):"C:\\Windows",n=gl.win32.join(i,"System32","taskkill.exe"),a=()=>new Promise(o=>{let s=!1,c=null,l=null,f=(u,d=!1)=>{s||(s=!0,l&&clearTimeout(l),d&&c?.kill("SIGKILL"),o(u))};try{c=ZE(n,["/pid",String(t),"/t","/f"],{stdio:"ignore",windowsHide:!0}),c.once("error",()=>f(!1)),c.once("close",u=>f(u===0)),l=setTimeout(()=>f(!1,!0),ex)}catch{f(!1)}});for(let o=0;o<tx;o+=1)if(await a()){e.kill("SIGKILL");return}e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy();return}try{process.kill(-t,"SIGKILL")}catch(r){if(r.code!=="ESRCH")throw r}e.kill("SIGKILL")}var rx=/\b(Bearer|Basic)\s+[^\s"']+/giu,ix=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,nx=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,ax=/\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,ox=/("(?:[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,sx=/(["'])((?:[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,cx=/\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 qt(e){return e.replace(rx,"$1 [REDACTED]").replace(ix,"[REDACTED PRIVATE KEY]").replace(nx,"$1[REDACTED]@").replace(ax,"[REDACTED TOKEN]").replace(ox,'$1"[REDACTED]"').replace(sx,"$1$2$1$3$4[REDACTED]$4").replace(cx,"$1$2[REDACTED]")}function Ih(e,t){let r=Se.relative(e,t);return r===""||!Se.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Se.sep}`)}function Th(e,t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(e))throw new Error(`${t} is invalid`);return e}function fo(e,t){if(t.length===0||t.includes("\\")||Se.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||Se.posix.normalize(t)!==t)throw new Error("Native check cwd must be a normalized project-relative ref");let r=Se.resolve(e),i=Se.resolve(r,...t.split("/"));if(!Ih(r,i))throw new Error("Native check cwd escaped the project root");return i}function en(e){return JSON.stringify([e.executable,e.argv,e.cwdRef.replaceAll("\\","/"),e.timeoutMs,e.repeatable])}var dx=/^(?:-p|-u|--(?:[a-z0-9]+[-_])*(?:api[-_]?key|access[-_]?token|auth[-_]?token|client[-_]?secret|secret(?:[-_]?access)?[-_]?key|private[-_]?key|token|password|passwd|secret|authorization|cookie|set[-_]?cookie|user))$/iu;function wl(e){let t=!1;return e.map(r=>{if(t)return t=!1,"[REDACTED]";let i=qt(r);return dx.test(r)&&(t=!0),i})}function po(e,t){if(Th(t.id,"Native check ID"),t.name.trim().length===0||t.executable.trim().length===0)throw new Error("Native check name and executable must be non-empty");if(!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<1)throw new Error("Native check timeout must be a positive integer");return fo(e,t.cwdRef)}async function yl(e){let{plan:t}=e;Th(e.operationId,"Native check operation ID");let r=po(e.projectRoot,t),i=Se.join(e.runtimeDir,"logs","checks"),n=Se.join(i,`${e.operationId}-${t.id}.log`);if(!Ih(Se.resolve(e.runtimeDir),Se.resolve(n)))throw new Error("Native check log path escaped the Runtime root");await ux.mkdir(i,{recursive:!0});let a=(e.now??(()=>new Date))(),o=lx(n,{flags:"wx"});return new Promise((s,c)=>{let l;try{l=vl(t.executable,t.argv,{cwd:r,env:process.env})}catch(m){o.destroy(),c(m);return}let f=!1,u=null,d=setTimeout(()=>{f=!0,uo(l).catch(()=>l.kill("SIGKILL"))},t.timeoutMs);d.unref?.(),l.stdout.pipe(o,{end:!1}),l.stderr.pipe(o,{end:!1}),l.once("error",m=>{u=m,o.write(`
182
182
  [comet] failed to start check: ${qt(m.message)}
183
- `)}),l.once("close",(m,v)=>{clearTimeout(d);let h=(e.now??(()=>new Date))();o.end(()=>{let p=f||u!==null||v!==null;s({id:t.id,name:t.name,argvDisplay:wl(t.argv),cwdRef:t.cwdRef,status:p?"interrupted":m===0?"passed":"failed",exitCode:m,signal:v,timedOut:f,durationMs:Math.max(0,h.getTime()-a.getTime()),startedAt:a.toISOString(),completedAt:h.toISOString(),repeatable:t.repeatable,logRef:Se.relative(e.runtimeDir,n).split(Se.sep).join("/")})})}),o.once("error",m=>{clearTimeout(d),uo(l).catch(()=>l.kill("SIGKILL")),c(m)})})}import{randomUUID as px}from"node:crypto";var jh=Symbol("comet.native.trusted-execution-identity"),$h=Symbol("comet.native.trusted-verifier-envelope"),Z="skill-coordinated";function Nl(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} is invalid`);return e}function bl(){let e=new WeakSet;return Object.freeze({captureExecutionIdentity(t){Nl(t.identityProvider,"Native identity provider");let r=Object.freeze({identityProvider:Z,executionRef:Nl(t.executionRef,"Native execution ref"),[jh]:!0});return e.add(r),r},envelopeVerifierResponse(t){if(!e.has(t.identity))throw new Error("Native execution identity was not captured by this Runner channel");return Object.freeze({candidateId:Nl(t.candidateId,"Native candidate ID"),identityProvider:t.identity.identityProvider,verifierExecutionRef:t.identity.executionRef,payload:t.payload,[$h]:!0})}})}function ho(e){return typeof e=="object"&&e!==null&&e[$h]===!0}function Oh(e){return typeof e=="object"&&e!==null&&e[jh]===!0}function mo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function tn(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function rn(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function cr(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be non-empty text`);return e}function ux(e){if(!Array.isArray(e))throw new Error("Native Verifier acceptance must be an array");return e.map((t,r)=>{let i=mo(t,`Native Verifier acceptance ${r}`);tn(i,["id","result","reason"],`Native Verifier acceptance ${r}`);let n=cr(i.id,`Native Verifier acceptance ${r} ID`);if(!["passed","failed","blocked"].includes(String(i.result)))throw new Error(`Native Verifier acceptance ${n} result is invalid`);return{id:n,result:i.result,reason:cr(i.reason,`Native Verifier acceptance ${n} reason`)}})}function dx(e){let t=mo(e,"Native Verifier final result");if(tn(t,["iteration","attempt","verdict","acceptance","risks","summary"],"Native Verifier final result"),!["pass","fail","blocked"].includes(String(t.verdict)))throw new Error("Native Verifier verdict is invalid");if(!Array.isArray(t.risks)||!t.risks.every(r=>typeof r=="string"))throw new Error("Native Verifier risks must be text entries");return{iteration:rn(t.iteration,"Native Verifier iteration"),attempt:rn(t.attempt,"Native Verifier attempt"),verdict:t.verdict,acceptance:ux(t.acceptance),risks:t.risks,summary:cr(t.summary,"Native Verifier summary")}}function fx(e,t){let r=mo(e,`Native Verifier check request ${t}`);if(tn(r,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Verifier check request ${t}`),!Array.isArray(r.argv)||!r.argv.every(n=>typeof n=="string"))throw new Error(`Native Verifier check request ${t} argv is invalid`);if(typeof r.repeatable!="boolean")throw new Error(`Native Verifier check request ${t} repeatable is invalid`);let i=rn(r.timeoutMs,`Native Verifier check request ${t} timeout`);if(i<1)throw new Error("Native Verifier check timeout must be positive");return{id:cr(r.id,`Native Verifier check request ${t} ID`),name:cr(r.name,`Native Verifier check request ${t} name`),executable:cr(r.executable,`Native Verifier check request ${t} executable`),argv:r.argv,cwdRef:cr(r.cwdRef,`Native Verifier check request ${t} cwd`),timeoutMs:i,repeatable:r.repeatable}}function kl(e){let t=mo(e,"Native Verifier response");if(t.kind==="final-result")return tn(t,["kind","result"],"Native Verifier response"),{kind:"final-result",result:dx(t.result)};if(t.kind==="request-checks"){if(tn(t,["kind","iteration","attempt","checks"],"Native Verifier response"),!Array.isArray(t.checks)||t.checks.length===0)throw new Error("Native Verifier check request batch must be non-empty");return{kind:"request-checks",iteration:rn(t.iteration,"Native Verifier iteration"),attempt:rn(t.attempt,"Native Verifier attempt"),checks:t.checks.map(fx)}}throw new Error("Native Verifier response kind is invalid")}function Hh(e){if(!ho(e.envelope))throw new Error("Native Verifier result must come from the trusted Runner channel");let{envelope:t,binding:r}=e;if(t.candidateId!==r.candidateId)throw new Error("Native Verifier result does not match the current candidate");if(t.identityProvider!==r.identityProvider)throw new Error("Native Verifier identity provider does not match the Builder provider");if(t.verifierExecutionRef===r.builderExecutionRef)throw new Error("Native Builder and Verifier must be different executions");let i=kl(t.payload),n=i.kind==="final-result"?i.result.iteration:i.iteration,a=i.kind==="final-result"?i.result.attempt:i.attempt;if(n!==r.iteration||a!==r.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");if(i.kind==="request-checks")return i;let o=[...r.acceptanceIds],s=i.result.acceptance.map(({id:d})=>d),c=s.filter((d,m)=>s.indexOf(d)!==m),l=s.filter(d=>!o.includes(d)),f=o.filter(d=>!s.includes(d));if(c.length>0||l.length>0||f.length>0)throw new Error(`Native Verifier acceptance coverage is invalid (duplicate: ${[...new Set(c)].join(", ")||"none"}; unknown: ${l.join(", ")||"none"}; missing: ${f.join(", ")||"none"})`);if(!r.requiredChecksPassed&&i.result.verdict==="pass")throw new Error("Native verification cannot pass before every required check succeeds");let u=i.result.acceptance.map(({result:d})=>d);if(i.result.verdict==="pass"&&u.some(d=>d!=="passed"))throw new Error("Native pass requires every acceptance criterion to pass");if(i.result.verdict==="fail"&&!u.includes("failed"))throw new Error("Native fail requires at least one failed acceptance criterion");if(i.result.verdict==="blocked"&&!u.includes("blocked"))throw new Error("Native blocked verdict requires at least one blocked acceptance criterion");return i}var nn=3,Sl=2;function he(e){return e.state_version+1}function hx(e,t,r){let i=[...e];if(new Set(i).size!==i.length)throw new Error(`${r} contains duplicate IDs`);let n=new Set(t.map(({id:o})=>o)),a=i.filter(o=>!n.has(o));if(a.length>0)throw new Error(`${r} contains unknown IDs: ${a.join(", ")}`);return i}function El(e){return e.map(t=>({...t,result:"pending",reason:null}))}function xl(e){return e.acceptance.filter(({result:t})=>t==="pending").map(({id:t})=>t)}function mx(e){return(e??[]).map(t=>({name:H(t.name),result:t.result,note:t.note?H(t.note):null}))}function mt(e){return{goal_cycle:e.state.loop.goal_cycle,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,outcome:e.outcome,unresolved_ids:e.unresolvedIds??[],summary:H(e.summary),completed_at:e.completedAt}}function Dh(e){let t=C(e.state);if(t.phase!=="shape"||t.status!=="await-user"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-shape")throw new Error("Native acceptance can only be confirmed from the persisted Shape confirmation boundary");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let r=e.acceptance.map(({id:i})=>i);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return C({...t,phase:"build",status:"active",state_version:he(t),loop:{...t.loop,stage:"building",iteration:1,attempt:0,next_action:"submit-builder-candidate"},acceptance:e.acceptance.map(i=>({...i,result:"pending",reason:null}))})}function Bh(e){let t=C(e.state);if(t.phase!=="shape"||t.status!=="active"||t.loop.stage!=="shape")throw new Error("Native Shape confirmation can only be prepared from active Shape");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let r=e.acceptance.map(({id:i})=>i);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return C({...t,status:"await-user",state_version:he(t),loop:{...t.loop,stage:"await-user",next_action:"confirm-shape"},acceptance:e.acceptance.map(i=>({...i,result:"pending",reason:null}))})}function Lh(e){let t=C(e.state),{input:r}=e;if(t.phase!=="build"||t.status!=="active")throw new Error("Native candidate can only be submitted from active Build");if(!Oh(r.identity))throw new Error("Native Builder identity must come from the trusted Runner channel");if(!r.review||r.review.status!=="passed")throw new Error("Native Builder candidate requires a passed read-only review");if(r.review.reviewerExecutionRef===r.identity.executionRef)throw new Error("Native reviewer execution ref must differ from the Builder execution ref");if(t.loop.stage==="repairing"&&t.builder_handoff?.review?.reviewer_execution_ref===r.review.reviewerExecutionRef)throw new Error("Native repaired candidate requires a fresh read-only review");let i=hx(r.addressedAcceptanceIds,t.acceptance,"Native Builder addressed acceptance"),n=new Set([...t.loop.previous_unresolved_ids,...i]),a=t.loop.stage==="repairing"&&t.loop.previous_unresolved_ids.length>0?t.acceptance.map(s=>n.has(s.id)?{...s,result:"pending",reason:null}:s):El(t.acceptance),o=(r.now??new Date).toISOString();return C({...t,phase:"verify",state_version:he(t),verification_result:"pending",verification_report:null,verification:null,blockers:[],acceptance:a,builder_handoff:{candidate_id:r.candidateId??px(),identity_provider:r.identity.identityProvider,builder_execution_ref:r.identity.executionRef,iteration:t.loop.iteration,summary:H(r.summary),addressed_acceptance_ids:i,checks:mx(r.checks),checks_truncated:!1,known_limits:(r.knownLimits??[]).map(s=>H(s)),known_limits_truncated:!1,review:{status:"passed",summary:H(r.review.summary),reviewer_execution_ref:r.review.reviewerExecutionRef},submitted_at:o},loop:{...t.loop,stage:"verify-ready",attempt:0,execution_failure_count:0,next_action:"run-required-checks-and-dispatch-verifier"}})}function Vh(e){let t=C(e);if(t.phase!=="verify"||t.status!=="active"||t.loop.stage!=="verify-ready"||t.builder_handoff===null||t.builder_handoff.review===null)throw new Error("Native Verifier attempt requires a reviewed Builder candidate");return C({...t,state_version:he(t),verification:null,loop:{...t.loop,attempt:t.loop.attempt+1,next_action:"await-verifier-result"}})}function vx(e,t){let r=e.loop.previous_unresolved_ids;if(r.length===0)return 0;let i=new Set(r),n=new Set(t);return n.size<i.size&&[...n].every(o=>i.has(o))?0:e.loop.no_progress_count+1}function gx(e){return{candidate_id:e.envelope.candidateId,identity_provider:e.envelope.identityProvider,verifier_execution_ref:e.envelope.verifierExecutionRef,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,assurance:e.envelope.identityProvider===Z?"skill-coordinated":"host-attested",verdict:e.response.result.verdict,checks:e.checks,summary:H(e.response.result.summary),risks:e.response.result.risks.map(t=>H(t)),risks_truncated:!1,completed_at:e.completedAt}}function Mh(e){let t=C(e.state);if(t.phase!=="verify"||t.builder_handoff===null||t.loop.attempt<1)throw new Error("Native change is not awaiting a Verifier result");let r=xl(t);if(r.length===0)throw new Error("Native Verifier attempt has no pending acceptance scenarios");let i=Hh({envelope:e.envelope,binding:{candidateId:t.builder_handoff.candidate_id,identityProvider:t.builder_handoff.identity_provider,builderExecutionRef:t.builder_handoff.builder_execution_ref,iteration:t.loop.iteration,attempt:t.loop.attempt,acceptanceIds:r,requiredChecksPassed:e.checks.every(({status:p})=>p==="passed")}});if(i.kind==="request-checks")return{state:t,response:i};if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let n=(e.now??new Date).toISOString(),a=new Map(i.result.acceptance.map(p=>[p.id,p])),o=t.acceptance.map(p=>{let w=a.get(p.id);return w?{...p,result:w.result,reason:H(w.reason)}:p}),s=o.filter(({result:p})=>p==="failed"||p==="blocked").map(({id:p})=>p),c=gx({state:t,envelope:e.envelope,response:i,checks:e.checks,completedAt:n});if(i.result.verdict==="pass"){if(t.loop.previous_unresolved_ids.length>0){let g=pe({...t,acceptance:o,verification:c},mt({state:t,outcome:"recovery",summary:`Repair verification passed for ${r.join(", ")}; final full verification is required.`,completedAt:n}));return{response:i,state:C({...g,state_version:he(t),status:"active",verification_result:"pending",verification_report:null,blockers:[],acceptance:El(o),loop:{...t.loop,stage:"verify-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:"run-final-full-verification"}})}}let p=pe({...t,acceptance:o,verification:c},mt({state:t,outcome:"pass",summary:i.result.summary,completedAt:n})),w=t.builder_handoff.identity_provider===Z;return{response:i,state:C({...p,phase:w?"verify":"archive",status:w?"await-user":"active",state_version:he(t),verification_result:"pass",verification_report:"verification.md",blockers:w?[{owner:"user",reason:H("The generic Skill bridge cannot prove an independent Verifier execution; user confirmation is required before Archive."),acceptance_ids:[],resolution_action:"await-user"}]:[],loop:{...t.loop,stage:w?"await-user":"archive-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:w?"confirm-skill-coordinated-pass":"archive"}})}}if(i.result.verdict==="blocked"){let p=pe({...t,acceptance:o,verification:c},mt({state:t,outcome:"blocked",unresolvedIds:s,summary:i.result.summary,completedAt:n}));return{response:i,state:C({...p,status:"await-user",state_version:he(t),verification_result:"blocked",verification_report:"verification.md",blockers:[{owner:"user",reason:H(i.result.summary),acceptance_ids:s,resolution_action:"resolve-verifier-blocker"}],loop:{...t.loop,stage:"await-user",execution_failure_count:0,previous_unresolved_ids:s,next_action:"resolve-verifier-blocker"}})}}let l=t.loop.failed_iteration_count+1,f=vx(t,s),u=l>=e.maxVerifyFailures,d=f>=3,m=u||d,v=d?"stalled":u?"budget":void 0,h=pe({...t,acceptance:o,verification:c},mt({state:t,outcome:"fail",unresolvedIds:s,summary:i.result.summary,completedAt:n}));return{response:i,state:C({...h,phase:m?"verify":"build",status:m?"await-user":"active",state_version:he(t),verification_result:"fail",verification_report:"verification.md",builder_handoff:t.builder_handoff,blockers:m?[{owner:"user",reason:H(v==="budget"?"Native verification reached the configured failed iteration limit.":"Native verification did not strictly reduce the unresolved acceptance set three times."),acceptance_ids:s,resolution_action:"await-user"}]:f>=2?[{owner:"builder",reason:H("Native verification has not made reliable progress twice; use a different repair hypothesis before resubmitting."),acceptance_ids:s,resolution_action:"return-build"}]:[],loop:{...t.loop,stage:m?"await-user":"repairing",iteration:m?t.loop.iteration:t.loop.iteration+1,attempt:m?t.loop.attempt:0,failed_iteration_count:l,no_progress_count:f,...v===void 0?{}:{stop_reason:v},execution_failure_count:0,previous_unresolved_ids:s,next_action:m?"await-user":"repair-failed-acceptance"}})}}function Fh(e){let t=C(e);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="pass"||t.verification===null||t.builder_handoff?.identity_provider!==Z||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-skill-coordinated-pass")throw new Error("Native change is not awaiting Skill-coordinated pass confirmation");return C({...t,phase:"archive",status:"active",state_version:he(t),blockers:[],loop:{...t.loop,stage:"archive-ready",next_action:"archive"}})}function qh(e){let t=C(e.state);if(t.phase!=="verify"||t.status!=="active"||t.builder_handoff?.identity_provider!==Z||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native semantic verification unavailability requires an active Skill attempt");if(e.checks.some(({status:a})=>a!=="passed"))throw new Error("Native semantic verification unavailability requires every resolved Runtime check to pass");let r=(e.now??new Date).toISOString(),i=xl(t),n=pe(t,mt({state:t,outcome:"blocked",unresolvedIds:i,summary:e.summary,completedAt:r}));return C({...n,status:"await-user",state_version:he(t),verification_result:"blocked",verification_report:"verification.md",verification:{candidate_id:t.builder_handoff.candidate_id,identity_provider:t.builder_handoff.identity_provider,verifier_execution_ref:e.verifierExecutionRef,iteration:t.loop.iteration,attempt:t.loop.attempt,assurance:"semantic-verification-unavailable",verdict:"blocked",checks:e.checks,summary:H(e.summary),risks:[H("No independent semantic Verifier execution was available; Runtime checks alone do not cover acceptance semantics.")],risks_truncated:!1,completed_at:r},blockers:[{owner:"user",reason:H("Independent semantic verification is unavailable on this platform; only completed Runtime checks are available, so explicit user confirmation is required before Archive."),acceptance_ids:i,resolution_action:"confirm-verifier-unavailable"}],loop:{...t.loop,stage:"await-user",previous_unresolved_ids:i,execution_failure_count:0,next_action:"confirm-verifier-unavailable"}})}function Wh(e){let t=C(e.state);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.verification?.assurance!=="semantic-verification-unavailable"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-verifier-unavailable")throw new Error("Native change is not awaiting degraded verification confirmation");let r=(e.now??new Date).toISOString(),i=H(e.summary),n=pe(t,mt({state:t,outcome:"pass",summary:e.summary,completedAt:r}));return C({...n,phase:"archive",status:"active",state_version:he(t),verification_result:"pass",verification:{...t.verification,assurance:"user-confirmed-degraded",verdict:"pass",summary:i,completed_at:r},acceptance:t.acceptance.map(a=>({...a,result:"passed",reason:H(`User confirmed degraded completion without independent semantic verification: ${e.summary}`)})),blockers:[],loop:{...t.loop,stage:"archive-ready",previous_unresolved_ids:[],next_action:"archive"}})}function zh(e,t){let r=C(e);if(r.phase!=="verify"||r.status!=="await-user"||r.verification_result!=="blocked"||r.verification?.verdict!=="blocked"||r.verification.assurance==="semantic-verification-unavailable"||r.loop.stage!=="await-user"||r.loop.next_action!=="resolve-verifier-blocker"||!r.blockers.some(({resolution_action:n})=>n==="resolve-verifier-blocker"))throw new Error("Native change is not awaiting resolution of a semantic Verifier blocker");let i=pe(r,mt({state:r,outcome:"recovery",summary:t?.reason??"Resolved the semantic Verifier blocker and resumed verification.",completedAt:(t?.now??new Date).toISOString()}));return C({...i,status:"active",state_version:he(r),verification_result:"pending",verification_report:null,verification:null,acceptance:r.acceptance.map(n=>n.result==="failed"||n.result==="blocked"?{...n,result:"pending",reason:null}:n),blockers:[],loop:{...r.loop,stage:"verify-ready",retry_epoch:r.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function Jh(e){let t=C(e.state);if(t.phase!=="verify"||t.status!=="active"||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier execution error requires an active Verify attempt");let r=(e.now??new Date).toISOString(),i=t.loop.execution_failure_count+1,n=i>=nn,a=pe(t,mt({state:t,outcome:"execution-error",summary:e.summary,completedAt:r}));return C({...a,status:n?"blocked":"active",state_version:he(t),blockers:n?[{owner:"runtime",reason:H(e.summary),acceptance_ids:[],resolution_action:"retry-verifier"}]:[],loop:{...t.loop,stage:n?"blocked":"verify-ready",execution_failure_count:i,next_action:n?"retry-verifier":"dispatch-new-verifier"}})}function Gh(e){let t=C(e),r=t.status==="blocked"&&t.blockers.some(({resolution_action:o})=>o==="retry-verifier"),i=t.status==="await-user"&&t.verification_result==="blocked"&&t.verification?.assurance==="semantic-verification-unavailable"&&t.loop.stage==="await-user"&&t.loop.next_action==="confirm-verifier-unavailable"&&t.blockers.some(({resolution_action:o})=>o==="confirm-verifier-unavailable");if(t.phase!=="verify"||!r&&!i)throw new Error("Native change is not blocked on Verifier infrastructure");let n=xl(t),a=t.acceptance.some(({result:o})=>o==="passed");return C({...t,status:"active",state_version:he(t),...i?{verification_result:"pending",verification_report:null,verification:null}:{},blockers:[],loop:{...t.loop,stage:"verify-ready",retry_epoch:t.loop.retry_epoch+1,execution_failure_count:0,...i?{previous_unresolved_ids:a?n:[]}:{},next_action:"dispatch-new-verifier"}})}function an(e){let t=C(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let r=(e.now??new Date).toISOString(),i=pe(t,mt({state:t,outcome:"recovery",summary:e.reason,completedAt:r})),n=new Set(t.loop.previous_unresolved_ids),a=n.size===0?El(t.acceptance):t.acceptance.map(o=>n.has(o.id)?{...o,result:"pending",reason:null}:o);return C({...i,phase:"build",status:"active",state_version:he(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:t.builder_handoff,blockers:[],acceptance:a,loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,stop_reason:void 0,next_action:"submit-builder-candidate"}})}import{promises as Kh}from"node:fs";import on from"node:path";function vo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function go(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function at(e,t,r=!1){if(typeof e!="string"||!r&&e.length===0)throw new Error(`${t} must be ${r?"a string":"a non-empty string"}`);return e}function Uh(e,t){return e===null?null:at(e,t)}function yo(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function wx(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 yx(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function wo(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Cl(e,t){if(e===null)return null;let r=at(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function Pl(e,t){let r=at(e,t);if(!on.isAbsolute(r))throw new Error(`${t} must be absolute`);return on.resolve(r)}function Nx(e,t){let r=`Native local checks[${t}]`,i=vo(e,r);if(go(i,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),r),!Array.isArray(i.argv)||i.argv.length===0)throw new Error(`${r}.argv must be a non-empty array`);let n=i.argv.map((l,f)=>at(l,`${r}.argv[${f}]`,!0)),a=wo(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=Cl(i.startedAt,`${r}.startedAt`),s=Cl(i.completedAt,`${r}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${r} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${r} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${r} completed check requires startedAt and completedAt`);let c=yo(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);return{id:at(i.id,`${r}.id`),name:at(i.name,`${r}.name`),operationId:at(i.operationId,`${r}.operationId`),status:a,repeatable:yx(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:yo(i.executionCount,`${r}.executionCount`),argv:n,cwd:Pl(i.cwd,`${r}.cwd`),exitCode:wx(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:at(i.log,`${r}.log`)}}function Rl(e){let t="Native local execution state",r=vo(e,t);if(go(r,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),r.schema!==Bi)throw new Error(`Native local execution schema must be ${Bi}`);let i=vo(r.workspace,"Native local workspace");go(i,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(r.execution!==null){let o=vo(r.execution,"Native local execution");go(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=Cl(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:at(o.operationId,"Native local execution.operationId"),stage:wo(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:wo(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Uh(o.executionId,"Native local execution.executionId"),status:wo(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:yo(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(Nx);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:Bi,change:at(r.change,"Native local change"),basedOnStateVersion:yo(r.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:Pl(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Pl(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Uh(i.branch,"Native local workspace.branch")},execution:n,checks:a}}function ae(e){return Rl({schema:Bi,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:on.resolve(e.projectRoot),worktreeRoot:on.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function ot(e){let t;try{t=await Kh.readFile(e,"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}let r;try{r=JSON.parse(t)}catch(i){throw new Error(`Native local execution state is invalid JSON: ${i.message}`,{cause:i})}return Rl(r)}async function V(e,t,r={}){let i=Rl(t);await Kh.mkdir(on.dirname(e),{recursive:!0}),await ye(e,i,r)}async function Al(e){let t=null,r=null;try{t=await ot(e.file),t===null&&(r="missing")}catch(n){if(n.code)throw n;r="invalid"}if(t&&(t.change!==e.portableState.name||t.basedOnStateVersion!==e.portableState.state_version)&&(r="version-mismatch"),t&&r===null)return{state:t,rebuilt:!1,reason:null};let i=ae(e);return await V(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{}}),{state:i,rebuilt:!0,reason:r??"missing"}}import{promises as bx}from"node:fs";function Wt(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
184
- `).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function vt(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function kx(e){return e.archived?Fe(e.language,"Archived","已归档"):e.phase==="verify"&&e.loop.next_action==="confirm-skill-coordinated-pass"?Fe(e.language,"Verification passed; your confirmation is required","验收通过,需要你确认"):e.phase==="archive"&&e.loop.next_action==="archive"?Fe(e.language,"Verification passed; ready to archive","验收通过,可归档"):Fe(e.language,"Verification passed","验收通过")}function Sx(e){let t=e.language;return e.verification?.assurance==="semantic-verification-unavailable"?Fe(t,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查"):e.verification_result==="pass"?kx(e):e.verification_result==="blocked"?Fe(t,"Blocked","已阻塞"):e.verification_result==="fail"?Fe(t,"Failed","未通过"):Fe(t,"Pending","待处理")}function Ex(e){let t=e.verification?.assurance??(e.builder_handoff?.identity_provider===Z?Z:"host-attested"),r=t===Z&&(e.archived||e.phase==="archive"&&e.loop.next_action==="archive");return(e.language==="en"?{"host-attested":"Host independently verified","skill-coordinated":r?"Checks completed; result confirmed":"Checks completed, but your confirmation is required","semantic-verification-unavailable":"Full verification was unavailable; only automatic checks completed","user-confirmed-degraded":"You accepted the incomplete verification result"}:{"host-attested":"已完成独立验证","skill-coordinated":r?"已完成检查,验证结果已确认":"已完成检查,但需要你确认验证结果","semantic-verification-unavailable":"无法完成完整验证,只完成了自动检查","user-confirmed-degraded":"你已确认接受不完整验证结果"})[t]??t}function xx(e,t){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let r=e.language,i=u=>Lc(r,u),n=(u,d)=>Fe(r,u,d),a=e.acceptance.map(u=>`| ${vt(u.id)} | ${vt(u.result)} | ${vt(u.source)} | ${vt(u.text)} | ${vt(Wt(u.reason))} |`).join(`
183
+ `)}),l.once("close",(m,v)=>{clearTimeout(d);let h=(e.now??(()=>new Date))();o.end(()=>{let p=f||u!==null||v!==null;s({id:t.id,name:t.name,argvDisplay:wl(t.argv),cwdRef:t.cwdRef,status:p?"interrupted":m===0?"passed":"failed",exitCode:m,signal:v,timedOut:f,durationMs:Math.max(0,h.getTime()-a.getTime()),startedAt:a.toISOString(),completedAt:h.toISOString(),repeatable:t.repeatable,logRef:Se.relative(e.runtimeDir,n).split(Se.sep).join("/")})})}),o.once("error",m=>{clearTimeout(d),uo(l).catch(()=>l.kill("SIGKILL")),c(m)})})}import{randomUUID as mx}from"node:crypto";var jh=Symbol("comet.native.trusted-execution-identity"),$h=Symbol("comet.native.trusted-verifier-envelope"),Z="skill-coordinated";function Nl(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} is invalid`);return e}function bl(){let e=new WeakSet;return Object.freeze({captureExecutionIdentity(t){Nl(t.identityProvider,"Native identity provider");let r=Object.freeze({identityProvider:Z,executionRef:Nl(t.executionRef,"Native execution ref"),[jh]:!0});return e.add(r),r},envelopeVerifierResponse(t){if(!e.has(t.identity))throw new Error("Native execution identity was not captured by this Runner channel");return Object.freeze({candidateId:Nl(t.candidateId,"Native candidate ID"),identityProvider:t.identity.identityProvider,verifierExecutionRef:t.identity.executionRef,payload:t.payload,[$h]:!0})}})}function ho(e){return typeof e=="object"&&e!==null&&e[$h]===!0}function Oh(e){return typeof e=="object"&&e!==null&&e[jh]===!0}function mo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function tn(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function rn(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function cr(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be non-empty text`);return e}function fx(e){if(!Array.isArray(e))throw new Error("Native Verifier acceptance must be an array");return e.map((t,r)=>{let i=mo(t,`Native Verifier acceptance ${r}`);tn(i,["id","result","reason"],`Native Verifier acceptance ${r}`);let n=cr(i.id,`Native Verifier acceptance ${r} ID`);if(!["passed","failed","blocked"].includes(String(i.result)))throw new Error(`Native Verifier acceptance ${n} result is invalid`);return{id:n,result:i.result,reason:cr(i.reason,`Native Verifier acceptance ${n} reason`)}})}function px(e){let t=mo(e,"Native Verifier final result");if(tn(t,["iteration","attempt","verdict","acceptance","risks","summary"],"Native Verifier final result"),!["pass","fail","blocked"].includes(String(t.verdict)))throw new Error("Native Verifier verdict is invalid");if(!Array.isArray(t.risks)||!t.risks.every(r=>typeof r=="string"))throw new Error("Native Verifier risks must be text entries");return{iteration:rn(t.iteration,"Native Verifier iteration"),attempt:rn(t.attempt,"Native Verifier attempt"),verdict:t.verdict,acceptance:fx(t.acceptance),risks:t.risks,summary:cr(t.summary,"Native Verifier summary")}}function hx(e,t){let r=mo(e,`Native Verifier check request ${t}`);if(tn(r,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Verifier check request ${t}`),!Array.isArray(r.argv)||!r.argv.every(n=>typeof n=="string"))throw new Error(`Native Verifier check request ${t} argv is invalid`);if(typeof r.repeatable!="boolean")throw new Error(`Native Verifier check request ${t} repeatable is invalid`);let i=rn(r.timeoutMs,`Native Verifier check request ${t} timeout`);if(i<1)throw new Error("Native Verifier check timeout must be positive");return{id:cr(r.id,`Native Verifier check request ${t} ID`),name:cr(r.name,`Native Verifier check request ${t} name`),executable:cr(r.executable,`Native Verifier check request ${t} executable`),argv:r.argv,cwdRef:cr(r.cwdRef,`Native Verifier check request ${t} cwd`),timeoutMs:i,repeatable:r.repeatable}}function kl(e){let t=mo(e,"Native Verifier response");if(t.kind==="final-result")return tn(t,["kind","result"],"Native Verifier response"),{kind:"final-result",result:px(t.result)};if(t.kind==="request-checks"){if(tn(t,["kind","iteration","attempt","checks"],"Native Verifier response"),!Array.isArray(t.checks)||t.checks.length===0)throw new Error("Native Verifier check request batch must be non-empty");return{kind:"request-checks",iteration:rn(t.iteration,"Native Verifier iteration"),attempt:rn(t.attempt,"Native Verifier attempt"),checks:t.checks.map(hx)}}throw new Error("Native Verifier response kind is invalid")}function Hh(e){if(!ho(e.envelope))throw new Error("Native Verifier result must come from the trusted Runner channel");let{envelope:t,binding:r}=e;if(t.candidateId!==r.candidateId)throw new Error("Native Verifier result does not match the current candidate");if(t.identityProvider!==r.identityProvider)throw new Error("Native Verifier identity provider does not match the Builder provider");if(t.verifierExecutionRef===r.builderExecutionRef)throw new Error("Native Builder and Verifier must be different executions");let i=kl(t.payload),n=i.kind==="final-result"?i.result.iteration:i.iteration,a=i.kind==="final-result"?i.result.attempt:i.attempt;if(n!==r.iteration||a!==r.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");if(i.kind==="request-checks")return i;let o=[...r.acceptanceIds],s=i.result.acceptance.map(({id:d})=>d),c=s.filter((d,m)=>s.indexOf(d)!==m),l=s.filter(d=>!o.includes(d)),f=o.filter(d=>!s.includes(d));if(c.length>0||l.length>0||f.length>0)throw new Error(`Native Verifier acceptance coverage is invalid (duplicate: ${[...new Set(c)].join(", ")||"none"}; unknown: ${l.join(", ")||"none"}; missing: ${f.join(", ")||"none"})`);if(!r.requiredChecksPassed&&i.result.verdict==="pass")throw new Error("Native verification cannot pass before every required check succeeds");let u=i.result.acceptance.map(({result:d})=>d);if(i.result.verdict==="pass"&&u.some(d=>d!=="passed"))throw new Error("Native pass requires every acceptance criterion to pass");if(i.result.verdict==="fail"&&!u.includes("failed"))throw new Error("Native fail requires at least one failed acceptance criterion");if(i.result.verdict==="blocked"&&!u.includes("blocked"))throw new Error("Native blocked verdict requires at least one blocked acceptance criterion");return i}var nn=3,Sl=2;function he(e){return e.state_version+1}function vx(e,t,r){let i=[...e];if(new Set(i).size!==i.length)throw new Error(`${r} contains duplicate IDs`);let n=new Set(t.map(({id:o})=>o)),a=i.filter(o=>!n.has(o));if(a.length>0)throw new Error(`${r} contains unknown IDs: ${a.join(", ")}`);return i}function El(e){return e.map(t=>({...t,result:"pending",reason:null}))}function xl(e){return e.acceptance.filter(({result:t})=>t==="pending").map(({id:t})=>t)}function gx(e){return(e??[]).map(t=>({name:H(t.name),result:t.result,note:t.note?H(t.note):null}))}function mt(e){return{goal_cycle:e.state.loop.goal_cycle,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,outcome:e.outcome,unresolved_ids:e.unresolvedIds??[],summary:H(e.summary),completed_at:e.completedAt}}function Dh(e){let t=C(e.state);if(t.phase!=="shape"||t.status!=="await-user"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-shape")throw new Error("Native acceptance can only be confirmed from the persisted Shape confirmation boundary");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let r=e.acceptance.map(({id:i})=>i);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return C({...t,phase:"build",status:"active",state_version:he(t),loop:{...t.loop,stage:"building",iteration:1,attempt:0,next_action:"submit-builder-candidate"},acceptance:e.acceptance.map(i=>({...i,result:"pending",reason:null}))})}function Bh(e){let t=C(e.state);if(t.phase!=="shape"||t.status!=="active"||t.loop.stage!=="shape")throw new Error("Native Shape confirmation can only be prepared from active Shape");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let r=e.acceptance.map(({id:i})=>i);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return C({...t,status:"await-user",state_version:he(t),loop:{...t.loop,stage:"await-user",next_action:"confirm-shape"},acceptance:e.acceptance.map(i=>({...i,result:"pending",reason:null}))})}function Lh(e){let t=C(e.state),{input:r}=e;if(t.phase!=="build"||t.status!=="active")throw new Error("Native candidate can only be submitted from active Build");if(!Oh(r.identity))throw new Error("Native Builder identity must come from the trusted Runner channel");if(!r.review||r.review.status!=="passed")throw new Error("Native Builder candidate requires a passed read-only review");if(r.review.reviewerExecutionRef===r.identity.executionRef)throw new Error("Native reviewer execution ref must differ from the Builder execution ref");if(t.loop.stage==="repairing"&&t.builder_handoff?.review?.reviewer_execution_ref===r.review.reviewerExecutionRef)throw new Error("Native repaired candidate requires a fresh read-only review");let i=vx(r.addressedAcceptanceIds,t.acceptance,"Native Builder addressed acceptance"),n=new Set([...t.loop.previous_unresolved_ids,...i]),a=t.loop.stage==="repairing"&&t.loop.previous_unresolved_ids.length>0?t.acceptance.map(s=>n.has(s.id)?{...s,result:"pending",reason:null}:s):El(t.acceptance),o=(r.now??new Date).toISOString();return C({...t,phase:"verify",state_version:he(t),verification_result:"pending",verification_report:null,verification:null,blockers:[],acceptance:a,builder_handoff:{candidate_id:r.candidateId??mx(),identity_provider:r.identity.identityProvider,builder_execution_ref:r.identity.executionRef,iteration:t.loop.iteration,summary:H(r.summary),addressed_acceptance_ids:i,checks:gx(r.checks),checks_truncated:!1,known_limits:(r.knownLimits??[]).map(s=>H(s)),known_limits_truncated:!1,review:{status:"passed",summary:H(r.review.summary),reviewer_execution_ref:r.review.reviewerExecutionRef},submitted_at:o},loop:{...t.loop,stage:"verify-ready",attempt:0,execution_failure_count:0,next_action:"run-required-checks-and-dispatch-verifier"}})}function Vh(e){let t=C(e);if(t.phase!=="verify"||t.status!=="active"||t.loop.stage!=="verify-ready"||t.builder_handoff===null||t.builder_handoff.review===null)throw new Error("Native Verifier attempt requires a reviewed Builder candidate");return C({...t,state_version:he(t),verification:null,loop:{...t.loop,attempt:t.loop.attempt+1,next_action:"await-verifier-result"}})}function wx(e,t){let r=e.loop.previous_unresolved_ids;if(r.length===0)return 0;let i=new Set(r),n=new Set(t);return n.size<i.size&&[...n].every(o=>i.has(o))?0:e.loop.no_progress_count+1}function yx(e){return{candidate_id:e.envelope.candidateId,identity_provider:e.envelope.identityProvider,verifier_execution_ref:e.envelope.verifierExecutionRef,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,assurance:e.envelope.identityProvider===Z?"skill-coordinated":"host-attested",verdict:e.response.result.verdict,checks:e.checks,summary:H(e.response.result.summary),risks:e.response.result.risks.map(t=>H(t)),risks_truncated:!1,completed_at:e.completedAt}}function Mh(e){let t=C(e.state);if(t.phase!=="verify"||t.builder_handoff===null||t.loop.attempt<1)throw new Error("Native change is not awaiting a Verifier result");let r=xl(t);if(r.length===0)throw new Error("Native Verifier attempt has no pending acceptance scenarios");let i=Hh({envelope:e.envelope,binding:{candidateId:t.builder_handoff.candidate_id,identityProvider:t.builder_handoff.identity_provider,builderExecutionRef:t.builder_handoff.builder_execution_ref,iteration:t.loop.iteration,attempt:t.loop.attempt,acceptanceIds:r,requiredChecksPassed:e.checks.every(({status:p})=>p==="passed")}});if(i.kind==="request-checks")return{state:t,response:i};if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let n=(e.now??new Date).toISOString(),a=new Map(i.result.acceptance.map(p=>[p.id,p])),o=t.acceptance.map(p=>{let w=a.get(p.id);return w?{...p,result:w.result,reason:H(w.reason)}:p}),s=o.filter(({result:p})=>p==="failed"||p==="blocked").map(({id:p})=>p),c=yx({state:t,envelope:e.envelope,response:i,checks:e.checks,completedAt:n});if(i.result.verdict==="pass"){if(t.loop.previous_unresolved_ids.length>0){let g=pe({...t,acceptance:o,verification:c},mt({state:t,outcome:"recovery",summary:`Repair verification passed for ${r.join(", ")}; final full verification is required.`,completedAt:n}));return{response:i,state:C({...g,state_version:he(t),status:"active",verification_result:"pending",verification_report:null,blockers:[],acceptance:El(o),loop:{...t.loop,stage:"verify-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:"run-final-full-verification"}})}}let p=pe({...t,acceptance:o,verification:c},mt({state:t,outcome:"pass",summary:i.result.summary,completedAt:n})),w=t.builder_handoff.identity_provider===Z;return{response:i,state:C({...p,phase:w?"verify":"archive",status:w?"await-user":"active",state_version:he(t),verification_result:"pass",verification_report:"verification.md",blockers:w?[{owner:"user",reason:H("The generic Skill bridge cannot prove an independent Verifier execution; user confirmation is required before Archive."),acceptance_ids:[],resolution_action:"await-user"}]:[],loop:{...t.loop,stage:w?"await-user":"archive-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:w?"confirm-skill-coordinated-pass":"archive"}})}}if(i.result.verdict==="blocked"){let p=pe({...t,acceptance:o,verification:c},mt({state:t,outcome:"blocked",unresolvedIds:s,summary:i.result.summary,completedAt:n}));return{response:i,state:C({...p,status:"await-user",state_version:he(t),verification_result:"blocked",verification_report:"verification.md",blockers:[{owner:"user",reason:H(i.result.summary),acceptance_ids:s,resolution_action:"resolve-verifier-blocker"}],loop:{...t.loop,stage:"await-user",execution_failure_count:0,previous_unresolved_ids:s,next_action:"resolve-verifier-blocker"}})}}let l=t.loop.failed_iteration_count+1,f=wx(t,s),u=l>=e.maxVerifyFailures,d=f>=3,m=u||d,v=d?"stalled":u?"budget":void 0,h=pe({...t,acceptance:o,verification:c},mt({state:t,outcome:"fail",unresolvedIds:s,summary:i.result.summary,completedAt:n}));return{response:i,state:C({...h,phase:m?"verify":"build",status:m?"await-user":"active",state_version:he(t),verification_result:"fail",verification_report:"verification.md",builder_handoff:t.builder_handoff,blockers:m?[{owner:"user",reason:H(v==="budget"?"Native verification reached the configured failed iteration limit.":"Native verification did not strictly reduce the unresolved acceptance set three times."),acceptance_ids:s,resolution_action:"await-user"}]:f>=2?[{owner:"builder",reason:H("Native verification has not made reliable progress twice; use a different repair hypothesis before resubmitting."),acceptance_ids:s,resolution_action:"return-build"}]:[],loop:{...t.loop,stage:m?"await-user":"repairing",iteration:m?t.loop.iteration:t.loop.iteration+1,attempt:m?t.loop.attempt:0,failed_iteration_count:l,no_progress_count:f,...v===void 0?{}:{stop_reason:v},execution_failure_count:0,previous_unresolved_ids:s,next_action:m?"await-user":"repair-failed-acceptance"}})}}function Fh(e){let t=C(e);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="pass"||t.verification===null||t.builder_handoff?.identity_provider!==Z||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-skill-coordinated-pass")throw new Error("Native change is not awaiting Skill-coordinated pass confirmation");return C({...t,phase:"archive",status:"active",state_version:he(t),blockers:[],loop:{...t.loop,stage:"archive-ready",next_action:"archive"}})}function qh(e){let t=C(e.state);if(t.phase!=="verify"||t.status!=="active"||t.builder_handoff?.identity_provider!==Z||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native semantic verification unavailability requires an active Skill attempt");if(e.checks.some(({status:a})=>a!=="passed"))throw new Error("Native semantic verification unavailability requires every resolved Runtime check to pass");let r=(e.now??new Date).toISOString(),i=xl(t),n=pe(t,mt({state:t,outcome:"blocked",unresolvedIds:i,summary:e.summary,completedAt:r}));return C({...n,status:"await-user",state_version:he(t),verification_result:"blocked",verification_report:"verification.md",verification:{candidate_id:t.builder_handoff.candidate_id,identity_provider:t.builder_handoff.identity_provider,verifier_execution_ref:e.verifierExecutionRef,iteration:t.loop.iteration,attempt:t.loop.attempt,assurance:"semantic-verification-unavailable",verdict:"blocked",checks:e.checks,summary:H(e.summary),risks:[H("No independent semantic Verifier execution was available; Runtime checks alone do not cover acceptance semantics.")],risks_truncated:!1,completed_at:r},blockers:[{owner:"user",reason:H("Independent semantic verification is unavailable on this platform; only completed Runtime checks are available, so explicit user confirmation is required before Archive."),acceptance_ids:i,resolution_action:"confirm-verifier-unavailable"}],loop:{...t.loop,stage:"await-user",previous_unresolved_ids:i,execution_failure_count:0,next_action:"confirm-verifier-unavailable"}})}function Wh(e){let t=C(e.state);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.verification?.assurance!=="semantic-verification-unavailable"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-verifier-unavailable")throw new Error("Native change is not awaiting degraded verification confirmation");let r=(e.now??new Date).toISOString(),i=H(e.summary),n=pe(t,mt({state:t,outcome:"pass",summary:e.summary,completedAt:r}));return C({...n,phase:"archive",status:"active",state_version:he(t),verification_result:"pass",verification:{...t.verification,assurance:"user-confirmed-degraded",verdict:"pass",summary:i,completed_at:r},acceptance:t.acceptance.map(a=>({...a,result:"passed",reason:H(`User confirmed degraded completion without independent semantic verification: ${e.summary}`)})),blockers:[],loop:{...t.loop,stage:"archive-ready",previous_unresolved_ids:[],next_action:"archive"}})}function zh(e,t){let r=C(e);if(r.phase!=="verify"||r.status!=="await-user"||r.verification_result!=="blocked"||r.verification?.verdict!=="blocked"||r.verification.assurance==="semantic-verification-unavailable"||r.loop.stage!=="await-user"||r.loop.next_action!=="resolve-verifier-blocker"||!r.blockers.some(({resolution_action:n})=>n==="resolve-verifier-blocker"))throw new Error("Native change is not awaiting resolution of a semantic Verifier blocker");let i=pe(r,mt({state:r,outcome:"recovery",summary:t?.reason??"Resolved the semantic Verifier blocker and resumed verification.",completedAt:(t?.now??new Date).toISOString()}));return C({...i,status:"active",state_version:he(r),verification_result:"pending",verification_report:null,verification:null,acceptance:r.acceptance.map(n=>n.result==="failed"||n.result==="blocked"?{...n,result:"pending",reason:null}:n),blockers:[],loop:{...r.loop,stage:"verify-ready",retry_epoch:r.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function Jh(e){let t=C(e.state);if(t.phase!=="verify"||t.status!=="active"||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier execution error requires an active Verify attempt");let r=(e.now??new Date).toISOString(),i=t.loop.execution_failure_count+1,n=i>=nn,a=pe(t,mt({state:t,outcome:"execution-error",summary:e.summary,completedAt:r}));return C({...a,status:n?"blocked":"active",state_version:he(t),blockers:n?[{owner:"runtime",reason:H(e.summary),acceptance_ids:[],resolution_action:"retry-verifier"}]:[],loop:{...t.loop,stage:n?"blocked":"verify-ready",execution_failure_count:i,next_action:n?"retry-verifier":"dispatch-new-verifier"}})}function Gh(e){let t=C(e),r=t.status==="blocked"&&t.blockers.some(({resolution_action:o})=>o==="retry-verifier"),i=t.status==="await-user"&&t.verification_result==="blocked"&&t.verification?.assurance==="semantic-verification-unavailable"&&t.loop.stage==="await-user"&&t.loop.next_action==="confirm-verifier-unavailable"&&t.blockers.some(({resolution_action:o})=>o==="confirm-verifier-unavailable");if(t.phase!=="verify"||!r&&!i)throw new Error("Native change is not blocked on Verifier infrastructure");let n=xl(t),a=t.acceptance.some(({result:o})=>o==="passed");return C({...t,status:"active",state_version:he(t),...i?{verification_result:"pending",verification_report:null,verification:null}:{},blockers:[],loop:{...t.loop,stage:"verify-ready",retry_epoch:t.loop.retry_epoch+1,execution_failure_count:0,...i?{previous_unresolved_ids:a?n:[]}:{},next_action:"dispatch-new-verifier"}})}function an(e){let t=C(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let r=(e.now??new Date).toISOString(),i=pe(t,mt({state:t,outcome:"recovery",summary:e.reason,completedAt:r})),n=new Set(t.loop.previous_unresolved_ids),a=n.size===0?El(t.acceptance):t.acceptance.map(o=>n.has(o.id)?{...o,result:"pending",reason:null}:o);return C({...i,phase:"build",status:"active",state_version:he(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:t.builder_handoff,blockers:[],acceptance:a,loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,stop_reason:void 0,next_action:"submit-builder-candidate"}})}import{promises as Kh}from"node:fs";import on from"node:path";function vo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function go(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function at(e,t,r=!1){if(typeof e!="string"||!r&&e.length===0)throw new Error(`${t} must be ${r?"a string":"a non-empty string"}`);return e}function Uh(e,t){return e===null?null:at(e,t)}function yo(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function Nx(e,t){if(e===null)return null;if(!Number.isSafeInteger(e))throw new Error(`${t} must be null or a safe integer`);return e}function bx(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function wo(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Cl(e,t){if(e===null)return null;let r=at(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function Pl(e,t){let r=at(e,t);if(!on.isAbsolute(r))throw new Error(`${t} must be absolute`);return on.resolve(r)}function kx(e,t){let r=`Native local checks[${t}]`,i=vo(e,r);if(go(i,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),r),!Array.isArray(i.argv)||i.argv.length===0)throw new Error(`${r}.argv must be a non-empty array`);let n=i.argv.map((l,f)=>at(l,`${r}.argv[${f}]`,!0)),a=wo(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=Cl(i.startedAt,`${r}.startedAt`),s=Cl(i.completedAt,`${r}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${r} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${r} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${r} completed check requires startedAt and completedAt`);let c=yo(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);return{id:at(i.id,`${r}.id`),name:at(i.name,`${r}.name`),operationId:at(i.operationId,`${r}.operationId`),status:a,repeatable:bx(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:yo(i.executionCount,`${r}.executionCount`),argv:n,cwd:Pl(i.cwd,`${r}.cwd`),exitCode:Nx(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:at(i.log,`${r}.log`)}}function Rl(e){let t="Native local execution state",r=vo(e,t);if(go(r,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),r.schema!==Bi)throw new Error(`Native local execution schema must be ${Bi}`);let i=vo(r.workspace,"Native local workspace");go(i,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(r.execution!==null){let o=vo(r.execution,"Native local execution");go(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=Cl(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:at(o.operationId,"Native local execution.operationId"),stage:wo(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:wo(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Uh(o.executionId,"Native local execution.executionId"),status:wo(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:yo(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(kx);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:Bi,change:at(r.change,"Native local change"),basedOnStateVersion:yo(r.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:Pl(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Pl(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Uh(i.branch,"Native local workspace.branch")},execution:n,checks:a}}function ae(e){return Rl({schema:Bi,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:on.resolve(e.projectRoot),worktreeRoot:on.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function ot(e){let t;try{t=await Kh.readFile(e,"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}let r;try{r=JSON.parse(t)}catch(i){throw new Error(`Native local execution state is invalid JSON: ${i.message}`,{cause:i})}return Rl(r)}async function V(e,t,r={}){let i=Rl(t);await Kh.mkdir(on.dirname(e),{recursive:!0}),await ye(e,i,r)}async function Al(e){let t=null,r=null;try{t=await ot(e.file),t===null&&(r="missing")}catch(n){if(n.code)throw n;r="invalid"}if(t&&(t.change!==e.portableState.name||t.basedOnStateVersion!==e.portableState.state_version)&&(r="version-mismatch"),t&&r===null)return{state:t,rebuilt:!1,reason:null};let i=ae(e);return await V(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{}}),{state:i,rebuilt:!0,reason:r??"missing"}}import{promises as Sx}from"node:fs";function Wt(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
184
+ `).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function vt(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function Ex(e){return e.archived?Fe(e.language,"Archived","已归档"):e.phase==="verify"&&e.loop.next_action==="confirm-skill-coordinated-pass"?Fe(e.language,"Verification passed; your confirmation is required","验收通过,需要你确认"):e.phase==="archive"&&e.loop.next_action==="archive"?Fe(e.language,"Verification passed; ready to archive","验收通过,可归档"):Fe(e.language,"Verification passed","验收通过")}function xx(e){let t=e.language;return e.verification?.assurance==="semantic-verification-unavailable"?Fe(t,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查"):e.verification_result==="pass"?Ex(e):e.verification_result==="blocked"?Fe(t,"Blocked","已阻塞"):e.verification_result==="fail"?Fe(t,"Failed","未通过"):Fe(t,"Pending","待处理")}function Cx(e){let t=e.verification?.assurance??(e.builder_handoff?.identity_provider===Z?Z:"host-attested"),r=t===Z&&(e.archived||e.phase==="archive"&&e.loop.next_action==="archive");return(e.language==="en"?{"host-attested":"Host independently verified","skill-coordinated":r?"Checks completed; result confirmed":"Checks completed, but your confirmation is required","semantic-verification-unavailable":"Full verification was unavailable; only automatic checks completed","user-confirmed-degraded":"You accepted the incomplete verification result"}:{"host-attested":"已完成独立验证","skill-coordinated":r?"已完成检查,验证结果已确认":"已完成检查,但需要你确认验证结果","semantic-verification-unavailable":"无法完成完整验证,只完成了自动检查","user-confirmed-degraded":"你已确认接受不完整验证结果"})[t]??t}function Px(e,t){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let r=e.language,i=u=>Lc(r,u),n=(u,d)=>Fe(r,u,d),a=e.acceptance.map(u=>`| ${vt(u.id)} | ${vt(u.result)} | ${vt(u.source)} | ${vt(u.text)} | ${vt(Wt(u.reason))} |`).join(`
185
185
  `),o=e.verification.checks.length===0?`_${n("No Runtime checks were recorded.","没有记录 Runtime 检查。")}_`:[`| ${n("Check","检查")} | ${n("Command","命令")} | ${n("Working directory","工作目录")} | ${n("Status","状态")} | ${n("Exit","退出码")} | ${n("Duration","耗时")} |`,"| --- | --- | --- | --- | ---: | ---: |",...e.verification.checks.map(u=>{let d=u.argv_display.map(Wt).join(" ");return`| ${vt(Wt(u.name))} | ${vt(d||"—")} | ${vt(u.cwd_ref)} | ${u.status} | ${u.exit_code??"—"} | ${u.duration_ms} ms |`})].join(`
186
186
  `),s=e.blockers.length===0?`_${n("None.","无。")}_`:e.blockers.map(u=>`- **${u.owner}**: ${Wt(u.reason)}${u.acceptance_ids.length>0?` (acceptance: ${u.acceptance_ids.join(", ")})`:""} — next: \`${u.resolution_action}\``).join(`
187
187
  `),c=e.verification.risks.length===0?`_${n("None reported.","未报告风险。")}_`:e.verification.risks.map(u=>`- ${Wt(u)}`).join(`
@@ -202,8 +202,8 @@ generated_from_state_version: ${e.state_version}
202
202
 
203
203
  ## ${i("currentResult")}
204
204
 
205
- - ${n("Result","结果")}: **${Sx(e)}**
206
- - ${n("Verification status","验证情况")}: **${Ex(e)}**
205
+ - ${n("Result","结果")}: **${xx(e)}**
206
+ - ${n("Verification status","验证情况")}: **${Cx(e)}**
207
207
  - ${n("Goal cycle","目标周期")}: ${e.loop.goal_cycle}
208
208
  - ${n("Iteration","迭代")}: ${e.verification.iteration}
209
209
  - ${n("Verifier attempt","验证器尝试次数")}: ${e.verification.attempt}
@@ -239,23 +239,23 @@ ${e.history_overflow.dropped_entries>0?`${n("Earlier history entries folded into
239
239
  `:""}## ${i("conclusion")}
240
240
 
241
241
  ${Wt(e.verification.summary)}
242
- `}function Cx(e){let t=/^---\r?\ngenerated_from_state_version: ([1-9]\d*)\r?\n---(?:\r?\n|$)/u.exec(e);if(!t)return null;let r=Number(t[1]);return Number.isSafeInteger(r)?r:null}async function Yh(e){let t;try{t=await bx.readFile(e.file,"utf8")}catch(i){if(i.code==="ENOENT")return"missing";throw i}let r=Cx(t);return r===null?"invalid":r===e.stateVersion?"aligned":"stale"}async function qr(e){await Re(e.file,xx(e.state,e.supervisor))}var Qh=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Px="comet-state.yaml",Rx="state.json",NO=Fa("en");function zt(e){let t=e.expected;if(t){if(e.state.state_version!==t.stateVersion)throw new Error(`Native continuation is stale for state version ${t.stateVersion}; current state version is ${e.state.state_version}`);if(t.action!==e.action)throw new Error(`Native continuation expected ${t.action} cannot be used for ${e.action}`)}}function ce(e,t){if(!Qh.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=oe.join(e.changesDir,t);if(!ue(e.changesDir,r))throw new Error("Native change path escaped");return r}function Je(e,t){return oe.join(ce(e,t),Px)}function D(e,t){return oe.join(Ve(e,t),Rx)}async function sn(e,t){try{let r=await lr.readFile(Je(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function Ee(e){return z(e).currentBranch}async function _(e,t){return Me(Je(e,t))}async function me(e){let t=await Li({file:Je(e.paths,e.previous.name),expectedStateVersion:e.previous.state_version,next:e.next,containedRoot:e.paths.nativeRoot});if(t.verification===null&&t.verification_report===null){let r=oe.join(ce(e.paths,t.name),"verification.md");await J(e.paths.nativeRoot,r),await lr.rm(r,{force:!0})}return t}async function Tl(e){let t=ce(e.paths,e.state.name),r=oe.join(t,"specs"),i=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await lr.readdir(r,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,c)=>s.name.localeCompare(c.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!Qh.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(i.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,c=oe.join(t,...s.split("/")),l=await lr.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let f=oe.join(e.paths.specsDir,o.name,"spec.md"),u="create";try{let d=await lr.lstat(f);if(!d.isFile()||d.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);u="modify"}catch(d){if(d.code!=="ENOENT")throw d}a.push({capability:o.name,operation:u,source:s})}return a.push(...i.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function jl(e){let t=ce(e.paths,e.state.name),r=await Y({root:t,ref:"brief.md",maxBytes:null,includeHash:!1});if(Ah(r.text))throw new Error("Brief has a blocking open question");let i=[],n=[];for(let a of e.specChanges){if(a.source===null){n.push({...a,contentHash:null});continue}let o=await Y({root:t,ref:a.source,maxBytes:null,includeHash:!1});i.push({capability:a.capability,source:o.ref,markdown:o.text}),n.push({...a,contentHash:X("comet.native.shape-artifact-content.v1",o.text)})}return{acceptance:Ya({briefMarkdown:r.text,specs:i}),formalHash:X("comet.native.shape-formal-artifacts.v1",{brief:{source:r.ref,contentHash:X("comet.native.shape-artifact-content.v1",r.text)},specs:n})}}function $l(e){return X("comet.native.shape-confirmation.v1",{formalHash:e.formalHash,childrenHash:e.childrenHash,coordinationMode:e.coordinationMode??null})}async function Zh(e){return x(e.paths,`prepare portable shape confirmation ${e.name}`,async()=>{let t=await _(e.paths,e.name);if(zt({state:t,expected:e.expectedContinuation,action:"prepare-shape-confirmation"}),t.phase!=="shape"||t.status!=="active"||t.loop.stage!=="shape")throw new Error("Native Shape confirmation can only be prepared from active Shape");let r=await Tl({paths:e.paths,state:t}),i=await jl({paths:e.paths,state:t,specChanges:r}),{acceptance:n}=i,a=await Mt({changeDir:ce(e.paths,t.name),acceptanceIds:n.map(({id:u})=>u),validation:Mr({...t,acceptance:n})});if(a&&t.workspace.change_branch===null)throw new Error("Native parent changes require a Git integration branch");let o=await lo(ce(e.paths,t.name))||a?.contract.schema==="comet.native.children.v2"&&a.contract.children.length>=2;if(o&&!a)throw new Error("Native Supervisor Shape requires children.yaml before confirmation");let s=o?e.coordinationMode??t.coordination_mode:void 0;if(o&&s===void 0)throw new Error("Native Supervisor Shape requires --coordination-mode multi-session or single-session");if(!o&&e.coordinationMode!==void 0)throw new Error("--coordination-mode is only valid for a multi-child Native Supervisor Shape");let c={...t,spec_changes:r,shape_confirmation_hash:$l({formalHash:i.formalHash,childrenHash:a?.hash??null,coordinationMode:s})};delete c.children_contract_hash,delete c.coordination_mode,o&&(c.coordination_mode=s);let l=Bh({state:c,acceptance:n.map(u=>({...u}))});a&&(l.children_contract_hash=Zi({acceptance:l.acceptance,children:a.contract}));let f=await me({paths:e.paths,previous:t,next:l});return await V(D(e.paths,t.name),ae({portableState:f,projectRoot:e.paths.projectRoot,branch:Ee(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),f})}async function em(e){return x(e.paths,`confirm portable shape ${e.name}`,async()=>{let t=await _(e.paths,e.name);if(zt({state:t,expected:e.expectedContinuation,action:"confirm-shape"}),t.phase!=="shape"||t.status!=="await-user"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-shape")throw new Error("Native Shape can only be confirmed from the persisted user confirmation boundary");if(e.coordinationMode!==void 0)throw new Error("--coordination-mode must be selected before final Shape confirmation");await gt({paths:e.paths,state:t});let r=await Tl({paths:e.paths,state:t}),i=await jl({paths:e.paths,state:t,specChanges:r}),{acceptance:n}=i,a=await Mt({changeDir:ce(e.paths,t.name),acceptanceIds:n.map(({id:h})=>h),validation:Mr({...t,acceptance:n})});if(a&&t.workspace.change_branch===null)throw new Error("Native parent changes require a Git integration branch");let o=await lo(ce(e.paths,t.name))||a?.contract.schema==="comet.native.children.v2"&&a.contract.children.length>=2,s=t.coordination_mode;if(o&&!a)throw new Error("Native Supervisor Shape requires children.yaml before confirmation");if(o&&s===void 0)throw new Error("Native Supervisor Shape requires --coordination-mode multi-session or single-session");let c=$l({formalHash:i.formalHash,childrenHash:a?.hash??null,coordinationMode:s});if(t.shape_confirmation_hash===void 0||c!==t.shape_confirmation_hash){let h=t.shape_confirmation_hash===void 0?"Native Shape confirmation fingerprint is missing":"Native Shape artifacts changed";throw await Dl({paths:e.paths,state:t,reason:h}),new Error(`${h}; Native change returned to Shape and requires confirmation`)}let l=Dh({state:{...t,spec_changes:r},acceptance:n.map(h=>({...h}))});if(delete l.children_contract_hash,delete l.coordination_mode,a){l.children_contract_hash=Zi({acceptance:l.acceptance,children:a.contract}),o&&(l.coordination_mode=s);let h=[...t.history].reverse().find(({outcome:p})=>p==="pass"||p==="fail");if(h?.outcome==="fail"&&h.unresolved_ids.length>0){let p=await nt({paths:e.paths,state:l}),w=new Map((p?.children??[]).map(({name:b,status:N})=>[b,N])),g=new Set(a.contract.children.filter(({name:b})=>{let N=w.get(b);return N!=="done"&&N!=="integrated"&&N!=="archived"}).flatMap(({covers:b})=>b)),y=h.unresolved_ids.filter(b=>!g.has(b));if(y.length>0)throw new Error(`Native parent repair plan requires an unfinished child covering: ${y.join(", ")}`)}}let f=null,u=a?.contract.schema==="comet.native.children.v2"?await W(e.paths,t.name):null,d=null,m=null;if(a?.contract.schema==="comet.native.children.v2"){if(d=t.workspace.target_branch??t.workspace.change_branch,!d)throw new Error("Native Supervisor v2 requires a target branch");if(m=Er(e.paths.projectRoot,d),!m)throw new Error(`Native Supervisor target branch has no commit: ${d}`);u||(u=await ao({paths:e.paths,parent:t.name,targetBranch:d,contract:a.contract})),u||(f=await lh({projectRoot:e.paths.projectRoot,parent:t.name,targetBranch:d,sourceConfig:await Ne(e.paths.projectRoot)}))}let v=await me({paths:e.paths,previous:t,next:l});if(await V(D(e.paths,t.name),ae({portableState:v,projectRoot:e.paths.projectRoot,branch:Ee(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),a?.contract.schema==="comet.native.children.v2"&&d&&m){let h=u?dh({state:u,contract:a.contract}):f?sl({parent:v.name,targetBranch:d,targetCommit:m,integrationBranch:f.binding.changeBranch,integrationWorktree:f.projectRoot,contract:a.contract}):null;if(!h)throw new Error("Native Supervisor integration state is unavailable");await ne(e.paths,h)}return v})}async function So(e){let t=await Tl(e),r=e.ignoreSpecOperationFor??(e.state.children_contract_hash?new Set(e.state.spec_changes.map(({capability:l})=>l)):void 0);if(!(t.length===e.state.spec_changes.length&&t.every((l,f)=>{let u=e.state.spec_changes[f];return u!==void 0&&l.capability===u.capability&&l.source===u.source&&(l.operation===u.operation||r?.has(l.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n;try{n=await jl({...e,specChanges:t})}catch{return{drifted:!0,reason:"Native Shape artifacts changed or became invalid"}}let{acceptance:a}=n,o=e.state.acceptance.map(({source:l,text:f})=>({source:l,text:f}));if(!qp(o,a))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let s;try{s=await Mt({changeDir:ce(e.paths,e.state.name),acceptanceIds:a.map(({id:l})=>l),validation:Mr({...e.state,acceptance:a})})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return e.state.phase==="shape"&&e.state.status==="await-user"&&e.state.loop.next_action==="confirm-shape"&&e.state.shape_confirmation_hash===void 0?{drifted:!0,reason:"Native Shape confirmation fingerprint is missing"}:e.state.shape_confirmation_hash!==void 0&&$l({formalHash:n.formalHash,childrenHash:s?.hash??null,coordinationMode:e.state.coordination_mode})!==e.state.shape_confirmation_hash?{drifted:!0,reason:"Native Shape artifacts changed"}:(s?Zi({acceptance:a,children:s.contract}):null)===(e.state.children_contract_hash??null)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native child declarations changed"}}async function gt(e){let t=await So(e);if(!t.drifted)return;let r=t.reason??"Native confirmed requirements changed";throw await Dl({paths:e.paths,state:e.state,reason:r}),new Error(`${r}; Native change returned to Shape and requires confirmation`)}async function tm(e){return x(e.paths,`submit portable candidate ${e.name}`,async()=>{let t=await _(e.paths,e.name);if(await gt({paths:e.paths,state:t}),await Mt({changeDir:ce(e.paths,t.name),acceptanceIds:t.acceptance.map(({id:a})=>a),validation:Mr(t)})||t.children_contract_hash){let a=await nt({paths:e.paths,state:t});if(!a?.confirmed||!a.allDone)throw new Error("Native parent Build advances child changes before parent review");if(t.loop.stage==="repairing"&&t.verification_result==="fail")throw new Error("Native parent verification failed; complete the repair child first")}let i=Lh({state:t,input:e.input}),n=await me({paths:e.paths,previous:t,next:i});return await V(D(e.paths,t.name),ae({portableState:n,projectRoot:e.paths.projectRoot,branch:Ee(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function Eo(e){let t=await _(e.paths,e.name),r={trigger:e.trigger,parent:e.name,advanced:!1,message:null,blocker:null};if(t.phase!=="build"||t.status!=="active")return{state:t,parentAdvance:r};let i=await nt({paths:e.paths,state:t});if(!i||!i.confirmed||!i.allDone)return{state:t,parentAdvance:{...r,blocker:i&&!i.confirmed?"Supervisor child declarations require Shape confirmation":null}};if(t.loop.stage==="repairing"&&t.verification_result==="fail")return{state:t,parentAdvance:{...r,blocker:"Native parent verification failed; add and confirm a repair child"}};let n=t.language==="zh-CN"?"全部 Child 已完成;Supervisor 父级候选需要独立代码审查后再进入验证":"All Children are complete; the Supervisor parent candidate needs an independent code review before verification.";return{state:t,parentAdvance:{...r,message:n}}}function Ol(e,t,r){return{id:e.id,name:e.name,operationId:t,status:"planned",repeatable:e.repeatable,timeoutMs:e.timeoutMs,executionCount:0,argv:[e.executable,...e.argv],cwd:fo(r,e.cwdRef),exitCode:null,startedAt:null,completedAt:null,log:`logs/checks/${t}-${e.id}.log`}}function rm(e,t,r,i){if(!e.repeatable)throw new Error(`Native check ${e.id} was interrupted and is not repeatable; user resolution is required`);return{...Ol(t,r,i),executionCount:e.executionCount}}function im(e,t){let r=oe.relative(oe.resolve(e),oe.resolve(t));if(oe.isAbsolute(r)||r===".."||r.startsWith(`..${oe.sep}`))throw new Error("Native local check cwd escaped the project root");let i=r.length===0?".":r.split(oe.sep).join("/");return fo(e,i),i}function _l(e,t){let[r,...i]=e.argv;if(!r)throw new Error(`Native local check ${e.id} has no executable`);return en({id:e.id,name:e.id,executable:r,argv:i,cwdRef:im(t,e.cwd),timeoutMs:e.timeoutMs,repeatable:e.repeatable})}function Ax(e){return e.startedAt===null||e.completedAt===null?0:Math.max(0,Date.parse(e.completedAt)-Date.parse(e.startedAt))}function Wr(e){let t=new Map;for(let r of e.supplied){if(t.has(r.id))throw new Error(`Native Runtime check summaries contain duplicate ID ${r.id}`);t.set(r.id,r)}return e.local.checks.map(r=>{if(r.status==="planned"||r.status==="running")throw new Error(`Native Runtime check ${r.id} has not completed`);let i=e.requestedNames?.get(r.id)??r.name;return{id:r.id,name:H(i),argv_display:wl(r.argv.slice(1)).map(n=>H(n)),argv_truncated:!1,cwd_ref:im(e.projectRoot,r.cwd),status:r.status,exit_code:r.exitCode,duration_ms:Ax(r)}})}function _x(e){return{id:e.id,name:e.name,executable:e.executable,argv:[...e.argv],cwdRef:e.cwdRef,timeoutMs:e.timeoutMs,repeatable:e.repeatable}}function cn(e){if(e.local===null||e.local.change!==e.state.name)return ae({portableState:e.state,projectRoot:e.projectRoot,branch:Ee(e.projectRoot)});let t=e.local.execution?.operationId??Il();return{...e.local,basedOnStateVersion:e.state.state_version,execution:{operationId:t,stage:"checking",actor:"runtime",executionId:null,status:"completed",startedAt:e.local.execution?.startedAt??new Date().toISOString(),requestCheckRounds:0},checks:e.local.checks.map(r=>r.status==="running"||r.status==="planned"?{...r,operationId:t,status:"interrupted"}:{...r,operationId:t})}}async function zr(e){try{let t=await ot(D(e.paths,e.state.name));return t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version?null:t}catch{return null}}function nm(e){let{state:t,local:r,expected:i}=e;if(t.state_version!==i.stateVersion||t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.loop.iteration!==i.iteration||t.loop.attempt!==i.attempt||t.builder_handoff===null||r===null||r.basedOnStateVersion!==t.state_version||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running"||r.execution.executionId!==i.verifierExecutionRef)throw new Error("Native Verifier execution message is stale for the current attempt");return r}function Ix(e){let{state:t,local:r,envelope:i}=e;if(!ho(i))throw new Error("Native Verifier result must come from the trusted Runner channel");if(t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.builder_handoff===null)throw new Error("Native Verifier result is stale for the current workflow state");if(i.candidateId!==t.builder_handoff.candidate_id||i.identityProvider!==t.builder_handoff.identity_provider||i.verifierExecutionRef===t.builder_handoff.builder_execution_ref)throw new Error("Native Verifier result is stale for the current candidate or identity");if(r===null||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running"||r.execution.executionId!==null&&r.execution.executionId!==i.verifierExecutionRef)throw new Error("Native Verifier result is stale for the active execution");return i}function Tx(e){return e.kind==="final-result"?{iteration:e.result.iteration,attempt:e.result.attempt}:{iteration:e.iteration,attempt:e.attempt}}async function ko(e){let t=await zr({paths:e.paths,state:e.state}),r=Jh({state:e.state,summary:e.summary}),i=await me({paths:e.paths,previous:e.state,next:r});return await V(D(e.paths,e.state.name),cn({local:t,state:i,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),i}function Xh(e,t,r){return e.checks.length!==t.length?!1:e.checks.every((i,n)=>_l(i,r)===en(t[n]))}async function jx(e){return x(e.paths,`reserve portable checks ${e.name}`,async()=>{let t=await _(e.paths,e.name);if(await gt({paths:e.paths,state:t}),t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native checks require Verify ready state");let r=D(e.paths,t.name),i=(await Al({file:r,portableState:t,projectRoot:e.projectRoot,branch:Ee(e.projectRoot),containedRoot:e.paths.runtimeDir})).state;if(i.execution?.stage==="checking"&&i.execution.actor==="runtime"&&Xh(i,e.plans,e.projectRoot)){let o=i.execution;if(o.status==="running")throw new Error("Native check plan is already in progress");let s=i.checks.filter(c=>c.status==="interrupted");if(s.length===0&&o.status==="completed"){let c=new Map(e.plans.map(({id:l,name:f})=>[l,f]));return{kind:"reuse",state:t,checks:Wr({local:i,projectRoot:e.projectRoot,supplied:[],requestedNames:c})}}if(s.length>0&&s.some(c=>!c.repeatable)){let c=an({state:t,reason:`A non-repeatable Runtime check was interrupted (${s.filter(f=>!f.repeatable).map(({id:f})=>f).join(", ")}); a new Builder candidate is required before it can run again.`}),l=await me({paths:e.paths,previous:t,next:c});throw await V(D(e.paths,t.name),ae({portableState:l,projectRoot:e.paths.projectRoot,branch:Ee(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),new Error(`Native check ${s.find(f=>!f.repeatable).id} was interrupted and is not repeatable; the change returned to Build for a new candidate`)}}if(i.execution!==null&&i.checks.length>0){if(!(i.execution.stage==="checking"&&i.execution.actor==="runtime"&&i.checks.some(s=>s.status==="interrupted")&&Xh(i,e.plans,e.projectRoot)))throw new Error("Native check plan was already resolved with a different plan")}else if(i.execution!==null||i.checks.length>0)throw new Error("Native check plan was already resolved with a different plan");let n=Il(),a={...i,execution:{operationId:n,stage:"checking",actor:"runtime",executionId:null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:e.plans.map(o=>{let s=i.checks.find(c=>c.id===o.id);return s?.status==="interrupted"?rm(s,o,n,e.projectRoot):s?{...s,operationId:n}:Ol(o,n,e.projectRoot)})};return await V(r,a,{containedRoot:e.paths.runtimeDir}),{kind:"execute",state:t,local:a,plans:e.plans.filter(o=>{let s=i.checks.find(c=>c.id===o.id);return s===void 0||s.status==="interrupted"})}})}async function No(e){return x(e.paths,`update portable checks ${e.state.name}`,async()=>{let t=await _(e.paths,e.state.name);if(t.state_version!==e.state.state_version||t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native check plan state changed during execution");let r=D(e.paths,t.name),i=await ot(r);if(i===null||i.basedOnStateVersion!==t.state_version||i.execution?.operationId!==e.operationId||i.execution.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="running")throw new Error("Native check plan reservation changed during execution");let n=e.update(i);return await V(r,n,{containedRoot:e.paths.runtimeDir}),n})}async function am(e){let t=e.projectRoot??e.paths.projectRoot;if(new Set(e.plans.map(({id:c})=>c)).size!==e.plans.length)throw new Error("Native check plan contains duplicate IDs");let r=[],i=new Set;for(let c of e.plans){po(t,c);let l=en(c);i.has(l)||(i.add(l),r.push(c))}let n=await jx({...e,plans:r,projectRoot:t});if(n.kind==="reuse")return n;let a=n.local.execution.operationId,o=Ve(e.paths,n.state.name);try{for(let c of n.plans){let l=new Date().toISOString();await No({paths:e.paths,state:n.state,operationId:a,update:u=>({...u,checks:u.checks.map(d=>d.id===c.id?{...d,status:"running",executionCount:d.executionCount+1,startedAt:l}:d)})});let f=await yl({projectRoot:t,runtimeDir:o,operationId:a,plan:c});await No({paths:e.paths,state:n.state,operationId:a,update:u=>({...u,checks:u.checks.map(d=>d.id===c.id?{...d,status:f.status,exitCode:f.exitCode,startedAt:f.startedAt,completedAt:f.completedAt,log:f.logRef}:d)})})}await No({paths:e.paths,state:n.state,operationId:a,update:c=>({...c,execution:{...c.execution,status:"completed"}})})}catch(c){try{await No({paths:e.paths,state:n.state,operationId:a,update:l=>({...l,execution:{...l.execution,status:"interrupted"},checks:l.checks.map(f=>f.status==="planned"||f.status==="running"?{...f,status:"interrupted"}:f)})})}catch{}throw c}let s=await ot(D(e.paths,n.state.name));if(s===null)throw new Error("Native Runtime check state disappeared after execution");return{state:n.state,checks:Wr({local:s,projectRoot:t,supplied:[]})}}async function $x(e){let t=D(e.paths,e.state.name),r=e.local;if(r===null||r.change!==e.state.name||r.basedOnStateVersion!==e.state.state_version||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running")throw new Error("Native Verifier request-checks has no active local execution");if(r.execution.executionId!==null&&r.execution.executionId!==e.envelope.verifierExecutionRef)throw new Error("Native Verifier request-checks changed execution within the same attempt");if(r.execution.requestCheckRounds>=Sl)throw new Error(`Native Verifier request-checks exceeded ${Sl} rounds for this attempt`);let i=new Map,n=new Map,a=new Map;for(let m of r.checks){let v=_l(m,e.projectRoot);n.set(v,m),m.status!=="interrupted"&&i.set(v,m),a.set(m.id,v)}let o=new Map,s=new Map;for(let m of e.response.checks){let v=_x(m);po(e.projectRoot,v);let h=en(v),p=s.get(v.id);if(p!==void 0&&p!==h)throw new Error(`Native Verifier check ID ${v.id} refers to conflicting commands`);let w=a.get(v.id);if(w!==void 0&&w!==h)throw new Error(`Native Verifier check ID ${v.id} conflicts with a Runtime check`);s.set(v.id,h);let g=n.get(h);if(g?.status==="interrupted"&&!g.repeatable)throw new Error(`Native check ${g.id} was interrupted and is not repeatable; user resolution is required`);o.has(h)||o.set(h,v)}let c=[...o.entries()],l=c.filter(([m])=>!i.has(m));if(r.execution.requestCheckRounds>0&&l.length===0)throw new Error("Native Verifier repeatedly requested only equivalent checks");let f=r.execution.requestCheckRounds+1,u=new Map(c.map(([,m])=>[m.id,m.name])),d={...r,execution:{...r.execution,stage:"checking",actor:"runtime",executionId:e.envelope.verifierExecutionRef,requestCheckRounds:f},checks:[...r.checks.map(m=>{let v=_l(m,e.projectRoot),h=o.get(v);return h&&m.status==="interrupted"?rm(m,h,r.execution.operationId,e.projectRoot):m}),...l.filter(([m])=>!n.has(m)).map(([,m])=>Ol(m,r.execution.operationId,e.projectRoot))]};return await V(t,d,{containedRoot:e.paths.runtimeDir}),{state:e.state,local:d,verifierExecutionRef:e.envelope.verifierExecutionRef,round:f,novelPlans:l.map(([,m])=>m),requestedNames:u,reusedCheckIds:c.filter(([m])=>i.has(m)).map(([,m])=>m.id),suppliedChecks:e.suppliedChecks}}async function bo(e){return x(e.paths,`update Verifier-requested checks ${e.reservation.state.name}`,async()=>{let t=await _(e.paths,e.reservation.state.name);if(t.state_version!==e.reservation.state.state_version||t.phase!=="verify"||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier request-checks state changed during execution");let r=D(e.paths,t.name),i=await ot(r),n=i?.execution;if(i===null||i.basedOnStateVersion!==t.state_version||n===null||n===void 0||n.operationId!==e.reservation.local.execution?.operationId||n.stage!=="checking"||n.actor!=="runtime"||n.status!=="running"||n.executionId!==e.reservation.verifierExecutionRef||n.requestCheckRounds!==e.reservation.round)throw new Error("Native Verifier request-checks reservation changed during execution");let a=e.update(i);return await V(r,a,{containedRoot:e.paths.runtimeDir}),a})}async function Ox(e){let t;try{for(let r of e.reservation.novelPlans){let i=new Date().toISOString();t=await bo({paths:e.paths,reservation:e.reservation,update:a=>({...a,checks:a.checks.map(o=>o.id===r.id?{...o,status:"running",executionCount:o.executionCount+1,startedAt:i}:o)})});let n=await yl({projectRoot:e.projectRoot,runtimeDir:Ve(e.paths,e.reservation.state.name),operationId:e.reservation.local.execution.operationId,plan:r});t=await bo({paths:e.paths,reservation:e.reservation,update:a=>({...a,checks:a.checks.map(o=>o.id===r.id?{...o,status:n.status,exitCode:n.exitCode,startedAt:n.startedAt,completedAt:n.completedAt,log:n.logRef}:o)})})}t=await bo({paths:e.paths,reservation:e.reservation,update:r=>({...r,execution:{...r.execution,stage:"verifying",actor:"verifier",executionId:e.reservation.verifierExecutionRef}})})}catch(r){try{await bo({paths:e.paths,reservation:e.reservation,update:i=>({...i,execution:{...i.execution,status:"interrupted"},checks:i.checks.map(n=>n.status==="planned"||n.status==="running"?{...n,status:"interrupted"}:n)})})}catch{}throw r}return{checks:Wr({local:t,projectRoot:e.projectRoot,supplied:e.reservation.suppliedChecks,requestedNames:e.reservation.requestedNames}),requestChecks:{round:e.reservation.round,reusedCheckIds:e.reservation.reusedCheckIds,executedCheckIds:e.reservation.novelPlans.map(({id:r})=>r)}}}async function om(e){return x(e.paths,`dispatch portable verifier ${e.name}`,async()=>{let t=await _(e.paths,e.name),r=e.projectRoot??e.paths.projectRoot;await gt({paths:e.paths,state:t});let i=(await Al({file:D(e.paths,t.name),portableState:t,projectRoot:r,branch:Ee(r),containedRoot:e.paths.runtimeDir})).state;if(i.execution?.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="completed")throw new Error("Native check plan must be explicitly resolved before Verifier dispatch");Wr({local:i,projectRoot:r,supplied:e.checks});let n=Vh(t),a=await me({paths:e.paths,previous:t,next:n}),o=D(e.paths,t.name),s=Il();return await V(o,{...i,basedOnStateVersion:a.state_version,execution:{operationId:s,stage:"verifying",actor:"verifier",executionId:e.verifierExecutionId??null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:i.checks.map(c=>({...c,operationId:s}))},{containedRoot:e.paths.runtimeDir}),a})}async function sm(e){if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let t=await x(e.paths,`apply portable verifier ${e.name}`,async()=>{let r=await _(e.paths,e.name),i=e.projectRoot??e.paths.projectRoot;await gt({paths:e.paths,state:r});let n=await zr({paths:e.paths,state:r}),a=Ix({state:r,local:n,envelope:e.envelope}),o;try{o=kl(a.payload)}catch(u){let d=`Native Verifier response was invalid: ${u.message}`,m=await ko({paths:e.paths,state:r,summary:d});throw new Error(`${d}; execution error ${m.loop.execution_failure_count}/${nn} was recorded`,{cause:u})}let s=Tx(o);if(s.iteration!==r.loop.iteration||s.attempt!==r.loop.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");let c=[],l;try{n!==null&&(c=Wr({local:n,projectRoot:i,supplied:e.checks}));let u=Mh({state:r,envelope:a,checks:c,maxVerifyFailures:e.maxVerifyFailures});if(u.response.kind==="request-checks"){if(n===null)throw new Error("Native Verifier request-checks has no active local execution");let d=await $x({paths:e.paths,projectRoot:i,state:r,local:n,envelope:a,response:u.response,suppliedChecks:c});return{kind:"request-checks",state:r,response:u.response,reservation:d}}if(n===null||n.execution===null||n.execution.stage!=="verifying"||n.execution.actor!=="verifier"||n.execution.status!=="running")throw new Error("Native Verifier final result has no active local execution");if(n.execution.executionId!==null&&n.execution.executionId!==a.verifierExecutionRef)throw new Error("Native Verifier final result changed execution within the same attempt");l=u}catch(u){let d=`Native Verifier response was invalid: ${u.message}`,m=await ko({paths:e.paths,state:r,summary:d});throw new Error(`${d}; execution error ${m.loop.execution_failure_count}/${nn} was recorded`,{cause:u})}let f=await me({paths:e.paths,previous:r,next:l.state});return await V(D(e.paths,r.name),f.loop.next_action==="resolve-verifier-blocker"||f.loop.next_action==="run-final-full-verification"?cn({local:n,state:f,projectRoot:i}):ae({portableState:f,projectRoot:i,branch:Ee(i)}),{containedRoot:e.paths.runtimeDir}),f.verification!==null&&await qr({file:oe.join(ce(e.paths,r.name),"verification.md"),state:f}),{kind:"final-result",result:{state:f,response:l.response,checks:c,requestChecks:null}}});if(t.kind==="final-result")return t.result;try{let r=await Ox({paths:e.paths,projectRoot:e.projectRoot??e.paths.projectRoot,reservation:t.reservation});return{state:t.state,response:t.response,checks:r.checks,requestChecks:r.requestChecks}}catch(r){let i=`Native Verifier response was invalid: ${r.message}`,n=await x(e.paths,`record Verifier-requested check failure ${e.name}`,async()=>{let a=await _(e.paths,e.name);return a.state_version!==t.state.state_version?null:ko({paths:e.paths,state:a,summary:i})});throw new Error(n?`${i}; execution error ${n.loop.execution_failure_count}/${nn} was recorded`:`${i}; the portable state changed before the execution error could be recorded`,{cause:r})}}async function cm(e){return x(e.paths,`record portable verifier failure ${e.name}`,async()=>{let t=await _(e.paths,e.name),r=await zr({paths:e.paths,state:t});if(nm({state:t,local:r,expected:e.expected}),e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");return ko({paths:e.paths,state:t,summary:e.summary})})}async function lm(e){return x(e.paths,`record unavailable portable verifier ${e.name}`,async()=>{let t=await _(e.paths,e.name);await gt({paths:e.paths,state:t});let r=await zr({paths:e.paths,state:t}),i=nm({state:t,local:r,expected:e.expected});if(e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");let n=Wr({local:i,projectRoot:e.paths.projectRoot,supplied:[]}),a=qh({state:t,checks:n,verifierExecutionRef:i.execution.executionId,summary:e.summary}),o=await me({paths:e.paths,previous:t,next:a});return await V(D(e.paths,t.name),cn({local:i,state:o,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),await qr({file:oe.join(ce(e.paths,t.name),"verification.md"),state:o}),o})}async function um(e){return x(e.paths,`confirm portable Skill-coordinated pass ${e.name}`,async()=>{let t=await _(e.paths,e.name);zt({state:t,expected:e.expectedContinuation,action:"accept-result"}),await gt({paths:e.paths,state:t});let r=await W(e.paths,e.name);if(r?.finalVerification.status==="pending"){if(Yi(r).stateVersion!==r.stateVersion)return hm({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; rerun the final full verification."});await ne(e.paths,Xi(r,t))}let i=Fh(t),n=await me({paths:e.paths,previous:t,next:i});return await V(D(e.paths,t.name),ae({portableState:n,projectRoot:e.paths.projectRoot,branch:Ee(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await qr({file:oe.join(ce(e.paths,t.name),"verification.md"),state:n}),n})}async function Hx(e){let t=await _(e.paths,e.name),r=await W(e.paths,e.name),i=await eo(e.paths,{kind:"archive",change:e.name}),n=i?.kind==="archive"?i:null;if(n&&r?.finalVerification.status==="pending"){if(n.journal.status!=="prepared"||n.journal.next_spec_index!==0)throw new Error("Native Supervisor final verification changed after Archive applied side effects; doctor intervention is required");if(t.phase==="verify"&&t.status==="active"&&t.verification===null&&t.verification_result==="pending"&&t.loop.stage==="verify-ready")return await lr.rm(n.file,{force:!0}),{state:t,action:"rerun-final-verification"}}if(t.archived||t.verification===null||t.verification_result!=="pass"||r?.finalVerification.status!=="pending")return{state:t,action:"none"};let a=Yi(r);if(n||a.stateVersion!==r.stateVersion){let o=await hm({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; the final full verification will resume automatically."});return n&&await lr.rm(n.file,{force:!0}),{state:o,action:"rerun-final-verification"}}return await ne(e.paths,Xi(r,t)),{state:t,action:"recorded-final-verification"}}async function Hl(e){return x(e.paths,`recover Supervisor final verification ${e.name}`,()=>Hx(e),{allowedPortableTransaction:{kind:"archive",change:e.name}})}async function dm(e){return x(e.paths,`confirm unavailable portable verifier ${e.name}`,async()=>{let t=await _(e.paths,e.name);zt({state:t,expected:e.expectedContinuation,action:"confirm-verifier-unavailable"}),await gt({paths:e.paths,state:t});let r=Wh({state:t,summary:e.summary}),i=await me({paths:e.paths,previous:t,next:r});return await V(D(e.paths,t.name),ae({portableState:i,projectRoot:e.paths.projectRoot,branch:Ee(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await qr({file:oe.join(ce(e.paths,t.name),"verification.md"),state:i}),i})}async function fm(e){return x(e.paths,`resolve portable verifier blocker ${e.name}`,async()=>{let t=await _(e.paths,e.name);zt({state:t,expected:e.expectedContinuation,action:"resolve-verifier-blocker"}),await gt({paths:e.paths,state:t});let r=await zr({paths:e.paths,state:t}),i=zh(t,{reason:e.reason}),n=await me({paths:e.paths,previous:t,next:i});return await V(D(e.paths,t.name),cn({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function pm(e){return x(e.paths,`retry portable verifier ${e.name}`,async()=>{let t=await _(e.paths,e.name);zt({state:t,expected:e.expectedContinuation,action:"retry-verifier"});let r=await zr({paths:e.paths,state:t}),i=Gh(t),n=await me({paths:e.paths,previous:t,next:i});return await V(D(e.paths,t.name),cn({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function xo(e){return x(e.paths,`return portable change ${e.name} to Build`,async()=>{let t=await _(e.paths,e.name);if(zt({state:t,expected:e.expectedContinuation,action:"revise-implementation"}),t.phase==="build")return t;let r=an({state:t,reason:e.reason}),i=await me({paths:e.paths,previous:t,next:r});return await V(D(e.paths,t.name),ae({portableState:i,projectRoot:e.paths.projectRoot,branch:Ee(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),i})}async function Co(e){return x(e.paths,`return portable change ${e.name} to Shape`,async()=>{let t=await _(e.paths,e.name);if(zt({state:t,expected:e.expectedContinuation,action:"revise-requirements"}),e.allowedPhases&&!e.allowedPhases.includes(t.phase))throw new Error("--revise-requirements is only valid from Verify or Archive");return t.phase==="shape"?t:Dl({paths:e.paths,state:t,reason:e.reason})})}async function Dl(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let i={...pe(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:H(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"prepare-shape-confirmation"}};delete i.shape_confirmation_hash,delete i.children_contract_hash;let n=await me({paths:e.paths,previous:t,next:i});return await V(D(e.paths,t.name),ae({portableState:n,projectRoot:e.paths.projectRoot,branch:Ee(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function hm(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);if(t.verification===null||t.verification_result!=="pass")throw new Error("Native Supervisor recovery requires a persisted final verification pass");let i={...pe(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:H(e.reason),completed_at:new Date().toISOString()}),phase:"verify",status:"active",state_version:t.state_version+1,acceptance:t.acceptance.map(a=>({...a,result:"pending",reason:null})),blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{...t.loop,stage:"verify-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:"run-final-full-verification"}},n=await me({paths:e.paths,previous:t,next:i});return await V(D(e.paths,t.name),ae({portableState:n,projectRoot:e.paths.projectRoot,branch:Ee(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function Po(e){if(e.state.verification===null)return"not-applicable";let t=oe.join(ce(e.paths,e.state.name),"verification.md");return await Yh({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await qr({file:t,state:e.state}),"rebuilt")}var mm=["evidence.md","repair.md","archive.md","checkpoint.md"],Lx="verification.md";async function Vx(e,t){let r=await eo(e,{kind:"migration",change:t});return r?.kind==="migration"?r.journal:null}async function vm(e,t){await ln.mkdir(e.transactionsDir,{recursive:!0}),await ye(Za(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function gm(e,t,r={}){let i=r.removeVerificationReport===!1?mm:[...mm,Lx];await Promise.all([ln.rm(Ve(e,t),{recursive:!0,force:!0}),ln.rm(_c(e,t),{recursive:!0,force:!0}),...i.map(n=>ln.rm(Bx.join(rt(e,t),n),{force:!0}))])}async function wm(e,t){await V(D(e,t.name),ae({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function ym(e,t){try{let r=await Mi(e,t);if(r?.schema==="comet.native.workspace.v3")return{isolation:r.isolation,change_branch:r.changeBranch,target_branch:r.targetBranch,finish:r.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function Nm(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let r=z(e.projectRoot);if(!r.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(r.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${r.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!r.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function Mx(e){let t=rt(e.paths,e.state.name),r=await Y({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),i=[];for(let n of e.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await Y({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return Ya({briefMarkdown:r.text,specs:i})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function bm(e,t){let r=await $p(e,t);if(!r.state)throw new Error(`Native legacy change ${t} is unreadable`);return r.state}async function km(e){return x(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await Vx(e.paths,e.name),r=await sn(e.paths,e.name)?await Me(Je(e.paths,e.name)):null;if(!t&&r)return await gm(e.paths,e.name,{removeVerificationReport:!1}),await wm(e.paths,r),r;let i=null,n=null;for(t||(i=await bm(e.paths,e.name),n=await ym(e.paths,e.name),Nm(e.paths,n),t={schema:Xa,id:Dx(),change:i.name,fromSchema:i.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await vm(e.paths,t));;){let a=zp(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?r||(i??=await bm(e.paths,e.name),n??=await ym(e.paths,e.name),Nm(e.paths,n),r=Wp({state:i,acceptance:await Mx({paths:e.paths,state:i}),workspace:n,migratedAt:e.now}),await Da(Je(e.paths,e.name),r,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await gm(e.paths,e.name):a.action==="commit-transaction"&&(r??=await Me(Je(e.paths,e.name)),await wm(e.paths,r)),t={...t,status:a.nextStatus},await vm(e.paths,t)}return await ln.rm(Za(e.paths,{kind:"migration",change:e.name}),{force:!0}),r??Me(Je(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as Em}from"node:fs";import xm from"node:path";import{promises as Bl}from"node:fs";import Fx from"node:path";var qx=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),Wx=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),zx=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task"]),Jx=new Set(["status","summary"]);function Ro(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Ao(e,t,r){let i=new Set(Object.keys(e)),n=[...t].filter(o=>!i.has(o)),a=[...i].filter(o=>!t.has(o));return n.length===0&&a.length===0?null:`${r} fields must be exact (missing: ${n.join(", ")||"none"}; unexpected: ${a.join(", ")||"none"})`}function Gx(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((r,i)=>r===t[i])}function ur(e,t,r){return{status:"incompatible",file:e,snapshot:t,message:r}}function Ux(e,t,r,i){let n=Ro(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=Ao(n,qx,"Native Supervisor overlay");if(a)return a;if(i.stateVersion!==1)return"Native Supervisor overlay stateVersion is not 1";if(i.parent!==t.name)return`Native Supervisor overlay parent ${i.parent} does not match ${t.name}`;let o=Ro(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=Ao(o,Wx,"Native Supervisor integration");if(s)return s;if(i.integration.headCommit!==i.integration.targetCommit)return"Native Supervisor integration headCommit has advanced beyond targetCommit";if(!Array.isArray(n.history)||n.history.length!==0)return"Native Supervisor overlay history is not empty";let c=Ro(n.finalVerification,"Native Supervisor finalVerification");if(!c)return"Native Supervisor finalVerification must be an object";let l=Ao(c,Jx,"Native Supervisor finalVerification");if(l)return l;if(i.finalVerification.status!=="pending"||i.finalVerification.summary!==null)return"Native Supervisor final verification already contains progress";if(!Array.isArray(n.children))return"Native Supervisor children must be an array";if(n.children.length!==r.children.length)return"Native Supervisor child count does not match the legacy children contract";for(let[f,u]of n.children.entries()){let d=Ro(u,`Native Supervisor child ${f}`);if(!d)return`Native Supervisor child ${f} must be an object`;let m=Ao(d,zx,`Native Supervisor child ${f}`);if(m)return m;let v=r.children[f];if(d.name!==v.name||d.summary!==v.summary||!Gx(d.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(d.status!==h)return`Native Supervisor child ${v.name} has progressed beyond its initial ${h} status`;if(d.baseCommit!==null||d.candidateCommit!==null||d.verifiedCommit!==null||d.integrationCommit!==null||d.verification!==null||d.blocker!==null||d.projectRoot!==null||d.task!==null)return`Native Supervisor child ${v.name} contains execution progress`;if(!Array.isArray(d.checks)||d.checks.length!==0)return`Native Supervisor child ${v.name} contains integration checks`}return null}async function un(e){let t=Lr(e.paths,e.state.name),r;try{let c=await Bl.lstat(t);if(!c.isFile()||c.isSymbolicLink())return ur(t,"","Native Supervisor overlay is not a regular file");r=await Bl.readFile(t,"utf8")}catch(c){return c.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:ur(t,"",`Native Supervisor overlay cannot be read: ${c.message}`)}let i;try{i=JSON.parse(r)}catch(c){return ur(t,r,`Native Supervisor overlay is invalid JSON: ${c.message}`)}let n=Fx.join(e.paths.changesDir,e.state.name),a;try{a=await Mt({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:c})=>c),policy:"advisory"})}catch(c){return ur(t,r,`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:r};let o;try{o=await W(e.paths,e.state.name)}catch(c){return ur(t,r,`Native Supervisor overlay is invalid: ${c.message}`)}if(!o)return ur(t,r,"Native Supervisor overlay disappeared during inspection");let s=Ux(i,e.state,a.contract,o);return s?ur(t,r,s):{status:"repairable-legacy-overlay",file:t,message:"An exact unstarted v2 Supervisor overlay is stale beside a legacy children.v1 contract",snapshot:r}}async function Sm(e){let t=await un({paths:e.paths,state:e.state});if(t.status!=="repairable-legacy-overlay"||t.snapshot!==e.expected.snapshot)throw new Error("Native Supervisor overlay changed before the safe repair could be applied");await Bl.rm(t.file,{force:!1})}function Ll(e,t){let r=z(e.projectRoot);if(t.workspace.change_branch!==null){if(!r.isGitWorktree)return"The portable change requires a Git branch/worktree";if(r.currentBranch!==t.workspace.change_branch)return`Expected Native change branch ${t.workspace.change_branch}, current branch is ${r.currentBranch??"(detached)"}`}return t.workspace.isolation==="current"?null:r.isGitWorktree?t.workspace.isolation==="worktree"&&!r.isSecondaryWorktree?"The portable change requires its linked worktree":null:"The portable change requires a Git branch/worktree"}function Kx(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function Yx(e,t,r){let i=new Date().toISOString(),n=e.verification===null?e:pe(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:H(t),completed_at:i});return C({...n,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:r?Kx(e):e.acceptance,verification:null,verification_result:"pending",verification_report:null,blockers:[],loop:{...e.loop,stage:"verify-ready",next_action:"run-required-checks-and-dispatch-verifier"}})}async function Xx(e){try{let t=await ot(e);return t===null?{local:null,reason:"missing"}:{local:t,reason:"available"}}catch(t){if(t.code&&t.code!=="ENOENT")throw t;return{local:null,reason:"invalid"}}}async function Vl(e){return x(e.paths,`recover portable change ${e.name}`,async()=>{let t=await _(e.paths,e.name);if(t.status==="done")return await Po({paths:e.paths,state:t}),{state:t,local:null,action:"done",reason:"done",message:"Archived Native changes do not require a local execution overlay."};let r=Ll(e.paths,t);if(r)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:r};let i=await un({paths:e.paths,state:t});if(i.status==="incompatible")return{state:t,local:null,action:"await-user",reason:"overlay-incompatible",message:i.message};let n=!1;i.status==="repairable-legacy-overlay"&&(await Sm({paths:e.paths,state:t,expected:i}),n=!0);let a=D(e.paths,e.name),o=await Xx(a),s=o.reason==="available"&&(o.local?.change!==t.name||o.local?.basedOnStateVersion!==t.state_version)?"stale":o.reason;if(s==="available"&&!e.preserveRunningExecution&&o.local?.execution!==null&&o.local?.execution?.status!=="completed"&&o.local&&(s="interrupted",o.local.execution?.status==="running"&&(o.local={...o.local,execution:{...o.local.execution,status:"interrupted"},checks:o.local.checks.map(v=>v.status==="planned"||v.status==="running"?{...v,status:"interrupted"}:v)},await V(a,o.local,{containedRoot:e.paths.runtimeDir}))),s==="available")return await Po({paths:e.paths,state:t}),{state:t,local:o.local,action:"resume-stable-boundary",reason:s,message:n?"Removed a stale legacy Supervisor overlay and resumed the portable state.":"Native local execution overlay matches the portable state."};let l=s==="interrupted"?o.local?.checks.find(v=>v.status==="interrupted"&&!v.repeatable):void 0;if(l){let v=an({state:t,reason:`Check ${l.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await Li({file:Je(e.paths,t.name),expectedStateVersion:t.state_version,next:v,containedRoot:e.paths.nativeRoot}),await Em.rm(xm.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let h=ae({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await V(a,h,{containedRoot:e.paths.runtimeDir}),{state:t,local:h,action:"resume-stable-boundary",reason:s,message:`Native check ${l.id} was not repeatable; the change returned to Build for a new candidate.`}}let f=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",u=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",d=f||u;if(d){let v=Yx(t,u?"Local Runtime was unavailable at Archive ready; the synchronized implementation must be verified again.":"The previous Verifier execution was unavailable; dispatch a new attempt from the stable Verify boundary.",u);t=await Li({file:Je(e.paths,t.name),expectedStateVersion:t.state_version,next:v,containedRoot:e.paths.nativeRoot})}let m=ae({portableState:t,projectRoot:e.paths.projectRoot,branch:z(e.paths.projectRoot).currentBranch});return await Em.mkdir(xm.dirname(D(e.paths,t.name)),{recursive:!0}),await V(a,m,{containedRoot:e.paths.runtimeDir}),await Po({paths:e.paths,state:t}),{state:t,local:m,action:d?"reverify":"resume-stable-boundary",reason:s,message:d?"Rebuilt local execution from the portable boundary; previous pass/execution was not reused.":`Rebuilt local execution from the portable ${t.phase}/${t.loop.stage} boundary.`}})}function Qx(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function xe(e){let t=e.acceptance.reduce((r,i)=>({...r,[i.result]:r[i.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0});return{schema:"comet.native.state-summary.v1",name:e.name,phase:e.phase,status:e.status,state_version:e.state_version,...e.coordination_mode===void 0?{}:{coordination_mode:e.coordination_mode},loop:e.loop,acceptance:t,unresolved_acceptance_ids:e.acceptance.filter(({result:r})=>r==="failed"||r==="blocked").map(({id:r})=>r),verification_result:e.verification_result,blockers:e.blockers.slice(0,8).map(r=>({owner:r.owner,reason:Qx(r.reason.text),acceptance_ids:r.acceptance_ids,resolution_action:r.resolution_action})),workspace:{isolation:e.workspace.isolation,change_branch:e.workspace.change_branch,target_branch:e.workspace.target_branch,finish:e.workspace.finish},archived:e.archived}}import{randomUUID as Im}from"node:crypto";import{promises as Cm}from"node:fs";import fn from"node:path";function Jr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ve(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function B(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} must be non-empty text`);return e}function Fl(e,t){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,i)=>B(r,`${t}[${i}]`))}function Zx(e){if(!Array.isArray(e))throw new Error("Native Builder checks must be an array");return e.map((t,r)=>{let i=Jr(t,`Native Builder check ${r}`);if(ve(i,["name","result","note"],`Native Builder check ${r}`),!["passed","failed","not-run"].includes(String(i.result)))throw new Error(`Native Builder check ${r} result is invalid`);if(i.note!==null&&typeof i.note!="string")throw new Error(`Native Builder check ${r} note is invalid`);return{name:B(i.name,`Native Builder check ${r} name`),result:i.result,note:i.note}})}function eC(e){if(!Array.isArray(e))throw new Error("Native Runtime checks must be an array");return e.map((t,r)=>{let i=Jr(t,`Native Runtime check ${r}`);if(ve(i,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Runtime check ${r}`),!Array.isArray(i.argv)||!i.argv.every(n=>typeof n=="string"))throw new Error(`Native Runtime check ${r} argv is invalid`);if(!Number.isSafeInteger(i.timeoutMs)||i.timeoutMs<1)throw new Error(`Native Runtime check ${r} timeoutMs is invalid`);if(typeof i.repeatable!="boolean")throw new Error(`Native Runtime check ${r} repeatable is invalid`);return{id:B(i.id,`Native Runtime check ${r} id`),name:B(i.name,`Native Runtime check ${r} name`),executable:B(i.executable,`Native Runtime check ${r} executable`),argv:[...i.argv],cwdRef:B(i.cwdRef,`Native Runtime check ${r} cwdRef`),timeoutMs:i.timeoutMs,repeatable:i.repeatable}})}function Pm(e,t){let r=e.stateVersion,i=e.iteration,n=e.attempt;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${t} stateVersion is invalid`);if(!Number.isSafeInteger(i)||i<1)throw new Error(`${t} iteration is invalid`);if(!Number.isSafeInteger(n)||n<1)throw new Error(`${t} attempt is invalid`);return{stateVersion:r,iteration:i,attempt:n,verifierExecutionRef:B(e.verifierExecutionRef,`${t} verifierExecutionRef`)}}function tC(e){let t=Jr(e,"Native Supervisor evidence");return ve(t,["summary","checks"],"Native Supervisor evidence"),{summary:B(t.summary,"Native Supervisor evidence summary"),checks:Fl(t.checks,"Native Supervisor evidence checks")}}function rC(e){if(!Array.isArray(e))throw new Error("Native Supervisor integration checks must be an array");return e.map((t,r)=>{let i=Jr(t,`Native Supervisor integration check ${r}`),n=new Set(["name","status","reason"]);if(Object.keys(i).some(a=>!n.has(a)))throw new Error(`Native Supervisor integration check ${r} fields are invalid`);if(!Object.hasOwn(i,"name")||!Object.hasOwn(i,"status"))throw new Error(`Native Supervisor integration check ${r} fields are invalid`);if(!["passed","failed","incomplete"].includes(String(i.status)))throw new Error(`Native Supervisor integration check ${r} status is invalid`);if(i.reason!==void 0&&i.reason!==null&&typeof i.reason!="string")throw new Error(`Native Supervisor integration check ${r} reason is invalid`);return{name:B(i.name,`Native Supervisor integration check ${r} name`),status:i.status,reason:i.reason??null}})}function iC(e){let t=Jr(e,"Native Runner input");if(t.kind==="builder-handoff"){ve(t,["kind","summary","addressed_acceptance_ids","checks","known_limits","review"],"Native Runner Builder input");let r=Jr(t.review,"Native Builder review");if(ve(r,["status","summary","reviewer_execution_ref"],"Native Builder review"),r.status!=="passed")throw new Error("Native Builder review status must be passed");return{kind:"builder-handoff",summary:B(t.summary,"Native Builder summary"),addressed_acceptance_ids:Fl(t.addressed_acceptance_ids,"Native Builder addressed acceptance IDs"),checks:Zx(t.checks),known_limits:Fl(t.known_limits,"Native Builder known limits"),review:{status:"passed",summary:B(r.summary,"Native Builder review summary"),reviewer_execution_ref:B(r.reviewer_execution_ref,"Native Builder reviewer execution ref")}}}if(t.kind==="dispatch-verifier")return ve(t,["kind","checks"],"Native Runner dispatch input"),{kind:"dispatch-verifier",checks:eC(t.checks)};if(t.kind==="verifier-response")return ve(t,["kind","response"],"Native Runner Verifier input"),{kind:"verifier-response",response:t.response};if(t.kind==="verifier-execution-error")return ve(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner execution error input"),{kind:"verifier-execution-error",summary:B(t.summary,"Native Verifier execution error summary"),...Pm(t,"Native Runner execution error input")};if(t.kind==="verifier-unavailable")return ve(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner unavailable Verifier input"),{kind:"verifier-unavailable",summary:B(t.summary,"Native unavailable Verifier summary"),...Pm(t,"Native Runner unavailable Verifier input")};if(t.kind==="supervisor-builder-result")return ve(t,["kind","child","runId","candidateCommit"],"Native Supervisor Builder input"),{kind:"supervisor-builder-result",child:B(t.child,"Native Supervisor child"),runId:B(t.runId,"Native Supervisor runId"),candidateCommit:B(t.candidateCommit,"Native Supervisor candidate commit")};if(t.kind==="supervisor-builder-failure")return ve(t,["kind","child","runId","reason"],"Native Supervisor Builder failure input"),{kind:"supervisor-builder-failure",child:B(t.child,"Native Supervisor child"),runId:B(t.runId,"Native Supervisor runId"),reason:B(t.reason,"Native Supervisor Builder failure reason")};if(t.kind==="supervisor-reconnect")return ve(t,["kind","child","runId"],"Native Supervisor reconnect input"),{kind:"supervisor-reconnect",child:B(t.child,"Native Supervisor child"),runId:B(t.runId,"Native Supervisor runId")};if(t.kind==="supervisor-cancel")return ve(t,["kind","child","runId","reason"],"Native Supervisor cancel input"),{kind:"supervisor-cancel",child:B(t.child,"Native Supervisor child"),runId:B(t.runId,"Native Supervisor runId"),reason:B(t.reason,"Native Supervisor cancellation reason")};if(t.kind==="supervisor-verifier-result"){if(ve(t,["kind","child","runId","verdict","evidence"],"Native Supervisor Verifier input"),!["pass","fail","incomplete"].includes(String(t.verdict)))throw new Error("Native Supervisor Verifier verdict is invalid");return{kind:"supervisor-verifier-result",child:B(t.child,"Native Supervisor child"),runId:B(t.runId,"Native Supervisor runId"),verdict:t.verdict,evidence:tC(t.evidence)}}if(t.kind==="supervisor-integrate")return ve(t,["kind","child","checks"],"Native Supervisor integration input"),{kind:"supervisor-integrate",child:B(t.child,"Native Supervisor child"),checks:rC(t.checks)};throw new Error("Native Runner input kind is invalid")}async function Tm(e,t){let r=fn.resolve(t,e),i=await Cm.lstat(r);if(!i.isFile()||i.isSymbolicLink())throw new Error("Native Runner input must be a regular non-symlink file");let n;try{n=JSON.parse(await Cm.readFile(r,"utf8"))}catch(a){throw new Error("Native Runner input must be valid JSON",{cause:a})}return iC(n)}function Rm(e){return`${Z}:${e}:${Im()}`}function Am(e,t,r,i){if(fn.resolve(I(e.projectRoot,["rev-parse","--show-toplevel"]))!==fn.resolve(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree identity is invalid`);if(I(e.projectRoot,["branch","--show-current"])!==i)throw new Error(`Native Supervisor ${r} result came from the wrong Child worktree branch`);if(!ut(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree must be clean before returning a commit`);if(I(e.projectRoot,["rev-parse","HEAD"])!==t)throw new Error(`Native Supervisor ${r} result is not bound to the worktree HEAD`);try{I(e.projectRoot,["merge-base","--is-ancestor",e.baseCommit,t])}catch(s){throw new Error(`Native Supervisor ${r} result is not based on its task base commit`,{cause:s})}}function nC(e,t){let r=z(e.projectRoot),i=fn.resolve(r.currentWorktreeRoot??"");if(!r.isGitWorktree||i!==fn.resolve(e.projectRoot))throw new Error("Native Supervisor task worktree identity is invalid");if(r.currentBranch!==t)throw new Error("Native Supervisor task is attached to the wrong Child branch");let n=I(e.projectRoot,["rev-parse","HEAD"]);if(e.role==="verifier"){if(!ut(e.projectRoot)||n!==e.baseCommit)throw new Error("Native Supervisor Verifier task worktree is not at its candidate commit");return}try{I(e.projectRoot,["merge-base","--is-ancestor",e.baseCommit,n])}catch(a){throw new Error("Native Supervisor Builder task base commit is not an ancestor of its HEAD",{cause:a})}}function dn(e){if(e.builder_handoff===null)throw new Error("Native Skill coordination has no current Builder candidate");if(e.builder_handoff.identity_provider!==Z)throw new Error("Native candidate is owned by a host identity adapter and cannot use the generic Skill coordination bridge");if(!e.builder_handoff.review)throw new Error("Native Skill coordination requires a passed read-only review");return e.builder_handoff}function aC(e){return[...e.history].reverse().find(({outcome:t})=>t==="recovery")?.summary}function _m(e){let{paths:t,state:r,checks:i,verifierExecutionRef:n,supervisor:a}=e,o=dn(r);if(!o.review)throw new Error("Native Skill coordination requires a passed read-only review");let s=aC(r),c=r.acceptance.filter(({result:l})=>l==="pending").map(({id:l})=>l);return{coordination:Z,change:r.name,candidateId:o.candidate_id,stateVersion:r.state_version,iteration:r.loop.iteration,attempt:r.loop.attempt,verifierExecutionRef:n,projectRoot:t.projectRoot,verificationRoot:a?.integration.worktree??t.projectRoot,changeDir:ce(t,r.name),supervisorStateRef:a?Lr(t,r.name):null,briefRef:r.brief,specRefs:r.spec_changes.map(({capability:l,operation:f,source:u})=>({capability:l,operation:f,ref:u})),acceptanceCount:r.acceptance.length,scopeIds:c,detailsPageArgs:["comet","native","status",r.name,"--details","--json","--project-root",t.projectRoot],...s===void 0?{}:{recoveryContext:s},builderReview:{status:o.review.status,summary:o.review.summary},runtimeChecks:i.map(l=>({...l}))}}async function Ml(e){dn(e.state);let t=await ot(D(e.paths,e.state.name));if(t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version||t.execution===null||t.execution.stage!=="verifying"||t.execution.actor!=="verifier"||t.execution.status!=="running"||t.execution.executionId===null)throw new Error("Native Skill coordination has no active Verifier attempt");return t.execution.executionId}async function jm(e){let t=e.input,r=await _(e.paths,e.name),i=await un({paths:e.paths,state:r});if(i.status==="incompatible")throw new Error(i.message);let n=i.status==="repairable-legacy-overlay"?null:await W(e.paths,e.name),a=n!==null&&r?.phase==="verify"&&n.children.every(({status:v})=>v==="integrated"||v==="archived"),o=n!==null&&r?.phase==="build"&&n.children.every(({status:v})=>v==="integrated"||v==="archived");if(n&&t.kind==="supervisor-builder-result")return x(e.paths,`apply Native Supervisor Builder result ${t.child}`,async()=>{let v=await W(e.paths,e.name);if(!v)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=v.children.find(({name:b})=>b===t.child);if(!h?.task||h.task.role!=="builder")throw new Error(`Native Supervisor Builder task is not active for ${t.child}`);try{Am(h.task,t.candidateCommit,"builder",`comet/supervisor/${v.parent}/${t.child}`)}catch(b){throw await ne(e.paths,oo(v,{child:t.child,runId:t.runId,reason:b.message})),b}let p=h.task.projectRoot,w=hh(v,t),g=cl(w,{role:"verifier",child:t.child,projectRoot:p,runId:Im()});await ne(e.paths,g.state);let y=await _(e.paths,e.name);return{state:y,supervisorTask:g.task,checks:[],requestChecks:null,verifierDispatch:null,continuation:Q(y)}});if(n&&t.kind==="supervisor-builder-failure")return x(e.paths,`cancel Native Supervisor Builder task ${t.child}`,async()=>{let v=await W(e.paths,e.name);if(!v)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=v.children.find(({name:g})=>g===t.child);if(!h?.task||h.task.role!=="builder")throw new Error(`Native Supervisor Builder failure is not valid for ${t.child}`);let p=ul(v,{child:t.child,runId:t.runId,reason:t.reason});await ne(e.paths,p);let w=await _(e.paths,e.name);return{state:w,supervisorState:p,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:Q(w)}});if(n&&t.kind==="supervisor-reconnect")return x(e.paths,`reconnect Native Supervisor task ${t.child}`,async()=>{let v=await W(e.paths,e.name);if(!v)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=v.children.find(({name:g})=>g===t.child)?.task;if(!h||h.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);try{nC(h,`comet/supervisor/${v.parent}/${t.child}`)}catch(g){throw await ne(e.paths,oo(v,{child:t.child,runId:t.runId,reason:g.message})),g}let p=fh(v,{child:t.child,runId:t.runId});await ne(e.paths,p.state);let w=await _(e.paths,e.name);return{state:w,supervisorState:p.state,supervisorTask:p.task,checks:[],requestChecks:null,verifierDispatch:null,continuation:Q(w)}});if(n&&t.kind==="supervisor-cancel")return x(e.paths,`cancel Native Supervisor task ${t.child}`,async()=>{let v=await W(e.paths,e.name);if(!v)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=ul(v,{child:t.child,runId:t.runId,reason:t.reason});await ne(e.paths,h);let p=await _(e.paths,e.name);return{state:p,supervisorState:h,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:Q(p)}});if(n&&t.kind==="supervisor-verifier-result")return x(e.paths,`apply Native Supervisor Verifier result ${t.child}`,async()=>{let v=await W(e.paths,e.name);if(!v)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=v.children.find(({name:g})=>g===t.child);if(!h?.task||h.task.role!=="verifier"||!h.candidateCommit)throw new Error(`Native Supervisor Verifier task is not active for ${t.child}`);try{Am(h.task,h.candidateCommit,"verifier",`comet/supervisor/${v.parent}/${t.child}`)}catch(g){throw await ne(e.paths,oo(v,{child:t.child,runId:t.runId,reason:g.message})),g}let p=mh(v,t);await ne(e.paths,p);let w=await _(e.paths,e.name);return{state:w,supervisorState:p,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:Q(w)}});if(n&&t.kind==="supervisor-integrate"){let v=await vh({paths:e.paths,state:n,name:t.child,checks:t.checks}),h=await Eo({paths:e.paths,name:e.name,trigger:"v2-integrate"}),p=h.state;return{state:p,supervisorState:v,supervisorTask:null,checks:t.checks,requestChecks:null,verifierDispatch:null,parentAdvance:h.parentAdvance,continuation:Q(p)}}if(n&&(t.kind==="builder-handoff"||t.kind==="dispatch-verifier"||t.kind==="verifier-response"||t.kind==="verifier-execution-error"||t.kind==="verifier-unavailable"||t.kind==="supervisor-builder-result"||t.kind==="supervisor-builder-failure"||t.kind==="supervisor-reconnect"||t.kind==="supervisor-cancel"||t.kind==="supervisor-verifier-result")&&!a&&!(t.kind==="builder-handoff"&&o))throw new Error("Native Supervisor accepts only Supervisor task result inputs until every Child is integrated");if(t.kind==="builder-handoff"){let h=bl().captureExecutionIdentity({identityProvider:Z,executionRef:Rm("builder")}),p=await tm({paths:e.paths,name:e.name,input:{identity:h,summary:t.summary,addressedAcceptanceIds:t.addressed_acceptance_ids,checks:t.checks,knownLimits:t.known_limits,review:{status:t.review.status,summary:t.review.summary,reviewerExecutionRef:t.review.reviewer_execution_ref}}});return{state:p,checks:[],requestChecks:null,verifierDispatch:null,continuation:Q(p)}}if(t.kind==="dispatch-verifier"){if(a&&t.checks.length===0)throw new Error("Native Supervisor parent verification requires at least one check");let v=await _(e.paths,e.name);if(v.builder_handoff!==null&&v.builder_handoff.identity_provider!==Z){let y=await xo({paths:e.paths,name:e.name,reason:"The previous Builder identity provider is unavailable to the generic Skill bridge; submit a new Builder candidate before dispatching a Verifier."});return{state:y,checks:[],requestChecks:null,verifierDispatch:null,continuation:Q(y)}}dn(v);let p=(v.loop.next_action==="run-final-full-verification"&&v.verification?.verdict==="pass"&&v.verification.checks.every(({status:y})=>y==="passed")?v.verification.checks:null)??(await am({paths:e.paths,name:e.name,plans:t.checks,...a&&n?{projectRoot:n.integration.worktree}:{}})).checks,w=Rm("verifier"),g=await om({paths:e.paths,name:e.name,checks:p,verifierExecutionId:w,...a&&n?{projectRoot:n.integration.worktree}:{}});return{state:g,checks:p,requestChecks:null,verifierDispatch:_m({paths:e.paths,state:g,checks:p,verifierExecutionRef:w,supervisor:a?n:null}),continuation:Q(g)}}if(t.kind==="verifier-execution-error"){let v=await _(e.paths,e.name);dn(v),await Ml({paths:e.paths,state:v});let h=await cm({paths:e.paths,name:e.name,summary:t.summary,expected:t,requireSkillCoordination:!0});return{state:h,checks:[],requestChecks:null,verifierDispatch:null,continuation:Q(h)}}if(t.kind==="verifier-unavailable"){let v=await lm({paths:e.paths,name:e.name,summary:t.summary,expected:t,requireSkillCoordination:!0});return{state:v,checks:v.verification?.checks??[],requestChecks:null,verifierDispatch:null,continuation:Q(v)}}if(t.kind!=="verifier-response")throw new Error("Native Runner input kind is invalid for the portable verifier bridge");let s=await _(e.paths,e.name),c=dn(s),l=await Ml({paths:e.paths,state:s}),f=bl(),u=f.captureExecutionIdentity({identityProvider:Z,executionRef:l}),d=null;if(a&&typeof t.response=="object"&&t.response!==null&&"kind"in t.response&&t.response.kind==="final-result"){let v=await W(e.paths,e.name);if(!v)throw new Error("Native Supervisor state disappeared before final verification");d=Yi(v)}let m=await sm({paths:e.paths,name:e.name,envelope:f.envelopeVerifierResponse({candidateId:c.candidate_id,identity:u,payload:t.response}),checks:[],maxVerifyFailures:e.maxVerifyFailures,...a&&n?{projectRoot:n.integration.worktree}:{}});if(a&&m.response.kind==="final-result"){if(m.state.verification_result==="pass"&&(m.checks.length===0||m.checks.some(({status:p})=>p!=="passed")))throw new Error("Native Supervisor parent verification cannot pass without completed integration checks");let v=d??await W(e.paths,e.name);if(!v)throw new Error("Native Supervisor state disappeared during verification");let h=Xi(v,m.state);return await ne(e.paths,h),{...m,supervisorState:h,verifierDispatch:null,continuation:Q(m.state)}}return{...m,verifierDispatch:m.requestChecks===null?null:_m({paths:e.paths,state:m.state,checks:m.checks,verifierExecutionRef:await Ml({paths:e.paths,state:m.state}),supervisor:a?n:null}),continuation:Q(m.state)}}import hn from"path";import{realpathSync as ZC}from"fs";var wt={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function $m(e){return e?e.command?`${wt.next} ${e.command}`:e.ask_user?`${wt.next} ${e.ask_user}`:null:null}function Om(e,t){let r=[e.summary],i=$m(e.next);return i&&r.push(i),e.user_message&&r.push("",wt.relay,e.user_message),t!==void 0&&r.push("",wt.details,JSON.stringify(t,null,2)),`${r.join(`
242
+ `}function Rx(e){let t=/^---\r?\ngenerated_from_state_version: ([1-9]\d*)\r?\n---(?:\r?\n|$)/u.exec(e);if(!t)return null;let r=Number(t[1]);return Number.isSafeInteger(r)?r:null}async function Yh(e){let t;try{t=await Sx.readFile(e.file,"utf8")}catch(i){if(i.code==="ENOENT")return"missing";throw i}let r=Rx(t);return r===null?"invalid":r===e.stateVersion?"aligned":"stale"}async function qr(e){await Re(e.file,Px(e.state,e.supervisor))}var Qh=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Ax="comet-state.yaml",_x="state.json",bO=Fa("en");function zt(e){let t=e.expected;if(t){if(e.state.state_version!==t.stateVersion)throw new Error(`Native continuation is stale for state version ${t.stateVersion}; current state version is ${e.state.state_version}`);if(t.action!==e.action)throw new Error(`Native continuation expected ${t.action} cannot be used for ${e.action}`)}}function ce(e,t){if(!Qh.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=oe.join(e.changesDir,t);if(!ue(e.changesDir,r))throw new Error("Native change path escaped");return r}function Je(e,t){return oe.join(ce(e,t),Ax)}function D(e,t){return oe.join(Ve(e,t),_x)}async function sn(e,t){try{let r=await lr.readFile(Je(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function Ee(e){return z(e).currentBranch}async function _(e,t){return Me(Je(e,t))}async function me(e){let t=await Li({file:Je(e.paths,e.previous.name),expectedStateVersion:e.previous.state_version,next:e.next,containedRoot:e.paths.nativeRoot});if(t.verification===null&&t.verification_report===null){let r=oe.join(ce(e.paths,t.name),"verification.md");await J(e.paths.nativeRoot,r),await lr.rm(r,{force:!0})}return t}async function Tl(e){let t=ce(e.paths,e.state.name),r=oe.join(t,"specs"),i=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await lr.readdir(r,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,c)=>s.name.localeCompare(c.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!Qh.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(i.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,c=oe.join(t,...s.split("/")),l=await lr.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let f=oe.join(e.paths.specsDir,o.name,"spec.md"),u="create";try{let d=await lr.lstat(f);if(!d.isFile()||d.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);u="modify"}catch(d){if(d.code!=="ENOENT")throw d}a.push({capability:o.name,operation:u,source:s})}return a.push(...i.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function jl(e){let t=ce(e.paths,e.state.name),r=await Y({root:t,ref:"brief.md",maxBytes:null,includeHash:!1});if(Ah(r.text))throw new Error("Brief has a blocking open question");let i=[],n=[];for(let a of e.specChanges){if(a.source===null){n.push({...a,contentHash:null});continue}let o=await Y({root:t,ref:a.source,maxBytes:null,includeHash:!1});i.push({capability:a.capability,source:o.ref,markdown:o.text}),n.push({...a,contentHash:X("comet.native.shape-artifact-content.v1",o.text)})}return{acceptance:Ya({briefMarkdown:r.text,specs:i}),formalHash:X("comet.native.shape-formal-artifacts.v1",{brief:{source:r.ref,contentHash:X("comet.native.shape-artifact-content.v1",r.text)},specs:n})}}function $l(e){return X("comet.native.shape-confirmation.v1",{formalHash:e.formalHash,childrenHash:e.childrenHash,coordinationMode:e.coordinationMode??null})}async function Zh(e){return x(e.paths,`prepare portable shape confirmation ${e.name}`,async()=>{let t=await _(e.paths,e.name);if(zt({state:t,expected:e.expectedContinuation,action:"prepare-shape-confirmation"}),t.phase!=="shape"||t.status!=="active"||t.loop.stage!=="shape")throw new Error("Native Shape confirmation can only be prepared from active Shape");let r=await Tl({paths:e.paths,state:t}),i=await jl({paths:e.paths,state:t,specChanges:r}),{acceptance:n}=i,a=await Mt({changeDir:ce(e.paths,t.name),acceptanceIds:n.map(({id:u})=>u),validation:Mr({...t,acceptance:n})});if(a&&t.workspace.change_branch===null)throw new Error("Native parent changes require a Git integration branch");let o=await lo(ce(e.paths,t.name))||a?.contract.schema==="comet.native.children.v2"&&a.contract.children.length>=2;if(o&&!a)throw new Error("Native Supervisor Shape requires children.yaml before confirmation");let s=o?e.coordinationMode??t.coordination_mode:void 0;if(o&&s===void 0)throw new Error("Native Supervisor Shape requires --coordination-mode multi-session or single-session");if(!o&&e.coordinationMode!==void 0)throw new Error("--coordination-mode is only valid for a multi-child Native Supervisor Shape");let c={...t,spec_changes:r,shape_confirmation_hash:$l({formalHash:i.formalHash,childrenHash:a?.hash??null,coordinationMode:s})};delete c.children_contract_hash,delete c.coordination_mode,o&&(c.coordination_mode=s);let l=Bh({state:c,acceptance:n.map(u=>({...u}))});a&&(l.children_contract_hash=Zi({acceptance:l.acceptance,children:a.contract}));let f=await me({paths:e.paths,previous:t,next:l});return await V(D(e.paths,t.name),ae({portableState:f,projectRoot:e.paths.projectRoot,branch:Ee(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),f})}async function em(e){return x(e.paths,`confirm portable shape ${e.name}`,async()=>{let t=await _(e.paths,e.name);if(zt({state:t,expected:e.expectedContinuation,action:"confirm-shape"}),t.phase!=="shape"||t.status!=="await-user"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-shape")throw new Error("Native Shape can only be confirmed from the persisted user confirmation boundary");if(e.coordinationMode!==void 0)throw new Error("--coordination-mode must be selected before final Shape confirmation");await gt({paths:e.paths,state:t});let r=await Tl({paths:e.paths,state:t}),i=await jl({paths:e.paths,state:t,specChanges:r}),{acceptance:n}=i,a=await Mt({changeDir:ce(e.paths,t.name),acceptanceIds:n.map(({id:h})=>h),validation:Mr({...t,acceptance:n})});if(a&&t.workspace.change_branch===null)throw new Error("Native parent changes require a Git integration branch");let o=await lo(ce(e.paths,t.name))||a?.contract.schema==="comet.native.children.v2"&&a.contract.children.length>=2,s=t.coordination_mode;if(o&&!a)throw new Error("Native Supervisor Shape requires children.yaml before confirmation");if(o&&s===void 0)throw new Error("Native Supervisor Shape requires --coordination-mode multi-session or single-session");let c=$l({formalHash:i.formalHash,childrenHash:a?.hash??null,coordinationMode:s});if(t.shape_confirmation_hash===void 0||c!==t.shape_confirmation_hash){let h=t.shape_confirmation_hash===void 0?"Native Shape confirmation fingerprint is missing":"Native Shape artifacts changed";throw await Dl({paths:e.paths,state:t,reason:h}),new Error(`${h}; Native change returned to Shape and requires confirmation`)}let l=Dh({state:{...t,spec_changes:r},acceptance:n.map(h=>({...h}))});if(delete l.children_contract_hash,delete l.coordination_mode,a){l.children_contract_hash=Zi({acceptance:l.acceptance,children:a.contract}),o&&(l.coordination_mode=s);let h=[...t.history].reverse().find(({outcome:p})=>p==="pass"||p==="fail");if(h?.outcome==="fail"&&h.unresolved_ids.length>0){let p=await nt({paths:e.paths,state:l}),w=new Map((p?.children??[]).map(({name:b,status:N})=>[b,N])),g=new Set(a.contract.children.filter(({name:b})=>{let N=w.get(b);return N!=="done"&&N!=="integrated"&&N!=="archived"}).flatMap(({covers:b})=>b)),y=h.unresolved_ids.filter(b=>!g.has(b));if(y.length>0)throw new Error(`Native parent repair plan requires an unfinished child covering: ${y.join(", ")}`)}}let f=null,u=a?.contract.schema==="comet.native.children.v2"?await W(e.paths,t.name):null,d=null,m=null;if(a?.contract.schema==="comet.native.children.v2"){if(d=t.workspace.target_branch??t.workspace.change_branch,!d)throw new Error("Native Supervisor v2 requires a target branch");if(m=Er(e.paths.projectRoot,d),!m)throw new Error(`Native Supervisor target branch has no commit: ${d}`);u||(u=await ao({paths:e.paths,parent:t.name,targetBranch:d,contract:a.contract})),u||(f=await lh({projectRoot:e.paths.projectRoot,parent:t.name,targetBranch:d,sourceConfig:await Ne(e.paths.projectRoot)}))}let v=await me({paths:e.paths,previous:t,next:l});if(await V(D(e.paths,t.name),ae({portableState:v,projectRoot:e.paths.projectRoot,branch:Ee(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),a?.contract.schema==="comet.native.children.v2"&&d&&m){let h=u?dh({state:u,contract:a.contract}):f?sl({parent:v.name,targetBranch:d,targetCommit:m,integrationBranch:f.binding.changeBranch,integrationWorktree:f.projectRoot,contract:a.contract}):null;if(!h)throw new Error("Native Supervisor integration state is unavailable");await ne(e.paths,h)}return v})}async function So(e){let t=await Tl(e),r=e.ignoreSpecOperationFor??(e.state.children_contract_hash?new Set(e.state.spec_changes.map(({capability:l})=>l)):void 0);if(!(t.length===e.state.spec_changes.length&&t.every((l,f)=>{let u=e.state.spec_changes[f];return u!==void 0&&l.capability===u.capability&&l.source===u.source&&(l.operation===u.operation||r?.has(l.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n;try{n=await jl({...e,specChanges:t})}catch{return{drifted:!0,reason:"Native Shape artifacts changed or became invalid"}}let{acceptance:a}=n,o=e.state.acceptance.map(({source:l,text:f})=>({source:l,text:f}));if(!qp(o,a))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let s;try{s=await Mt({changeDir:ce(e.paths,e.state.name),acceptanceIds:a.map(({id:l})=>l),validation:Mr({...e.state,acceptance:a})})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return e.state.phase==="shape"&&e.state.status==="await-user"&&e.state.loop.next_action==="confirm-shape"&&e.state.shape_confirmation_hash===void 0?{drifted:!0,reason:"Native Shape confirmation fingerprint is missing"}:e.state.shape_confirmation_hash!==void 0&&$l({formalHash:n.formalHash,childrenHash:s?.hash??null,coordinationMode:e.state.coordination_mode})!==e.state.shape_confirmation_hash?{drifted:!0,reason:"Native Shape artifacts changed"}:(s?Zi({acceptance:a,children:s.contract}):null)===(e.state.children_contract_hash??null)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native child declarations changed"}}async function gt(e){let t=await So(e);if(!t.drifted)return;let r=t.reason??"Native confirmed requirements changed";throw await Dl({paths:e.paths,state:e.state,reason:r}),new Error(`${r}; Native change returned to Shape and requires confirmation`)}async function tm(e){return x(e.paths,`submit portable candidate ${e.name}`,async()=>{let t=await _(e.paths,e.name);if(await gt({paths:e.paths,state:t}),await Mt({changeDir:ce(e.paths,t.name),acceptanceIds:t.acceptance.map(({id:a})=>a),validation:Mr(t)})||t.children_contract_hash){let a=await nt({paths:e.paths,state:t});if(!a?.confirmed||!a.allDone)throw new Error("Native parent Build advances child changes before parent review");if(t.loop.stage==="repairing"&&t.verification_result==="fail")throw new Error("Native parent verification failed; complete the repair child first")}let i=Lh({state:t,input:e.input}),n=await me({paths:e.paths,previous:t,next:i});return await V(D(e.paths,t.name),ae({portableState:n,projectRoot:e.paths.projectRoot,branch:Ee(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function Eo(e){let t=await _(e.paths,e.name),r={trigger:e.trigger,parent:e.name,advanced:!1,message:null,blocker:null};if(t.phase!=="build"||t.status!=="active")return{state:t,parentAdvance:r};let i=await nt({paths:e.paths,state:t});if(!i||!i.confirmed||!i.allDone)return{state:t,parentAdvance:{...r,blocker:i&&!i.confirmed?"Supervisor child declarations require Shape confirmation":null}};if(t.loop.stage==="repairing"&&t.verification_result==="fail")return{state:t,parentAdvance:{...r,blocker:"Native parent verification failed; add and confirm a repair child"}};let n=t.language==="zh-CN"?"全部 Child 已完成;Supervisor 父级候选需要独立代码审查后再进入验证":"All Children are complete; the Supervisor parent candidate needs an independent code review before verification.";return{state:t,parentAdvance:{...r,message:n}}}function Ol(e,t,r){return{id:e.id,name:e.name,operationId:t,status:"planned",repeatable:e.repeatable,timeoutMs:e.timeoutMs,executionCount:0,argv:[e.executable,...e.argv],cwd:fo(r,e.cwdRef),exitCode:null,startedAt:null,completedAt:null,log:`logs/checks/${t}-${e.id}.log`}}function rm(e,t,r,i){if(!e.repeatable)throw new Error(`Native check ${e.id} was interrupted and is not repeatable; user resolution is required`);return{...Ol(t,r,i),executionCount:e.executionCount}}function im(e,t){let r=oe.relative(oe.resolve(e),oe.resolve(t));if(oe.isAbsolute(r)||r===".."||r.startsWith(`..${oe.sep}`))throw new Error("Native local check cwd escaped the project root");let i=r.length===0?".":r.split(oe.sep).join("/");return fo(e,i),i}function _l(e,t){let[r,...i]=e.argv;if(!r)throw new Error(`Native local check ${e.id} has no executable`);return en({id:e.id,name:e.id,executable:r,argv:i,cwdRef:im(t,e.cwd),timeoutMs:e.timeoutMs,repeatable:e.repeatable})}function Ix(e){return e.startedAt===null||e.completedAt===null?0:Math.max(0,Date.parse(e.completedAt)-Date.parse(e.startedAt))}function Wr(e){let t=new Map;for(let r of e.supplied){if(t.has(r.id))throw new Error(`Native Runtime check summaries contain duplicate ID ${r.id}`);t.set(r.id,r)}return e.local.checks.map(r=>{if(r.status==="planned"||r.status==="running")throw new Error(`Native Runtime check ${r.id} has not completed`);let i=e.requestedNames?.get(r.id)??r.name;return{id:r.id,name:H(i),argv_display:wl(r.argv.slice(1)).map(n=>H(n)),argv_truncated:!1,cwd_ref:im(e.projectRoot,r.cwd),status:r.status,exit_code:r.exitCode,duration_ms:Ix(r)}})}function Tx(e){return{id:e.id,name:e.name,executable:e.executable,argv:[...e.argv],cwdRef:e.cwdRef,timeoutMs:e.timeoutMs,repeatable:e.repeatable}}function cn(e){if(e.local===null||e.local.change!==e.state.name)return ae({portableState:e.state,projectRoot:e.projectRoot,branch:Ee(e.projectRoot)});let t=e.local.execution?.operationId??Il();return{...e.local,basedOnStateVersion:e.state.state_version,execution:{operationId:t,stage:"checking",actor:"runtime",executionId:null,status:"completed",startedAt:e.local.execution?.startedAt??new Date().toISOString(),requestCheckRounds:0},checks:e.local.checks.map(r=>r.status==="running"||r.status==="planned"?{...r,operationId:t,status:"interrupted"}:{...r,operationId:t})}}async function zr(e){try{let t=await ot(D(e.paths,e.state.name));return t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version?null:t}catch{return null}}function nm(e){let{state:t,local:r,expected:i}=e;if(t.state_version!==i.stateVersion||t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.loop.iteration!==i.iteration||t.loop.attempt!==i.attempt||t.builder_handoff===null||r===null||r.basedOnStateVersion!==t.state_version||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running"||r.execution.executionId!==i.verifierExecutionRef)throw new Error("Native Verifier execution message is stale for the current attempt");return r}function jx(e){let{state:t,local:r,envelope:i}=e;if(!ho(i))throw new Error("Native Verifier result must come from the trusted Runner channel");if(t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.builder_handoff===null)throw new Error("Native Verifier result is stale for the current workflow state");if(i.candidateId!==t.builder_handoff.candidate_id||i.identityProvider!==t.builder_handoff.identity_provider||i.verifierExecutionRef===t.builder_handoff.builder_execution_ref)throw new Error("Native Verifier result is stale for the current candidate or identity");if(r===null||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running"||r.execution.executionId!==null&&r.execution.executionId!==i.verifierExecutionRef)throw new Error("Native Verifier result is stale for the active execution");return i}function $x(e){return e.kind==="final-result"?{iteration:e.result.iteration,attempt:e.result.attempt}:{iteration:e.iteration,attempt:e.attempt}}async function ko(e){let t=await zr({paths:e.paths,state:e.state}),r=Jh({state:e.state,summary:e.summary}),i=await me({paths:e.paths,previous:e.state,next:r});return await V(D(e.paths,e.state.name),cn({local:t,state:i,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),i}function Xh(e,t,r){return e.checks.length!==t.length?!1:e.checks.every((i,n)=>_l(i,r)===en(t[n]))}async function Ox(e){return x(e.paths,`reserve portable checks ${e.name}`,async()=>{let t=await _(e.paths,e.name);if(await gt({paths:e.paths,state:t}),t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native checks require Verify ready state");let r=D(e.paths,t.name),i=(await Al({file:r,portableState:t,projectRoot:e.projectRoot,branch:Ee(e.projectRoot),containedRoot:e.paths.runtimeDir})).state;if(i.execution?.stage==="checking"&&i.execution.actor==="runtime"&&Xh(i,e.plans,e.projectRoot)){let o=i.execution;if(o.status==="running")throw new Error("Native check plan is already in progress");let s=i.checks.filter(c=>c.status==="interrupted");if(s.length===0&&o.status==="completed"){let c=new Map(e.plans.map(({id:l,name:f})=>[l,f]));return{kind:"reuse",state:t,checks:Wr({local:i,projectRoot:e.projectRoot,supplied:[],requestedNames:c})}}if(s.length>0&&s.some(c=>!c.repeatable)){let c=an({state:t,reason:`A non-repeatable Runtime check was interrupted (${s.filter(f=>!f.repeatable).map(({id:f})=>f).join(", ")}); a new Builder candidate is required before it can run again.`}),l=await me({paths:e.paths,previous:t,next:c});throw await V(D(e.paths,t.name),ae({portableState:l,projectRoot:e.paths.projectRoot,branch:Ee(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),new Error(`Native check ${s.find(f=>!f.repeatable).id} was interrupted and is not repeatable; the change returned to Build for a new candidate`)}}if(i.execution!==null&&i.checks.length>0){if(!(i.execution.stage==="checking"&&i.execution.actor==="runtime"&&i.checks.some(s=>s.status==="interrupted")&&Xh(i,e.plans,e.projectRoot)))throw new Error("Native check plan was already resolved with a different plan")}else if(i.execution!==null||i.checks.length>0)throw new Error("Native check plan was already resolved with a different plan");let n=Il(),a={...i,execution:{operationId:n,stage:"checking",actor:"runtime",executionId:null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:e.plans.map(o=>{let s=i.checks.find(c=>c.id===o.id);return s?.status==="interrupted"?rm(s,o,n,e.projectRoot):s?{...s,operationId:n}:Ol(o,n,e.projectRoot)})};return await V(r,a,{containedRoot:e.paths.runtimeDir}),{kind:"execute",state:t,local:a,plans:e.plans.filter(o=>{let s=i.checks.find(c=>c.id===o.id);return s===void 0||s.status==="interrupted"})}})}async function No(e){return x(e.paths,`update portable checks ${e.state.name}`,async()=>{let t=await _(e.paths,e.state.name);if(t.state_version!==e.state.state_version||t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native check plan state changed during execution");let r=D(e.paths,t.name),i=await ot(r);if(i===null||i.basedOnStateVersion!==t.state_version||i.execution?.operationId!==e.operationId||i.execution.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="running")throw new Error("Native check plan reservation changed during execution");let n=e.update(i);return await V(r,n,{containedRoot:e.paths.runtimeDir}),n})}async function am(e){let t=e.projectRoot??e.paths.projectRoot;if(new Set(e.plans.map(({id:c})=>c)).size!==e.plans.length)throw new Error("Native check plan contains duplicate IDs");let r=[],i=new Set;for(let c of e.plans){po(t,c);let l=en(c);i.has(l)||(i.add(l),r.push(c))}let n=await Ox({...e,plans:r,projectRoot:t});if(n.kind==="reuse")return n;let a=n.local.execution.operationId,o=Ve(e.paths,n.state.name);try{for(let c of n.plans){let l=new Date().toISOString();await No({paths:e.paths,state:n.state,operationId:a,update:u=>({...u,checks:u.checks.map(d=>d.id===c.id?{...d,status:"running",executionCount:d.executionCount+1,startedAt:l}:d)})});let f=await yl({projectRoot:t,runtimeDir:o,operationId:a,plan:c});await No({paths:e.paths,state:n.state,operationId:a,update:u=>({...u,checks:u.checks.map(d=>d.id===c.id?{...d,status:f.status,exitCode:f.exitCode,startedAt:f.startedAt,completedAt:f.completedAt,log:f.logRef}:d)})})}await No({paths:e.paths,state:n.state,operationId:a,update:c=>({...c,execution:{...c.execution,status:"completed"}})})}catch(c){try{await No({paths:e.paths,state:n.state,operationId:a,update:l=>({...l,execution:{...l.execution,status:"interrupted"},checks:l.checks.map(f=>f.status==="planned"||f.status==="running"?{...f,status:"interrupted"}:f)})})}catch{}throw c}let s=await ot(D(e.paths,n.state.name));if(s===null)throw new Error("Native Runtime check state disappeared after execution");return{state:n.state,checks:Wr({local:s,projectRoot:t,supplied:[]})}}async function Hx(e){let t=D(e.paths,e.state.name),r=e.local;if(r===null||r.change!==e.state.name||r.basedOnStateVersion!==e.state.state_version||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running")throw new Error("Native Verifier request-checks has no active local execution");if(r.execution.executionId!==null&&r.execution.executionId!==e.envelope.verifierExecutionRef)throw new Error("Native Verifier request-checks changed execution within the same attempt");if(r.execution.requestCheckRounds>=Sl)throw new Error(`Native Verifier request-checks exceeded ${Sl} rounds for this attempt`);let i=new Map,n=new Map,a=new Map;for(let m of r.checks){let v=_l(m,e.projectRoot);n.set(v,m),m.status!=="interrupted"&&i.set(v,m),a.set(m.id,v)}let o=new Map,s=new Map;for(let m of e.response.checks){let v=Tx(m);po(e.projectRoot,v);let h=en(v),p=s.get(v.id);if(p!==void 0&&p!==h)throw new Error(`Native Verifier check ID ${v.id} refers to conflicting commands`);let w=a.get(v.id);if(w!==void 0&&w!==h)throw new Error(`Native Verifier check ID ${v.id} conflicts with a Runtime check`);s.set(v.id,h);let g=n.get(h);if(g?.status==="interrupted"&&!g.repeatable)throw new Error(`Native check ${g.id} was interrupted and is not repeatable; user resolution is required`);o.has(h)||o.set(h,v)}let c=[...o.entries()],l=c.filter(([m])=>!i.has(m));if(r.execution.requestCheckRounds>0&&l.length===0)throw new Error("Native Verifier repeatedly requested only equivalent checks");let f=r.execution.requestCheckRounds+1,u=new Map(c.map(([,m])=>[m.id,m.name])),d={...r,execution:{...r.execution,stage:"checking",actor:"runtime",executionId:e.envelope.verifierExecutionRef,requestCheckRounds:f},checks:[...r.checks.map(m=>{let v=_l(m,e.projectRoot),h=o.get(v);return h&&m.status==="interrupted"?rm(m,h,r.execution.operationId,e.projectRoot):m}),...l.filter(([m])=>!n.has(m)).map(([,m])=>Ol(m,r.execution.operationId,e.projectRoot))]};return await V(t,d,{containedRoot:e.paths.runtimeDir}),{state:e.state,local:d,verifierExecutionRef:e.envelope.verifierExecutionRef,round:f,novelPlans:l.map(([,m])=>m),requestedNames:u,reusedCheckIds:c.filter(([m])=>i.has(m)).map(([,m])=>m.id),suppliedChecks:e.suppliedChecks}}async function bo(e){return x(e.paths,`update Verifier-requested checks ${e.reservation.state.name}`,async()=>{let t=await _(e.paths,e.reservation.state.name);if(t.state_version!==e.reservation.state.state_version||t.phase!=="verify"||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier request-checks state changed during execution");let r=D(e.paths,t.name),i=await ot(r),n=i?.execution;if(i===null||i.basedOnStateVersion!==t.state_version||n===null||n===void 0||n.operationId!==e.reservation.local.execution?.operationId||n.stage!=="checking"||n.actor!=="runtime"||n.status!=="running"||n.executionId!==e.reservation.verifierExecutionRef||n.requestCheckRounds!==e.reservation.round)throw new Error("Native Verifier request-checks reservation changed during execution");let a=e.update(i);return await V(r,a,{containedRoot:e.paths.runtimeDir}),a})}async function Dx(e){let t;try{for(let r of e.reservation.novelPlans){let i=new Date().toISOString();t=await bo({paths:e.paths,reservation:e.reservation,update:a=>({...a,checks:a.checks.map(o=>o.id===r.id?{...o,status:"running",executionCount:o.executionCount+1,startedAt:i}:o)})});let n=await yl({projectRoot:e.projectRoot,runtimeDir:Ve(e.paths,e.reservation.state.name),operationId:e.reservation.local.execution.operationId,plan:r});t=await bo({paths:e.paths,reservation:e.reservation,update:a=>({...a,checks:a.checks.map(o=>o.id===r.id?{...o,status:n.status,exitCode:n.exitCode,startedAt:n.startedAt,completedAt:n.completedAt,log:n.logRef}:o)})})}t=await bo({paths:e.paths,reservation:e.reservation,update:r=>({...r,execution:{...r.execution,stage:"verifying",actor:"verifier",executionId:e.reservation.verifierExecutionRef}})})}catch(r){try{await bo({paths:e.paths,reservation:e.reservation,update:i=>({...i,execution:{...i.execution,status:"interrupted"},checks:i.checks.map(n=>n.status==="planned"||n.status==="running"?{...n,status:"interrupted"}:n)})})}catch{}throw r}return{checks:Wr({local:t,projectRoot:e.projectRoot,supplied:e.reservation.suppliedChecks,requestedNames:e.reservation.requestedNames}),requestChecks:{round:e.reservation.round,reusedCheckIds:e.reservation.reusedCheckIds,executedCheckIds:e.reservation.novelPlans.map(({id:r})=>r)}}}async function om(e){return x(e.paths,`dispatch portable verifier ${e.name}`,async()=>{let t=await _(e.paths,e.name),r=e.projectRoot??e.paths.projectRoot;await gt({paths:e.paths,state:t});let i=(await Al({file:D(e.paths,t.name),portableState:t,projectRoot:r,branch:Ee(r),containedRoot:e.paths.runtimeDir})).state;if(i.execution?.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="completed")throw new Error("Native check plan must be explicitly resolved before Verifier dispatch");Wr({local:i,projectRoot:r,supplied:e.checks});let n=Vh(t),a=await me({paths:e.paths,previous:t,next:n}),o=D(e.paths,t.name),s=Il();return await V(o,{...i,basedOnStateVersion:a.state_version,execution:{operationId:s,stage:"verifying",actor:"verifier",executionId:e.verifierExecutionId??null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:i.checks.map(c=>({...c,operationId:s}))},{containedRoot:e.paths.runtimeDir}),a})}async function sm(e){if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let t=await x(e.paths,`apply portable verifier ${e.name}`,async()=>{let r=await _(e.paths,e.name),i=e.projectRoot??e.paths.projectRoot;await gt({paths:e.paths,state:r});let n=await zr({paths:e.paths,state:r}),a=jx({state:r,local:n,envelope:e.envelope}),o;try{o=kl(a.payload)}catch(u){let d=`Native Verifier response was invalid: ${u.message}`,m=await ko({paths:e.paths,state:r,summary:d});throw new Error(`${d}; execution error ${m.loop.execution_failure_count}/${nn} was recorded`,{cause:u})}let s=$x(o);if(s.iteration!==r.loop.iteration||s.attempt!==r.loop.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");let c=[],l;try{n!==null&&(c=Wr({local:n,projectRoot:i,supplied:e.checks}));let u=Mh({state:r,envelope:a,checks:c,maxVerifyFailures:e.maxVerifyFailures});if(u.response.kind==="request-checks"){if(n===null)throw new Error("Native Verifier request-checks has no active local execution");let d=await Hx({paths:e.paths,projectRoot:i,state:r,local:n,envelope:a,response:u.response,suppliedChecks:c});return{kind:"request-checks",state:r,response:u.response,reservation:d}}if(n===null||n.execution===null||n.execution.stage!=="verifying"||n.execution.actor!=="verifier"||n.execution.status!=="running")throw new Error("Native Verifier final result has no active local execution");if(n.execution.executionId!==null&&n.execution.executionId!==a.verifierExecutionRef)throw new Error("Native Verifier final result changed execution within the same attempt");l=u}catch(u){let d=`Native Verifier response was invalid: ${u.message}`,m=await ko({paths:e.paths,state:r,summary:d});throw new Error(`${d}; execution error ${m.loop.execution_failure_count}/${nn} was recorded`,{cause:u})}let f=await me({paths:e.paths,previous:r,next:l.state});return await V(D(e.paths,r.name),f.loop.next_action==="resolve-verifier-blocker"||f.loop.next_action==="run-final-full-verification"?cn({local:n,state:f,projectRoot:i}):ae({portableState:f,projectRoot:i,branch:Ee(i)}),{containedRoot:e.paths.runtimeDir}),f.verification!==null&&await qr({file:oe.join(ce(e.paths,r.name),"verification.md"),state:f}),{kind:"final-result",result:{state:f,response:l.response,checks:c,requestChecks:null}}});if(t.kind==="final-result")return t.result;try{let r=await Dx({paths:e.paths,projectRoot:e.projectRoot??e.paths.projectRoot,reservation:t.reservation});return{state:t.state,response:t.response,checks:r.checks,requestChecks:r.requestChecks}}catch(r){let i=`Native Verifier response was invalid: ${r.message}`,n=await x(e.paths,`record Verifier-requested check failure ${e.name}`,async()=>{let a=await _(e.paths,e.name);return a.state_version!==t.state.state_version?null:ko({paths:e.paths,state:a,summary:i})});throw new Error(n?`${i}; execution error ${n.loop.execution_failure_count}/${nn} was recorded`:`${i}; the portable state changed before the execution error could be recorded`,{cause:r})}}async function cm(e){return x(e.paths,`record portable verifier failure ${e.name}`,async()=>{let t=await _(e.paths,e.name),r=await zr({paths:e.paths,state:t});if(nm({state:t,local:r,expected:e.expected}),e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");return ko({paths:e.paths,state:t,summary:e.summary})})}async function lm(e){return x(e.paths,`record unavailable portable verifier ${e.name}`,async()=>{let t=await _(e.paths,e.name);await gt({paths:e.paths,state:t});let r=await zr({paths:e.paths,state:t}),i=nm({state:t,local:r,expected:e.expected});if(e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");let n=Wr({local:i,projectRoot:e.paths.projectRoot,supplied:[]}),a=qh({state:t,checks:n,verifierExecutionRef:i.execution.executionId,summary:e.summary}),o=await me({paths:e.paths,previous:t,next:a});return await V(D(e.paths,t.name),cn({local:i,state:o,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),await qr({file:oe.join(ce(e.paths,t.name),"verification.md"),state:o}),o})}async function um(e){return x(e.paths,`confirm portable Skill-coordinated pass ${e.name}`,async()=>{let t=await _(e.paths,e.name);zt({state:t,expected:e.expectedContinuation,action:"accept-result"}),await gt({paths:e.paths,state:t});let r=await W(e.paths,e.name);if(r?.finalVerification.status==="pending"){if(Yi(r).stateVersion!==r.stateVersion)return hm({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; rerun the final full verification."});await ne(e.paths,Xi(r,t))}let i=Fh(t),n=await me({paths:e.paths,previous:t,next:i});return await V(D(e.paths,t.name),ae({portableState:n,projectRoot:e.paths.projectRoot,branch:Ee(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await qr({file:oe.join(ce(e.paths,t.name),"verification.md"),state:n}),n})}async function Bx(e){let t=await _(e.paths,e.name),r=await W(e.paths,e.name),i=await eo(e.paths,{kind:"archive",change:e.name}),n=i?.kind==="archive"?i:null;if(n&&r?.finalVerification.status==="pending"){if(n.journal.status!=="prepared"||n.journal.next_spec_index!==0)throw new Error("Native Supervisor final verification changed after Archive applied side effects; doctor intervention is required");if(t.phase==="verify"&&t.status==="active"&&t.verification===null&&t.verification_result==="pending"&&t.loop.stage==="verify-ready")return await lr.rm(n.file,{force:!0}),{state:t,action:"rerun-final-verification"}}if(t.archived||t.verification===null||t.verification_result!=="pass"||r?.finalVerification.status!=="pending")return{state:t,action:"none"};let a=Yi(r);if(n||a.stateVersion!==r.stateVersion){let o=await hm({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; the final full verification will resume automatically."});return n&&await lr.rm(n.file,{force:!0}),{state:o,action:"rerun-final-verification"}}return await ne(e.paths,Xi(r,t)),{state:t,action:"recorded-final-verification"}}async function Hl(e){return x(e.paths,`recover Supervisor final verification ${e.name}`,()=>Bx(e),{allowedPortableTransaction:{kind:"archive",change:e.name}})}async function dm(e){return x(e.paths,`confirm unavailable portable verifier ${e.name}`,async()=>{let t=await _(e.paths,e.name);zt({state:t,expected:e.expectedContinuation,action:"confirm-verifier-unavailable"}),await gt({paths:e.paths,state:t});let r=Wh({state:t,summary:e.summary}),i=await me({paths:e.paths,previous:t,next:r});return await V(D(e.paths,t.name),ae({portableState:i,projectRoot:e.paths.projectRoot,branch:Ee(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await qr({file:oe.join(ce(e.paths,t.name),"verification.md"),state:i}),i})}async function fm(e){return x(e.paths,`resolve portable verifier blocker ${e.name}`,async()=>{let t=await _(e.paths,e.name);zt({state:t,expected:e.expectedContinuation,action:"resolve-verifier-blocker"}),await gt({paths:e.paths,state:t});let r=await zr({paths:e.paths,state:t}),i=zh(t,{reason:e.reason}),n=await me({paths:e.paths,previous:t,next:i});return await V(D(e.paths,t.name),cn({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function pm(e){return x(e.paths,`retry portable verifier ${e.name}`,async()=>{let t=await _(e.paths,e.name);zt({state:t,expected:e.expectedContinuation,action:"retry-verifier"});let r=await zr({paths:e.paths,state:t}),i=Gh(t),n=await me({paths:e.paths,previous:t,next:i});return await V(D(e.paths,t.name),cn({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function xo(e){return x(e.paths,`return portable change ${e.name} to Build`,async()=>{let t=await _(e.paths,e.name);if(zt({state:t,expected:e.expectedContinuation,action:"revise-implementation"}),t.phase==="build")return t;let r=an({state:t,reason:e.reason}),i=await me({paths:e.paths,previous:t,next:r});return await V(D(e.paths,t.name),ae({portableState:i,projectRoot:e.paths.projectRoot,branch:Ee(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),i})}async function Co(e){return x(e.paths,`return portable change ${e.name} to Shape`,async()=>{let t=await _(e.paths,e.name);if(zt({state:t,expected:e.expectedContinuation,action:"revise-requirements"}),e.allowedPhases&&!e.allowedPhases.includes(t.phase))throw new Error("--revise-requirements is only valid from Verify or Archive");return t.phase==="shape"?t:Dl({paths:e.paths,state:t,reason:e.reason})})}async function Dl(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let i={...pe(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:H(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"prepare-shape-confirmation"}};delete i.shape_confirmation_hash,delete i.children_contract_hash;let n=await me({paths:e.paths,previous:t,next:i});return await V(D(e.paths,t.name),ae({portableState:n,projectRoot:e.paths.projectRoot,branch:Ee(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function hm(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);if(t.verification===null||t.verification_result!=="pass")throw new Error("Native Supervisor recovery requires a persisted final verification pass");let i={...pe(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:H(e.reason),completed_at:new Date().toISOString()}),phase:"verify",status:"active",state_version:t.state_version+1,acceptance:t.acceptance.map(a=>({...a,result:"pending",reason:null})),blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{...t.loop,stage:"verify-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:"run-final-full-verification"}},n=await me({paths:e.paths,previous:t,next:i});return await V(D(e.paths,t.name),ae({portableState:n,projectRoot:e.paths.projectRoot,branch:Ee(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function Po(e){if(e.state.verification===null)return"not-applicable";let t=oe.join(ce(e.paths,e.state.name),"verification.md");return await Yh({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await qr({file:t,state:e.state}),"rebuilt")}var mm=["evidence.md","repair.md","archive.md","checkpoint.md"],Mx="verification.md";async function Fx(e,t){let r=await eo(e,{kind:"migration",change:t});return r?.kind==="migration"?r.journal:null}async function vm(e,t){await ln.mkdir(e.transactionsDir,{recursive:!0}),await ye(Za(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function gm(e,t,r={}){let i=r.removeVerificationReport===!1?mm:[...mm,Mx];await Promise.all([ln.rm(Ve(e,t),{recursive:!0,force:!0}),ln.rm(_c(e,t),{recursive:!0,force:!0}),...i.map(n=>ln.rm(Vx.join(rt(e,t),n),{force:!0}))])}async function wm(e,t){await V(D(e,t.name),ae({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function ym(e,t){try{let r=await Mi(e,t);if(r?.schema==="comet.native.workspace.v3")return{isolation:r.isolation,change_branch:r.changeBranch,target_branch:r.targetBranch,finish:r.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function Nm(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let r=z(e.projectRoot);if(!r.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(r.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${r.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!r.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function qx(e){let t=rt(e.paths,e.state.name),r=await Y({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),i=[];for(let n of e.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await Y({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return Ya({briefMarkdown:r.text,specs:i})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function bm(e,t){let r=await $p(e,t);if(!r.state)throw new Error(`Native legacy change ${t} is unreadable`);return r.state}async function km(e){return x(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await Fx(e.paths,e.name),r=await sn(e.paths,e.name)?await Me(Je(e.paths,e.name)):null;if(!t&&r)return await gm(e.paths,e.name,{removeVerificationReport:!1}),await wm(e.paths,r),r;let i=null,n=null;for(t||(i=await bm(e.paths,e.name),n=await ym(e.paths,e.name),Nm(e.paths,n),t={schema:Xa,id:Lx(),change:i.name,fromSchema:i.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await vm(e.paths,t));;){let a=zp(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?r||(i??=await bm(e.paths,e.name),n??=await ym(e.paths,e.name),Nm(e.paths,n),r=Wp({state:i,acceptance:await qx({paths:e.paths,state:i}),workspace:n,migratedAt:e.now}),await Da(Je(e.paths,e.name),r,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await gm(e.paths,e.name):a.action==="commit-transaction"&&(r??=await Me(Je(e.paths,e.name)),await wm(e.paths,r)),t={...t,status:a.nextStatus},await vm(e.paths,t)}return await ln.rm(Za(e.paths,{kind:"migration",change:e.name}),{force:!0}),r??Me(Je(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as Em}from"node:fs";import xm from"node:path";import{promises as Bl}from"node:fs";import Wx from"node:path";var zx=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),Jx=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),Gx=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task"]),Ux=new Set(["status","summary"]);function Ro(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Ao(e,t,r){let i=new Set(Object.keys(e)),n=[...t].filter(o=>!i.has(o)),a=[...i].filter(o=>!t.has(o));return n.length===0&&a.length===0?null:`${r} fields must be exact (missing: ${n.join(", ")||"none"}; unexpected: ${a.join(", ")||"none"})`}function Kx(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((r,i)=>r===t[i])}function ur(e,t,r){return{status:"incompatible",file:e,snapshot:t,message:r}}function Yx(e,t,r,i){let n=Ro(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=Ao(n,zx,"Native Supervisor overlay");if(a)return a;if(i.stateVersion!==1)return"Native Supervisor overlay stateVersion is not 1";if(i.parent!==t.name)return`Native Supervisor overlay parent ${i.parent} does not match ${t.name}`;let o=Ro(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=Ao(o,Jx,"Native Supervisor integration");if(s)return s;if(i.integration.headCommit!==i.integration.targetCommit)return"Native Supervisor integration headCommit has advanced beyond targetCommit";if(!Array.isArray(n.history)||n.history.length!==0)return"Native Supervisor overlay history is not empty";let c=Ro(n.finalVerification,"Native Supervisor finalVerification");if(!c)return"Native Supervisor finalVerification must be an object";let l=Ao(c,Ux,"Native Supervisor finalVerification");if(l)return l;if(i.finalVerification.status!=="pending"||i.finalVerification.summary!==null)return"Native Supervisor final verification already contains progress";if(!Array.isArray(n.children))return"Native Supervisor children must be an array";if(n.children.length!==r.children.length)return"Native Supervisor child count does not match the legacy children contract";for(let[f,u]of n.children.entries()){let d=Ro(u,`Native Supervisor child ${f}`);if(!d)return`Native Supervisor child ${f} must be an object`;let m=Ao(d,Gx,`Native Supervisor child ${f}`);if(m)return m;let v=r.children[f];if(d.name!==v.name||d.summary!==v.summary||!Kx(d.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(d.status!==h)return`Native Supervisor child ${v.name} has progressed beyond its initial ${h} status`;if(d.baseCommit!==null||d.candidateCommit!==null||d.verifiedCommit!==null||d.integrationCommit!==null||d.verification!==null||d.blocker!==null||d.projectRoot!==null||d.task!==null)return`Native Supervisor child ${v.name} contains execution progress`;if(!Array.isArray(d.checks)||d.checks.length!==0)return`Native Supervisor child ${v.name} contains integration checks`}return null}async function un(e){let t=Lr(e.paths,e.state.name),r;try{let c=await Bl.lstat(t);if(!c.isFile()||c.isSymbolicLink())return ur(t,"","Native Supervisor overlay is not a regular file");r=await Bl.readFile(t,"utf8")}catch(c){return c.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:ur(t,"",`Native Supervisor overlay cannot be read: ${c.message}`)}let i;try{i=JSON.parse(r)}catch(c){return ur(t,r,`Native Supervisor overlay is invalid JSON: ${c.message}`)}let n=Wx.join(e.paths.changesDir,e.state.name),a;try{a=await Mt({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:c})=>c),policy:"advisory"})}catch(c){return ur(t,r,`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:r};let o;try{o=await W(e.paths,e.state.name)}catch(c){return ur(t,r,`Native Supervisor overlay is invalid: ${c.message}`)}if(!o)return ur(t,r,"Native Supervisor overlay disappeared during inspection");let s=Yx(i,e.state,a.contract,o);return s?ur(t,r,s):{status:"repairable-legacy-overlay",file:t,message:"An exact unstarted v2 Supervisor overlay is stale beside a legacy children.v1 contract",snapshot:r}}async function Sm(e){let t=await un({paths:e.paths,state:e.state});if(t.status!=="repairable-legacy-overlay"||t.snapshot!==e.expected.snapshot)throw new Error("Native Supervisor overlay changed before the safe repair could be applied");await Bl.rm(t.file,{force:!1})}function Ll(e,t){let r=z(e.projectRoot);if(t.workspace.change_branch!==null){if(!r.isGitWorktree)return"The portable change requires a Git branch/worktree";if(r.currentBranch!==t.workspace.change_branch)return`Expected Native change branch ${t.workspace.change_branch}, current branch is ${r.currentBranch??"(detached)"}`}return t.workspace.isolation==="current"?null:r.isGitWorktree?t.workspace.isolation==="worktree"&&!r.isSecondaryWorktree?"The portable change requires its linked worktree":null:"The portable change requires a Git branch/worktree"}function Xx(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function Qx(e,t,r){let i=new Date().toISOString(),n=e.verification===null?e:pe(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:H(t),completed_at:i});return C({...n,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:r?Xx(e):e.acceptance,verification:null,verification_result:"pending",verification_report:null,blockers:[],loop:{...e.loop,stage:"verify-ready",next_action:"run-required-checks-and-dispatch-verifier"}})}async function Zx(e){try{let t=await ot(e);return t===null?{local:null,reason:"missing"}:{local:t,reason:"available"}}catch(t){if(t.code&&t.code!=="ENOENT")throw t;return{local:null,reason:"invalid"}}}async function Vl(e){return x(e.paths,`recover portable change ${e.name}`,async()=>{let t=await _(e.paths,e.name);if(t.status==="done")return await Po({paths:e.paths,state:t}),{state:t,local:null,action:"done",reason:"done",message:"Archived Native changes do not require a local execution overlay."};let r=Ll(e.paths,t);if(r)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:r};let i=await un({paths:e.paths,state:t});if(i.status==="incompatible")return{state:t,local:null,action:"await-user",reason:"overlay-incompatible",message:i.message};let n=!1;i.status==="repairable-legacy-overlay"&&(await Sm({paths:e.paths,state:t,expected:i}),n=!0);let a=D(e.paths,e.name),o=await Zx(a),s=o.reason==="available"&&(o.local?.change!==t.name||o.local?.basedOnStateVersion!==t.state_version)?"stale":o.reason;if(s==="available"&&!e.preserveRunningExecution&&o.local?.execution!==null&&o.local?.execution?.status!=="completed"&&o.local&&(s="interrupted",o.local.execution?.status==="running"&&(o.local={...o.local,execution:{...o.local.execution,status:"interrupted"},checks:o.local.checks.map(v=>v.status==="planned"||v.status==="running"?{...v,status:"interrupted"}:v)},await V(a,o.local,{containedRoot:e.paths.runtimeDir}))),s==="available")return await Po({paths:e.paths,state:t}),{state:t,local:o.local,action:"resume-stable-boundary",reason:s,message:n?"Removed a stale legacy Supervisor overlay and resumed the portable state.":"Native local execution overlay matches the portable state."};let l=s==="interrupted"?o.local?.checks.find(v=>v.status==="interrupted"&&!v.repeatable):void 0;if(l){let v=an({state:t,reason:`Check ${l.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await Li({file:Je(e.paths,t.name),expectedStateVersion:t.state_version,next:v,containedRoot:e.paths.nativeRoot}),await Em.rm(xm.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let h=ae({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await V(a,h,{containedRoot:e.paths.runtimeDir}),{state:t,local:h,action:"resume-stable-boundary",reason:s,message:`Native check ${l.id} was not repeatable; the change returned to Build for a new candidate.`}}let f=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",u=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",d=f||u;if(d){let v=Qx(t,u?"Local Runtime was unavailable at Archive ready; the synchronized implementation must be verified again.":"The previous Verifier execution was unavailable; dispatch a new attempt from the stable Verify boundary.",u);t=await Li({file:Je(e.paths,t.name),expectedStateVersion:t.state_version,next:v,containedRoot:e.paths.nativeRoot})}let m=ae({portableState:t,projectRoot:e.paths.projectRoot,branch:z(e.paths.projectRoot).currentBranch});return await Em.mkdir(xm.dirname(D(e.paths,t.name)),{recursive:!0}),await V(a,m,{containedRoot:e.paths.runtimeDir}),await Po({paths:e.paths,state:t}),{state:t,local:m,action:d?"reverify":"resume-stable-boundary",reason:s,message:d?"Rebuilt local execution from the portable boundary; previous pass/execution was not reused.":`Rebuilt local execution from the portable ${t.phase}/${t.loop.stage} boundary.`}})}import Cm from"node:path";function Pm(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function xe(e,t){let r=e.acceptance.reduce((i,n)=>({...i,[n.result]:i[n.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0});return{schema:"comet.native.state-summary.v1",name:e.name,phase:e.phase,status:e.status,state_version:e.state_version,...e.coordination_mode===void 0?{}:{coordination_mode:e.coordination_mode},loop:e.loop,acceptance:r,unresolved_acceptance_ids:e.acceptance.filter(({result:i})=>i==="failed"||i==="blocked").map(({id:i})=>i),verification_result:e.verification_result,blockers:e.blockers.slice(0,8).map(i=>({owner:i.owner,reason:Pm(i.reason.text),acceptance_ids:i.acceptance_ids,resolution_action:i.resolution_action})),workspace:{isolation:e.workspace.isolation,change_branch:e.workspace.change_branch,target_branch:e.workspace.target_branch,finish:e.workspace.finish},learning:{failureResolved:e.verification_result==="pass"&&e.history.some(i=>i.outcome==="fail"&&i.goal_cycle===e.loop.goal_cycle),...e.verification?{summary:Pm(e.verification.summary.text)}:{},artifactRefs:t?["brief.md",...e.verification_report?[e.verification_report]:[],...e.spec_changes.map(i=>i.source).filter(i=>i!==null)].slice(0,16).map(i=>Cm.relative(t.projectRoot,Cm.join(t.changesDir,e.name,i)).replaceAll("\\","/")):[]},archived:e.archived}}import{randomUUID as jm}from"node:crypto";import{promises as Rm}from"node:fs";import fn from"node:path";function Jr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ve(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function B(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} must be non-empty text`);return e}function Fl(e,t){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,i)=>B(r,`${t}[${i}]`))}function eC(e){if(!Array.isArray(e))throw new Error("Native Builder checks must be an array");return e.map((t,r)=>{let i=Jr(t,`Native Builder check ${r}`);if(ve(i,["name","result","note"],`Native Builder check ${r}`),!["passed","failed","not-run"].includes(String(i.result)))throw new Error(`Native Builder check ${r} result is invalid`);if(i.note!==null&&typeof i.note!="string")throw new Error(`Native Builder check ${r} note is invalid`);return{name:B(i.name,`Native Builder check ${r} name`),result:i.result,note:i.note}})}function tC(e){if(!Array.isArray(e))throw new Error("Native Runtime checks must be an array");return e.map((t,r)=>{let i=Jr(t,`Native Runtime check ${r}`);if(ve(i,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Runtime check ${r}`),!Array.isArray(i.argv)||!i.argv.every(n=>typeof n=="string"))throw new Error(`Native Runtime check ${r} argv is invalid`);if(!Number.isSafeInteger(i.timeoutMs)||i.timeoutMs<1)throw new Error(`Native Runtime check ${r} timeoutMs is invalid`);if(typeof i.repeatable!="boolean")throw new Error(`Native Runtime check ${r} repeatable is invalid`);return{id:B(i.id,`Native Runtime check ${r} id`),name:B(i.name,`Native Runtime check ${r} name`),executable:B(i.executable,`Native Runtime check ${r} executable`),argv:[...i.argv],cwdRef:B(i.cwdRef,`Native Runtime check ${r} cwdRef`),timeoutMs:i.timeoutMs,repeatable:i.repeatable}})}function Am(e,t){let r=e.stateVersion,i=e.iteration,n=e.attempt;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${t} stateVersion is invalid`);if(!Number.isSafeInteger(i)||i<1)throw new Error(`${t} iteration is invalid`);if(!Number.isSafeInteger(n)||n<1)throw new Error(`${t} attempt is invalid`);return{stateVersion:r,iteration:i,attempt:n,verifierExecutionRef:B(e.verifierExecutionRef,`${t} verifierExecutionRef`)}}function rC(e){let t=Jr(e,"Native Supervisor evidence");return ve(t,["summary","checks"],"Native Supervisor evidence"),{summary:B(t.summary,"Native Supervisor evidence summary"),checks:Fl(t.checks,"Native Supervisor evidence checks")}}function iC(e){if(!Array.isArray(e))throw new Error("Native Supervisor integration checks must be an array");return e.map((t,r)=>{let i=Jr(t,`Native Supervisor integration check ${r}`),n=new Set(["name","status","reason"]);if(Object.keys(i).some(a=>!n.has(a)))throw new Error(`Native Supervisor integration check ${r} fields are invalid`);if(!Object.hasOwn(i,"name")||!Object.hasOwn(i,"status"))throw new Error(`Native Supervisor integration check ${r} fields are invalid`);if(!["passed","failed","incomplete"].includes(String(i.status)))throw new Error(`Native Supervisor integration check ${r} status is invalid`);if(i.reason!==void 0&&i.reason!==null&&typeof i.reason!="string")throw new Error(`Native Supervisor integration check ${r} reason is invalid`);return{name:B(i.name,`Native Supervisor integration check ${r} name`),status:i.status,reason:i.reason??null}})}function nC(e){let t=Jr(e,"Native Runner input");if(t.kind==="builder-handoff"){ve(t,["kind","summary","addressed_acceptance_ids","checks","known_limits","review"],"Native Runner Builder input");let r=Jr(t.review,"Native Builder review");if(ve(r,["status","summary","reviewer_execution_ref"],"Native Builder review"),r.status!=="passed")throw new Error("Native Builder review status must be passed");return{kind:"builder-handoff",summary:B(t.summary,"Native Builder summary"),addressed_acceptance_ids:Fl(t.addressed_acceptance_ids,"Native Builder addressed acceptance IDs"),checks:eC(t.checks),known_limits:Fl(t.known_limits,"Native Builder known limits"),review:{status:"passed",summary:B(r.summary,"Native Builder review summary"),reviewer_execution_ref:B(r.reviewer_execution_ref,"Native Builder reviewer execution ref")}}}if(t.kind==="dispatch-verifier")return ve(t,["kind","checks"],"Native Runner dispatch input"),{kind:"dispatch-verifier",checks:tC(t.checks)};if(t.kind==="verifier-response")return ve(t,["kind","response"],"Native Runner Verifier input"),{kind:"verifier-response",response:t.response};if(t.kind==="verifier-execution-error")return ve(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner execution error input"),{kind:"verifier-execution-error",summary:B(t.summary,"Native Verifier execution error summary"),...Am(t,"Native Runner execution error input")};if(t.kind==="verifier-unavailable")return ve(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner unavailable Verifier input"),{kind:"verifier-unavailable",summary:B(t.summary,"Native unavailable Verifier summary"),...Am(t,"Native Runner unavailable Verifier input")};if(t.kind==="supervisor-builder-result")return ve(t,["kind","child","runId","candidateCommit"],"Native Supervisor Builder input"),{kind:"supervisor-builder-result",child:B(t.child,"Native Supervisor child"),runId:B(t.runId,"Native Supervisor runId"),candidateCommit:B(t.candidateCommit,"Native Supervisor candidate commit")};if(t.kind==="supervisor-builder-failure")return ve(t,["kind","child","runId","reason"],"Native Supervisor Builder failure input"),{kind:"supervisor-builder-failure",child:B(t.child,"Native Supervisor child"),runId:B(t.runId,"Native Supervisor runId"),reason:B(t.reason,"Native Supervisor Builder failure reason")};if(t.kind==="supervisor-reconnect")return ve(t,["kind","child","runId"],"Native Supervisor reconnect input"),{kind:"supervisor-reconnect",child:B(t.child,"Native Supervisor child"),runId:B(t.runId,"Native Supervisor runId")};if(t.kind==="supervisor-cancel")return ve(t,["kind","child","runId","reason"],"Native Supervisor cancel input"),{kind:"supervisor-cancel",child:B(t.child,"Native Supervisor child"),runId:B(t.runId,"Native Supervisor runId"),reason:B(t.reason,"Native Supervisor cancellation reason")};if(t.kind==="supervisor-verifier-result"){if(ve(t,["kind","child","runId","verdict","evidence"],"Native Supervisor Verifier input"),!["pass","fail","incomplete"].includes(String(t.verdict)))throw new Error("Native Supervisor Verifier verdict is invalid");return{kind:"supervisor-verifier-result",child:B(t.child,"Native Supervisor child"),runId:B(t.runId,"Native Supervisor runId"),verdict:t.verdict,evidence:rC(t.evidence)}}if(t.kind==="supervisor-integrate")return ve(t,["kind","child","checks"],"Native Supervisor integration input"),{kind:"supervisor-integrate",child:B(t.child,"Native Supervisor child"),checks:iC(t.checks)};throw new Error("Native Runner input kind is invalid")}async function $m(e,t){let r=fn.resolve(t,e),i=await Rm.lstat(r);if(!i.isFile()||i.isSymbolicLink())throw new Error("Native Runner input must be a regular non-symlink file");let n;try{n=JSON.parse(await Rm.readFile(r,"utf8"))}catch(a){throw new Error("Native Runner input must be valid JSON",{cause:a})}return nC(n)}function _m(e){return`${Z}:${e}:${jm()}`}function Im(e,t,r,i){if(fn.resolve(I(e.projectRoot,["rev-parse","--show-toplevel"]))!==fn.resolve(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree identity is invalid`);if(I(e.projectRoot,["branch","--show-current"])!==i)throw new Error(`Native Supervisor ${r} result came from the wrong Child worktree branch`);if(!ut(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree must be clean before returning a commit`);if(I(e.projectRoot,["rev-parse","HEAD"])!==t)throw new Error(`Native Supervisor ${r} result is not bound to the worktree HEAD`);try{I(e.projectRoot,["merge-base","--is-ancestor",e.baseCommit,t])}catch(s){throw new Error(`Native Supervisor ${r} result is not based on its task base commit`,{cause:s})}}function aC(e,t){let r=z(e.projectRoot),i=fn.resolve(r.currentWorktreeRoot??"");if(!r.isGitWorktree||i!==fn.resolve(e.projectRoot))throw new Error("Native Supervisor task worktree identity is invalid");if(r.currentBranch!==t)throw new Error("Native Supervisor task is attached to the wrong Child branch");let n=I(e.projectRoot,["rev-parse","HEAD"]);if(e.role==="verifier"){if(!ut(e.projectRoot)||n!==e.baseCommit)throw new Error("Native Supervisor Verifier task worktree is not at its candidate commit");return}try{I(e.projectRoot,["merge-base","--is-ancestor",e.baseCommit,n])}catch(a){throw new Error("Native Supervisor Builder task base commit is not an ancestor of its HEAD",{cause:a})}}function dn(e){if(e.builder_handoff===null)throw new Error("Native Skill coordination has no current Builder candidate");if(e.builder_handoff.identity_provider!==Z)throw new Error("Native candidate is owned by a host identity adapter and cannot use the generic Skill coordination bridge");if(!e.builder_handoff.review)throw new Error("Native Skill coordination requires a passed read-only review");return e.builder_handoff}function oC(e){return[...e.history].reverse().find(({outcome:t})=>t==="recovery")?.summary}function Tm(e){let{paths:t,state:r,checks:i,verifierExecutionRef:n,supervisor:a}=e,o=dn(r);if(!o.review)throw new Error("Native Skill coordination requires a passed read-only review");let s=oC(r),c=r.acceptance.filter(({result:l})=>l==="pending").map(({id:l})=>l);return{coordination:Z,change:r.name,candidateId:o.candidate_id,stateVersion:r.state_version,iteration:r.loop.iteration,attempt:r.loop.attempt,verifierExecutionRef:n,projectRoot:t.projectRoot,verificationRoot:a?.integration.worktree??t.projectRoot,changeDir:ce(t,r.name),supervisorStateRef:a?Lr(t,r.name):null,briefRef:r.brief,specRefs:r.spec_changes.map(({capability:l,operation:f,source:u})=>({capability:l,operation:f,ref:u})),acceptanceCount:r.acceptance.length,scopeIds:c,detailsPageArgs:["comet","native","status",r.name,"--details","--json","--project-root",t.projectRoot],...s===void 0?{}:{recoveryContext:s},builderReview:{status:o.review.status,summary:o.review.summary},runtimeChecks:i.map(l=>({...l}))}}async function Ml(e){dn(e.state);let t=await ot(D(e.paths,e.state.name));if(t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version||t.execution===null||t.execution.stage!=="verifying"||t.execution.actor!=="verifier"||t.execution.status!=="running"||t.execution.executionId===null)throw new Error("Native Skill coordination has no active Verifier attempt");return t.execution.executionId}async function Om(e){let t=e.input,r=await _(e.paths,e.name),i=await un({paths:e.paths,state:r});if(i.status==="incompatible")throw new Error(i.message);let n=i.status==="repairable-legacy-overlay"?null:await W(e.paths,e.name),a=n!==null&&r?.phase==="verify"&&n.children.every(({status:v})=>v==="integrated"||v==="archived"),o=n!==null&&r?.phase==="build"&&n.children.every(({status:v})=>v==="integrated"||v==="archived");if(n&&t.kind==="supervisor-builder-result")return x(e.paths,`apply Native Supervisor Builder result ${t.child}`,async()=>{let v=await W(e.paths,e.name);if(!v)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=v.children.find(({name:b})=>b===t.child);if(!h?.task||h.task.role!=="builder")throw new Error(`Native Supervisor Builder task is not active for ${t.child}`);try{Im(h.task,t.candidateCommit,"builder",`comet/supervisor/${v.parent}/${t.child}`)}catch(b){throw await ne(e.paths,oo(v,{child:t.child,runId:t.runId,reason:b.message})),b}let p=h.task.projectRoot,w=hh(v,t),g=cl(w,{role:"verifier",child:t.child,projectRoot:p,runId:jm()});await ne(e.paths,g.state);let y=await _(e.paths,e.name);return{state:y,supervisorTask:g.task,checks:[],requestChecks:null,verifierDispatch:null,continuation:Q(y)}});if(n&&t.kind==="supervisor-builder-failure")return x(e.paths,`cancel Native Supervisor Builder task ${t.child}`,async()=>{let v=await W(e.paths,e.name);if(!v)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=v.children.find(({name:g})=>g===t.child);if(!h?.task||h.task.role!=="builder")throw new Error(`Native Supervisor Builder failure is not valid for ${t.child}`);let p=ul(v,{child:t.child,runId:t.runId,reason:t.reason});await ne(e.paths,p);let w=await _(e.paths,e.name);return{state:w,supervisorState:p,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:Q(w)}});if(n&&t.kind==="supervisor-reconnect")return x(e.paths,`reconnect Native Supervisor task ${t.child}`,async()=>{let v=await W(e.paths,e.name);if(!v)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=v.children.find(({name:g})=>g===t.child)?.task;if(!h||h.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);try{aC(h,`comet/supervisor/${v.parent}/${t.child}`)}catch(g){throw await ne(e.paths,oo(v,{child:t.child,runId:t.runId,reason:g.message})),g}let p=fh(v,{child:t.child,runId:t.runId});await ne(e.paths,p.state);let w=await _(e.paths,e.name);return{state:w,supervisorState:p.state,supervisorTask:p.task,checks:[],requestChecks:null,verifierDispatch:null,continuation:Q(w)}});if(n&&t.kind==="supervisor-cancel")return x(e.paths,`cancel Native Supervisor task ${t.child}`,async()=>{let v=await W(e.paths,e.name);if(!v)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=ul(v,{child:t.child,runId:t.runId,reason:t.reason});await ne(e.paths,h);let p=await _(e.paths,e.name);return{state:p,supervisorState:h,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:Q(p)}});if(n&&t.kind==="supervisor-verifier-result")return x(e.paths,`apply Native Supervisor Verifier result ${t.child}`,async()=>{let v=await W(e.paths,e.name);if(!v)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=v.children.find(({name:g})=>g===t.child);if(!h?.task||h.task.role!=="verifier"||!h.candidateCommit)throw new Error(`Native Supervisor Verifier task is not active for ${t.child}`);try{Im(h.task,h.candidateCommit,"verifier",`comet/supervisor/${v.parent}/${t.child}`)}catch(g){throw await ne(e.paths,oo(v,{child:t.child,runId:t.runId,reason:g.message})),g}let p=mh(v,t);await ne(e.paths,p);let w=await _(e.paths,e.name);return{state:w,supervisorState:p,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:Q(w)}});if(n&&t.kind==="supervisor-integrate"){let v=await vh({paths:e.paths,state:n,name:t.child,checks:t.checks}),h=await Eo({paths:e.paths,name:e.name,trigger:"v2-integrate"}),p=h.state;return{state:p,supervisorState:v,supervisorTask:null,checks:t.checks,requestChecks:null,verifierDispatch:null,parentAdvance:h.parentAdvance,continuation:Q(p)}}if(n&&(t.kind==="builder-handoff"||t.kind==="dispatch-verifier"||t.kind==="verifier-response"||t.kind==="verifier-execution-error"||t.kind==="verifier-unavailable"||t.kind==="supervisor-builder-result"||t.kind==="supervisor-builder-failure"||t.kind==="supervisor-reconnect"||t.kind==="supervisor-cancel"||t.kind==="supervisor-verifier-result")&&!a&&!(t.kind==="builder-handoff"&&o))throw new Error("Native Supervisor accepts only Supervisor task result inputs until every Child is integrated");if(t.kind==="builder-handoff"){let h=bl().captureExecutionIdentity({identityProvider:Z,executionRef:_m("builder")}),p=await tm({paths:e.paths,name:e.name,input:{identity:h,summary:t.summary,addressedAcceptanceIds:t.addressed_acceptance_ids,checks:t.checks,knownLimits:t.known_limits,review:{status:t.review.status,summary:t.review.summary,reviewerExecutionRef:t.review.reviewer_execution_ref}}});return{state:p,checks:[],requestChecks:null,verifierDispatch:null,continuation:Q(p)}}if(t.kind==="dispatch-verifier"){if(a&&t.checks.length===0)throw new Error("Native Supervisor parent verification requires at least one check");let v=await _(e.paths,e.name);if(v.builder_handoff!==null&&v.builder_handoff.identity_provider!==Z){let y=await xo({paths:e.paths,name:e.name,reason:"The previous Builder identity provider is unavailable to the generic Skill bridge; submit a new Builder candidate before dispatching a Verifier."});return{state:y,checks:[],requestChecks:null,verifierDispatch:null,continuation:Q(y)}}dn(v);let p=(v.loop.next_action==="run-final-full-verification"&&v.verification?.verdict==="pass"&&v.verification.checks.every(({status:y})=>y==="passed")?v.verification.checks:null)??(await am({paths:e.paths,name:e.name,plans:t.checks,...a&&n?{projectRoot:n.integration.worktree}:{}})).checks,w=_m("verifier"),g=await om({paths:e.paths,name:e.name,checks:p,verifierExecutionId:w,...a&&n?{projectRoot:n.integration.worktree}:{}});return{state:g,checks:p,requestChecks:null,verifierDispatch:Tm({paths:e.paths,state:g,checks:p,verifierExecutionRef:w,supervisor:a?n:null}),continuation:Q(g)}}if(t.kind==="verifier-execution-error"){let v=await _(e.paths,e.name);dn(v),await Ml({paths:e.paths,state:v});let h=await cm({paths:e.paths,name:e.name,summary:t.summary,expected:t,requireSkillCoordination:!0});return{state:h,checks:[],requestChecks:null,verifierDispatch:null,continuation:Q(h)}}if(t.kind==="verifier-unavailable"){let v=await lm({paths:e.paths,name:e.name,summary:t.summary,expected:t,requireSkillCoordination:!0});return{state:v,checks:v.verification?.checks??[],requestChecks:null,verifierDispatch:null,continuation:Q(v)}}if(t.kind!=="verifier-response")throw new Error("Native Runner input kind is invalid for the portable verifier bridge");let s=await _(e.paths,e.name),c=dn(s),l=await Ml({paths:e.paths,state:s}),f=bl(),u=f.captureExecutionIdentity({identityProvider:Z,executionRef:l}),d=null;if(a&&typeof t.response=="object"&&t.response!==null&&"kind"in t.response&&t.response.kind==="final-result"){let v=await W(e.paths,e.name);if(!v)throw new Error("Native Supervisor state disappeared before final verification");d=Yi(v)}let m=await sm({paths:e.paths,name:e.name,envelope:f.envelopeVerifierResponse({candidateId:c.candidate_id,identity:u,payload:t.response}),checks:[],maxVerifyFailures:e.maxVerifyFailures,...a&&n?{projectRoot:n.integration.worktree}:{}});if(a&&m.response.kind==="final-result"){if(m.state.verification_result==="pass"&&(m.checks.length===0||m.checks.some(({status:p})=>p!=="passed")))throw new Error("Native Supervisor parent verification cannot pass without completed integration checks");let v=d??await W(e.paths,e.name);if(!v)throw new Error("Native Supervisor state disappeared during verification");let h=Xi(v,m.state);return await ne(e.paths,h),{...m,supervisorState:h,verifierDispatch:null,continuation:Q(m.state)}}return{...m,verifierDispatch:m.requestChecks===null?null:Tm({paths:e.paths,state:m.state,checks:m.checks,verifierExecutionRef:await Ml({paths:e.paths,state:m.state}),supervisor:a?n:null}),continuation:Q(m.state)}}import hn from"path";import{realpathSync as eP}from"fs";var wt={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function Hm(e){return e?e.command?`${wt.next} ${e.command}`:e.ask_user?`${wt.next} ${e.ask_user}`:null:null}function Dm(e,t){let r=[e.summary],i=Hm(e.next);return i&&r.push(i),e.user_message&&r.push("",wt.relay,e.user_message),t!==void 0&&r.push("",wt.details,JSON.stringify(t,null,2)),`${r.join(`
243
243
  `)}
244
- `}function Hm(e,t,r){let i=[e.summary],n=$m(e.next);return n&&i.push(n),e.user_message&&i.push("",wt.relay,e.user_message),i.push("",`${wt.detail} ${t}`),r!==void 0&&i.push("",wt.details,JSON.stringify(r,null,2)),i.join(`
245
- `)}var oC=Object.freeze({maxChanges:32,maxSpecsPerChange:64,maxArtifactsPerChange:128,maxTotalSpecs:512,maxTotalArtifacts:1024,maxSignalsPerRelationship:8,maxRelationships:256,maxSerializedBytes:64*1024,maxNameBytes:128,maxCapabilityBytes:128,maxArtifactPathBytes:512});var Dm=1024*1024;var Lm="scoped-text-safety",sC=1,cC=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var lC="comet.native.checker-policy.v1";var V0=X(lC,{policy:Lm,version:sC,limits:cC,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var uC=["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"],M0=new Set(uC);var pC=Dm,nH=3*pC;var Vm={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:[]},mC=Ie("comet-native-runtime:v3:scope-reopen"),IH=[{skillVersion:"3",skillHash:Ie("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:Ie("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:Ie("comet-native-runtime:v1")}];var Fm=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],dD=new Set(Fm),kC=new Set([...Fm,"minimum_runtime_version","revision"]),fD=new Set([...kC,"operation"]),pD=512*1024,SC=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),hD=new Set([...SC,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);var yD={maxAcceptanceCriteria:Ka.maxCriteria};var ED={maxSpecs:64,maxFileBytes:va,maxTotalBytes:4*1024*1024};import{execFile as TC}from"node:child_process";import{promisify as jC}from"node:util";var $D={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};var tB=512*1024;var pn=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};var EB=64*1024;var xB=3600*1e3;var CB=jC(TC);var _o=class extends Error{details;constructor(t){let r=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(i=>`${i.ref}${i.acceptanceId?`[${i.acceptanceId}]`:""} -> ${i.mismatches.join("; ")}`).join(" | ")}`;super(r),this.name="NativeVerificationReceiptBindingError",this.details=t}};var dL={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var bL=16*1024*1024,kL=256*1024,SL=16*1024;var AL=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var TL=16*1024;var WL=16*1024;var $V=16*1024*1024,Io=class extends Error{constructor(r,i,n,a){super(`Canonical spec conflict for ${r}: expected ${i??"(missing)"}, actual ${n??"(missing)"}`);this.capability=r;this.expectedHash=i;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},To=class extends Error{constructor(r,i=r.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${r.findingCodes.join(", ")}`){super(i);this.preflight=r;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};function R(e,t,r){return e==="zh-CN"?r:t}var ql={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function zm(e,t){return typeof e=="string"&&ql[e]?R(t,ql[e].en,ql[e].zh):typeof e=="string"?e:""}function Wl(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 LC(e){let t={total:e.length,passed:0,failed:0,blocked:0,pending:0};for(let r of e){if(!r||typeof r!="object")return null;let i=r.result;if(i!=="passed"&&i!=="failed"&&i!=="blocked"&&i!=="pending")return null;t[i]+=1}return t}function Jm(e,t){let r=[];e.failed>0&&r.push(R(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(R(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(R(t,`${e.pending} pending`,`${e.pending} 项待验`));let i=R(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function Gm(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.change!="string"||t.disposition!=="continue"&&t.disposition!=="await-user"&&t.disposition!=="blocked"&&t.disposition!=="done"||t.commandArgs!==null&&t.commandArgs!==void 0&&!Array.isArray(t.commandArgs))return!1;let r=t.userCommunication;return!!(r&&typeof r=="object"&&typeof r.required=="boolean"&&(r.message===null||typeof r.message=="string")&&typeof r.agentInstruction=="string")}function zl(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function VC(e,t,r){return e==="done"?R(r,"complete","已完成"):e==="await-user"?R(r,"waiting for a user decision","等待用户决定"):e==="blocked"?R(r,"paused: needs attention","已暂停,需要处理"):t?R(r,"waiting for a user decision","等待用户决定"):R(r,"ready to continue","可继续推进")}function MC(e,t,r){let i=zl(e),n=[];r&&n.push(r);let a=R(i,`Change ${e.change}`,`需求 ${e.change}`),o=zm(e.phase,i),s=VC(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(Jm(t,i));let c=e.userCommunication,l=Um(e,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function Um(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:R(t,"Relay the message below, wait for the user decision, then run the matching option (run with --json to see the exact alternative commands).","先转述下方信息并等待用户选择,再执行对应命令(完整候选命令以 --json 输出为准)。")};if(e.commandArgs&&e.commandArgs.length>0)return{command:e.commandArgs.join(" ")};if(e.disposition==="done")return{ask_user:R(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(e.disposition==="blocked")return{ask_user:R(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function FC(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function qC(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=zm(e.phase,t),n=e.status==="await-user"?R(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?R(t,"paused","已暂停"):e.status==="done"?R(t,"complete","已完成"):R(t,"in progress","进行中"),a=Wl(e.acceptance)?`${R(t,", ",",")}${Jm(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function WC(e){for(let t of e){let r=t.continuation;if(r?.userCommunication&&typeof r.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(r.userCommunication.agentInstruction))return"zh-CN"}return"en"}function zC(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 JC(e){if(e.healthy){let i=e.repaired?R("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):R("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=GC(e.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:R("en",r>0?`Diagnostics found ${r} problem${r===1?"":"s"} that need attention before this change can continue.`:"Diagnostics found problems that need attention before this change can continue.",r>0?`诊断发现 ${r} 个需要处理的问题,处理后该需求才能继续。`:"诊断发现需要处理的问题,处理后该需求才能继续。"),next:{ask_user:R("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function GC(e){return Gm(e)?Um(e,zl(e)):void 0}function Km(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(zC(t))return JC(t);if(FC(t)){let i=WC(t.items);return{summary:[t.total===t.items.length?R(i,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):R(i,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>qC(a,i))].join(`
246
- `)}}let r=t.continuation;if(Gm(r))return MC(r,UC(t),KC(t,zl(r)));if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let i=t.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in t;return{summary:R(i,n?`Comet Native artifacts live under ${t.artifactRoot} (state root: ${t.nativeRoot}).`:`Initialized Comet Native at ${t.nativeRoot} (artifacts: ${t.artifactRoot}).`,n?`Comet Native 产物位于 ${t.artifactRoot}(状态根目录:${t.nativeRoot})。`:`Comet Native 已初始化于 ${t.nativeRoot}(产物目录:${t.artifactRoot})。`)}}}function UC(e){if(Wl(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(Wl(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return LC(r.acceptance)}return null}function KC(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return R(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?R(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function Ym(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"conflict":return{summary:R("en","This change was updated elsewhere while the command ran, so the command stopped without changing anything. Nothing was lost — reload the latest state and continue from there.","这条需求刚被另一个会话更新,本次命令未做任何改动。没有工作丢失——重新读取最新状态后继续即可。"),...typeof r.change=="string"?{next:{command:`comet native status ${r.change} --json`}}:{}};case"baseline-incomplete":return{summary:R("en","The safety snapshot for this change exceeded its configured size budget, so the command stopped before changing anything. Raise the snapshot limits in .comet/config.yaml or exclude out-of-scope data, then retry.","该需求的安全快照超出配置的容量预算,命令在改动任何内容前已停止。请在 .comet/config.yaml 中调高快照上限,或将范围外的数据加入排除列表后重试。"),next:{ask_user:R("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:R("en","This change runs in its own Git worktree to keep work isolated. Create the linked worktree first, then continue inside it.","这条需求需要在独立的 Git worktree 中执行以保证隔离。请先创建关联的 worktree,然后在其中继续。"),next:{ask_user:R("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:R("en","The change workspace is not fully prepared (for example a branch or worktree is missing). Finish the preparation steps, then retry.","需求的工作区尚未准备完成(例如分支或 worktree 缺失)。请先完成准备步骤,再重试。"),next:{ask_user:R("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:R("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:R("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}var Xm=["--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."],Gl=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:Xm,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>]
244
+ `}function Bm(e,t,r){let i=[e.summary],n=Hm(e.next);return n&&i.push(n),e.user_message&&i.push("",wt.relay,e.user_message),i.push("",`${wt.detail} ${t}`),r!==void 0&&i.push("",wt.details,JSON.stringify(r,null,2)),i.join(`
245
+ `)}var sC=Object.freeze({maxChanges:32,maxSpecsPerChange:64,maxArtifactsPerChange:128,maxTotalSpecs:512,maxTotalArtifacts:1024,maxSignalsPerRelationship:8,maxRelationships:256,maxSerializedBytes:64*1024,maxNameBytes:128,maxCapabilityBytes:128,maxArtifactPathBytes:512});var Lm=1024*1024;var Mm="scoped-text-safety",cC=1,lC=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var uC="comet.native.checker-policy.v1";var F0=X(uC,{policy:Mm,version:cC,limits:lC,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var dC=["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"],q0=new Set(dC);var hC=Lm,oH=3*hC;var Fm={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:[]},vC=Ie("comet-native-runtime:v3:scope-reopen"),jH=[{skillVersion:"3",skillHash:Ie("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:Ie("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:Ie("comet-native-runtime:v1")}];var Wm=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],pD=new Set(Wm),SC=new Set([...Wm,"minimum_runtime_version","revision"]),hD=new Set([...SC,"operation"]),mD=512*1024,EC=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),vD=new Set([...EC,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);var bD={maxAcceptanceCriteria:Ka.maxCriteria};var CD={maxSpecs:64,maxFileBytes:va,maxTotalBytes:4*1024*1024};import{execFile as jC}from"node:child_process";import{promisify as $C}from"node:util";var HD={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};var iB=512*1024;var pn=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};var CB=64*1024;var PB=3600*1e3;var RB=$C(jC);var _o=class extends Error{details;constructor(t){let r=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(i=>`${i.ref}${i.acceptanceId?`[${i.acceptanceId}]`:""} -> ${i.mismatches.join("; ")}`).join(" | ")}`;super(r),this.name="NativeVerificationReceiptBindingError",this.details=t}};var pL={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var SL=16*1024*1024,EL=256*1024,xL=16*1024;var IL=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var $L=16*1024;var JL=16*1024;var HV=16*1024*1024,Io=class extends Error{constructor(r,i,n,a){super(`Canonical spec conflict for ${r}: expected ${i??"(missing)"}, actual ${n??"(missing)"}`);this.capability=r;this.expectedHash=i;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},To=class extends Error{constructor(r,i=r.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${r.findingCodes.join(", ")}`){super(i);this.preflight=r;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};function R(e,t,r){return e==="zh-CN"?r:t}var ql={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function Gm(e,t){return typeof e=="string"&&ql[e]?R(t,ql[e].en,ql[e].zh):typeof e=="string"?e:""}function Wl(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 VC(e){let t={total:e.length,passed:0,failed:0,blocked:0,pending:0};for(let r of e){if(!r||typeof r!="object")return null;let i=r.result;if(i!=="passed"&&i!=="failed"&&i!=="blocked"&&i!=="pending")return null;t[i]+=1}return t}function Um(e,t){let r=[];e.failed>0&&r.push(R(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(R(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(R(t,`${e.pending} pending`,`${e.pending} 项待验`));let i=R(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function Km(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.change!="string"||t.disposition!=="continue"&&t.disposition!=="await-user"&&t.disposition!=="blocked"&&t.disposition!=="done"||t.commandArgs!==null&&t.commandArgs!==void 0&&!Array.isArray(t.commandArgs))return!1;let r=t.userCommunication;return!!(r&&typeof r=="object"&&typeof r.required=="boolean"&&(r.message===null||typeof r.message=="string")&&typeof r.agentInstruction=="string")}function zl(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function MC(e,t,r){return e==="done"?R(r,"complete","已完成"):e==="await-user"?R(r,"waiting for a user decision","等待用户决定"):e==="blocked"?R(r,"paused: needs attention","已暂停,需要处理"):t?R(r,"waiting for a user decision","等待用户决定"):R(r,"ready to continue","可继续推进")}function FC(e,t,r){let i=zl(e),n=[];r&&n.push(r);let a=R(i,`Change ${e.change}`,`需求 ${e.change}`),o=Gm(e.phase,i),s=MC(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(Um(t,i));let c=e.userCommunication,l=Ym(e,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function Ym(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:R(t,"Relay the message below, wait for the user decision, then run the matching option (run with --json to see the exact alternative commands).","先转述下方信息并等待用户选择,再执行对应命令(完整候选命令以 --json 输出为准)。")};if(e.commandArgs&&e.commandArgs.length>0)return{command:e.commandArgs.join(" ")};if(e.disposition==="done")return{ask_user:R(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(e.disposition==="blocked")return{ask_user:R(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function qC(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function WC(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=Gm(e.phase,t),n=e.status==="await-user"?R(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?R(t,"paused","已暂停"):e.status==="done"?R(t,"complete","已完成"):R(t,"in progress","进行中"),a=Wl(e.acceptance)?`${R(t,", ",",")}${Um(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function zC(e){for(let t of e){let r=t.continuation;if(r?.userCommunication&&typeof r.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(r.userCommunication.agentInstruction))return"zh-CN"}return"en"}function JC(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 GC(e){if(e.healthy){let i=e.repaired?R("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):R("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=UC(e.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:R("en",r>0?`Diagnostics found ${r} problem${r===1?"":"s"} that need attention before this change can continue.`:"Diagnostics found problems that need attention before this change can continue.",r>0?`诊断发现 ${r} 个需要处理的问题,处理后该需求才能继续。`:"诊断发现需要处理的问题,处理后该需求才能继续。"),next:{ask_user:R("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function UC(e){return Km(e)?Ym(e,zl(e)):void 0}function Xm(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(JC(t))return GC(t);if(qC(t)){let i=zC(t.items);return{summary:[t.total===t.items.length?R(i,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):R(i,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>WC(a,i))].join(`
246
+ `)}}let r=t.continuation;if(Km(r))return FC(r,KC(t),YC(t,zl(r)));if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let i=t.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in t;return{summary:R(i,n?`Comet Native artifacts live under ${t.artifactRoot} (state root: ${t.nativeRoot}).`:`Initialized Comet Native at ${t.nativeRoot} (artifacts: ${t.artifactRoot}).`,n?`Comet Native 产物位于 ${t.artifactRoot}(状态根目录:${t.nativeRoot})。`:`Comet Native 已初始化于 ${t.nativeRoot}(产物目录:${t.artifactRoot})。`)}}}function KC(e){if(Wl(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(Wl(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return VC(r.acceptance)}return null}function YC(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return R(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?R(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function Qm(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"conflict":return{summary:R("en","This change was updated elsewhere while the command ran, so the command stopped without changing anything. Nothing was lost — reload the latest state and continue from there.","这条需求刚被另一个会话更新,本次命令未做任何改动。没有工作丢失——重新读取最新状态后继续即可。"),...typeof r.change=="string"?{next:{command:`comet native status ${r.change} --json`}}:{}};case"baseline-incomplete":return{summary:R("en","The safety snapshot for this change exceeded its configured size budget, so the command stopped before changing anything. Raise the snapshot limits in .comet/config.yaml or exclude out-of-scope data, then retry.","该需求的安全快照超出配置的容量预算,命令在改动任何内容前已停止。请在 .comet/config.yaml 中调高快照上限,或将范围外的数据加入排除列表后重试。"),next:{ask_user:R("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:R("en","This change runs in its own Git worktree to keep work isolated. Create the linked worktree first, then continue inside it.","这条需求需要在独立的 Git worktree 中执行以保证隔离。请先创建关联的 worktree,然后在其中继续。"),next:{ask_user:R("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:R("en","The change workspace is not fully prepared (for example a branch or worktree is missing). Finish the preparation steps, then retry.","需求的工作区尚未准备完成(例如分支或 worktree 缺失)。请先完成准备步骤,再重试。"),next:{ask_user:R("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:R("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:R("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}var Zm=["--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."],Gl=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:Zm,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>]
247
247
  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>]
248
248
  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]
249
249
  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 Jl(e,t){return`${e}:
250
250
  ${t.map(r=>` ${r}`).join(`
251
- `)}`}function YC(e){let t=e.filter(i=>i!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return Gl[r]||t.length>1&&Gl[t[0]]?.subcommands?r:t[0]}function XC(e=[]){let t=YC(e),r=Gl[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.subcommands&&i.push("",Jl("Commands",r.subcommands));let n=t===""?r.options:[...r.options??[],...Xm];return n&&n.length>0&&i.push("",Jl("Options",n)),i.push("",`Output:
251
+ `)}`}function XC(e){let t=e.filter(i=>i!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return Gl[r]||t.length>1&&Gl[t[0]]?.subcommands?r:t[0]}function QC(e=[]){let t=XC(e),r=Gl[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.subcommands&&i.push("",Jl("Commands",r.subcommands));let n=t===""?r.options:[...r.options??[],...Zm];return n&&n.length>0&&i.push("",Jl("Options",n)),i.push("",`Output:
252
252
  ${r.output}`),r.examples&&i.push("",Jl("Examples",r.examples)),t===""&&i.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${i.join(`
253
253
  `)}
254
- `}}var QC=XC().usage;var ZV=10*1024*1024,L=class extends Error{};function st(e,t){let r=e.flatMap((i,n)=>i===t?[n]:[]);if(r.length>1)throw new L(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function yt(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new L(`${t} may only be provided once`);if(r.length===0)return;let i=r[0],n=e[i+1];if(n===void 0||n.startsWith("--"))throw new L(`${t} requires a value`);return e.splice(i,2),n}function Zm(e){if(e.length>0)throw new L(`Unexpected argument: ${e[0]}`)}function ev(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new L(`${t} is required`);return r}function Ul(e,t){let r=hn.normalize(Qm(e)),i=hn.normalize(Qm(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function Qm(e){let t=hn.resolve(e);try{return ZC.native(t)}catch{return t}}function eP(e){let t=hn.resolve(e),r=z(process.cwd());if(!r.isSecondaryWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null)return t;let i=z(t);return!i.isGitWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null||!Ul(r.primaryWorktreeRoot,i.primaryWorktreeRoot)||Ul(r.currentWorktreeRoot,i.currentWorktreeRoot)?t:Ul(process.cwd(),r.currentWorktreeRoot)?hn.resolve(process.cwd()):r.currentWorktreeRoot}async function tv(e){return e?eP(e):Ra(process.cwd())}async function rv(e){let t=await ap({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function iv(e){return JSON.stringify(e,null,2)+`
255
- `}function je(e,t,r){return{command:e,exitCode:0,data:t,text:r??iv(t)}}function tP(e,t){if(t instanceof L)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Io)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 To)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof Ja)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 Fi)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 Lt)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Ga)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 _o)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof pn)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let r=t.code;if(r&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(r))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let i=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:i?73:65,error:{code:i?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function nv(e,t){let r=tP(e,t),i=r.error;if(!i)return r;let n=Ym({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function av(e,t,r=!1){let i=e.envelope??Km(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...i===void 0?{}:{summary:i.summary,...i.next===void 0?{}:{next:i.next},...i.user_message===void 0?{}:{user_message:i.user_message}},...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
256
- `}:e.error?{exitCode:e.exitCode,stderr:i?Hm(i,e.error.message,r?e.data:void 0):e.error.message}:i?{exitCode:e.exitCode,stdout:Om(i,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==iv(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
254
+ `}}var ZC=QC().usage;var t1=10*1024*1024,L=class extends Error{};function st(e,t){let r=e.flatMap((i,n)=>i===t?[n]:[]);if(r.length>1)throw new L(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function yt(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new L(`${t} may only be provided once`);if(r.length===0)return;let i=r[0],n=e[i+1];if(n===void 0||n.startsWith("--"))throw new L(`${t} requires a value`);return e.splice(i,2),n}function tv(e){if(e.length>0)throw new L(`Unexpected argument: ${e[0]}`)}function rv(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new L(`${t} is required`);return r}function Ul(e,t){let r=hn.normalize(ev(e)),i=hn.normalize(ev(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function ev(e){let t=hn.resolve(e);try{return eP.native(t)}catch{return t}}function tP(e){let t=hn.resolve(e),r=z(process.cwd());if(!r.isSecondaryWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null)return t;let i=z(t);return!i.isGitWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null||!Ul(r.primaryWorktreeRoot,i.primaryWorktreeRoot)||Ul(r.currentWorktreeRoot,i.currentWorktreeRoot)?t:Ul(process.cwd(),r.currentWorktreeRoot)?hn.resolve(process.cwd()):r.currentWorktreeRoot}async function iv(e){return e?tP(e):Ra(process.cwd())}async function nv(e){let t=await ap({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function av(e){return JSON.stringify(e,null,2)+`
255
+ `}function je(e,t,r){return{command:e,exitCode:0,data:t,text:r??av(t)}}function rP(e,t){if(t instanceof L)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Io)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 To)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof Ja)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 Fi)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 Lt)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Ga)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 _o)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof pn)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let r=t.code;if(r&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(r))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let i=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:i?73:65,error:{code:i?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function ov(e,t){let r=rP(e,t),i=r.error;if(!i)return r;let n=Qm({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function sv(e,t,r=!1){let i=e.envelope??Xm(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...i===void 0?{}:{summary:i.summary,...i.next===void 0?{}:{next:i.next},...i.user_message===void 0?{}:{user_message:i.user_message}},...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
256
+ `}:e.error?{exitCode:e.exitCode,stderr:i?Bm(i,e.error.message,r?e.data:void 0):e.error.message}:i?{exitCode:e.exitCode,stdout:Dm(i,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==av(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
257
257
  ${wt.details}
258
258
  ${JSON.stringify(e.data,null,2)}
259
- `}:{exitCode:e.exitCode,stdout:e.text}}var rP=new Set(["prepare-shape-confirmation","confirm-shape","accept-result","confirm-verifier-unavailable","revise-implementation","revise-requirements","retry-verifier","resolve-verifier-blocker"]);function iP(e){let t=yt(e,"--expected-state-version"),r=yt(e,"--expected-action");if(!(t===void 0&&r===void 0)){if(t===void 0||r===void 0)throw new L("--expected-state-version and --expected-action must be provided together");if(!/^[1-9]\d*$/u.test(t)||!Number.isSafeInteger(Number(t)))throw new L("--expected-state-version must be a positive integer");if(!rP.has(r))throw new L("--expected-action is not a recognized Native continuation action");return{stateVersion:Number(t),action:r}}}async function Nt(e,t){let r=await nt({paths:e,state:t});return{...r?{childSummary:r.children.reduce((i,n)=>({...i,[n.status]:(i[n.status]??0)+1}),{total:r.children.length}),readyChildren:r.readyChildren}:{},continuation:Q(t,r)}}function nP(e){return Object.fromEntries(Object.entries(e).filter(([t])=>t!=="state"&&t!=="response"&&t!=="supervisorState"))}function ov(e){return{action:e.action,reason:e.reason,message:e.message}}async function sv(e,t){let r=ev(e,"change name"),i=yt(e,"--summary"),n=yt(e,"--runner-input"),a=st(e,"--confirmed"),o=st(e,"--accept-result"),s=st(e,"--revise-implementation"),c=st(e,"--revise-requirements"),l=st(e,"--retry-verifier"),f=st(e,"--resolve-verifier-blocker"),u=yt(e,"--coordination-mode"),d=u;if(u!==void 0&&!Ta.includes(u))throw new L("--coordination-mode must be multi-session or single-session");let m=yt(e,"--max-parallel"),v=m===void 0?2:Number(m);if(!Number.isSafeInteger(v)||v<1)throw new L("--max-parallel must be a positive integer");let h=iP(e);if([a,o,s,c,l,f].filter(Boolean).length>1)throw new L("--confirmed, --accept-result, --revise-implementation, --revise-requirements, --retry-verifier, and --resolve-verifier-blocker are mutually exclusive");if(d!==void 0&&(a||o||s||c||l||f||n!==void 0))throw new L("--coordination-mode is only valid when preparing a Supervisor Shape confirmation");Zm(e);let p=await rv(t);if(!await sn(p.paths,r)){if(n)throw new L("--runner-input is only valid for portable Native changes");if(!i)throw new L("--summary is required");let k=await km({paths:p.paths,name:r});return je("next",{state:xe(k),migration:{completed:!0,summary:i},continuation:Q(k)})}let w=await _(p.paths,r),g=Ll(p.paths,w);if(g)return je("next",{state:xe(w),recovery:{action:"await-user",reason:"workspace-mismatch",message:g},...await Nt(p.paths,w)});if(n){if(i||a||o||s||c||l||f||d!==void 0||h)throw new L("--runner-input cannot be combined with --summary, continuation expectations, or Agent transition flags");let k=await Hl({paths:p.paths,name:r});if(k.action==="rerun-final-verification")return je("next",{state:xe(k.state),...await Nt(p.paths,k.state)});let T=await Vl({paths:p.paths,name:r,preserveRunningExecution:!0}),F=T.state;if(T.action==="await-user"||T.action==="done"||T.reason!=="available")return je("next",{state:xe(F),recovery:ov(T),...await Nt(p.paths,F)});if(F.phase==="build"){let bt=await So({paths:p.paths,state:F});if(bt.drifted){let Kl=await Co({paths:p.paths,name:r,reason:bt.reason??"Native confirmed requirements changed"});return je("next",{state:xe(Kl),...await Nt(p.paths,Kl)})}let Jt=await W(p.paths,r),Ur=await nt({paths:p.paths,state:F});if(Ur&&!Ur.allDone&&!Jt)throw new L("Native parent Build advances child changes and does not accept a Builder handoff")}let ee=await Tm(n,t),j=await jm({paths:p.paths,name:r,input:ee,maxVerifyFailures:p.config.native.max_verify_failures});return je("next",{...nP(j),state:xe(j.state),...await Nt(p.paths,j.state),coordination:Z})}let y=await Hl({paths:p.paths,name:r});if(y.action==="rerun-final-verification")return je("next",{state:xe(y.state),...await Nt(p.paths,y.state)});let b=await Vl({paths:p.paths,name:r}),N=b.state;if(d!==void 0&&N.phase!=="shape")throw new L("--coordination-mode is only valid when confirming Shape");if(!i)throw new L("--summary is required");let E,P=null;if(a)if(N.phase==="shape"&&N.status==="await-user"&&N.loop.next_action==="confirm-shape"){if(!h)throw new L("--expected-state-version and --expected-action are required for Shape confirmation");E=await em({paths:p.paths,name:r,expectedContinuation:h})}else{if(N.phase==="shape")throw new L("--confirmed is only valid from the persisted Shape user confirmation boundary");if(N.phase==="verify"&&N.status==="await-user"&&N.loop.next_action==="confirm-verifier-unavailable")E=await dm({paths:p.paths,name:r,summary:i,expectedContinuation:h});else throw new L("--confirmed is only valid in Shape or for a user-accepted degraded verification fallback")}else if(o){if(!h&&(N.phase!=="verify"||N.status!=="await-user"||N.loop.next_action!=="confirm-skill-coordinated-pass"))throw new L("--accept-result is only valid for a pending Verify pass decision");E=await um({paths:p.paths,name:r,expectedContinuation:h})}else if(s){if(N.phase!=="verify")throw new L("--revise-implementation is only valid from Verify");E=await xo({paths:p.paths,name:r,reason:i,expectedContinuation:h})}else if(c){if(!h&&N.phase!=="verify"&&N.phase!=="archive")throw new L("--revise-requirements is only valid from Verify or Archive");E=await Co({paths:p.paths,name:r,reason:i,allowedPhases:["verify","archive"],expectedContinuation:h})}else if(l)E=await pm({paths:p.paths,name:r,expectedContinuation:h});else if(f)E=await fm({paths:p.paths,name:r,reason:i,expectedContinuation:h});else{if(b.reason!=="available")return je("next",{state:xe(N),recovery:ov(b),...await Nt(p.paths,N)});if(N.phase==="build"){let T=await So({paths:p.paths,state:N});if(T.drifted)E=await Co({paths:p.paths,name:r,reason:T.reason??"Native confirmed requirements changed"});else{let F=await nt({paths:p.paths,state:N});if(F){let ee=F,j=[],bt=await W(p.paths,r);if(bt&&!F.allDone){let Jt=await ph({paths:p.paths,parent:r,maxParallel:v});j=Jt.tasks,(j.length>0||Jt.state.stateVersion!==bt.stateVersion)&&(ee=await nt({paths:p.paths,state:N})??ee)}if(ee.allDone&&!(N.loop.stage==="repairing"&&N.verification_result==="fail"))P=await Eo({paths:p.paths,name:r,trigger:"recovery"}),E=P.state;else return je("next",{state:xe(N),childSummary:ee.children.reduce((Jt,Ur)=>({...Jt,[Ur.status]:(Jt[Ur.status]??0)+1}),{total:ee.children.length}),readyChildren:ee.readyChildren,...j.length>0?{supervisorTasks:j}:{},continuation:Q(N,ee)})}}}if(N.phase==="shape"&&(E=await Zh({paths:p.paths,name:r,...d===void 0?{}:{coordinationMode:d},expectedContinuation:h})),E)return je("next",{state:xe(E),...P?{parentAdvance:P.parentAdvance}:{},...await Nt(p.paths,E)});let k=N.phase==="shape"?await nt({paths:p.paths,state:N}):null;return{command:"next",exitCode:65,data:{state:xe(N),continuation:Q(N,k)},error:{code:"invalid-data",message:"This Native step requires the skill-coordinated --runner-input action returned by continuation; public JSON cannot supply identity, provider, execution ref, or candidate binding"}}}return je("next",{state:xe(E),...d===void 0?{}:{coordinationMode:d},...await Nt(p.paths,E)})}async function cv(e,t,r=process.argv.slice(2)){let i=r.indexOf("--"),n=i<0?[...r]:r.slice(0,i),a=i<0?[]:r.slice(i),o=n.includes("--json"),s=n.includes("--verbose"),c,l;try{st(n,"--json"),st(n,"--verbose"),c=yt(n,"--project-root");let u=[...n,...a],d=await tv(c);l=await t(u,d)}catch(u){l=nv(e,u)}let f=av(l,o,s);return f.stdout&&process.stdout.write(f.stdout),f.stderr&&process.stderr.write(f.stderr+(f.stderr.endsWith(`
259
+ `}:{exitCode:e.exitCode,stdout:e.text}}var iP=new Set(["prepare-shape-confirmation","confirm-shape","accept-result","confirm-verifier-unavailable","revise-implementation","revise-requirements","retry-verifier","resolve-verifier-blocker"]);function nP(e){let t=yt(e,"--expected-state-version"),r=yt(e,"--expected-action");if(!(t===void 0&&r===void 0)){if(t===void 0||r===void 0)throw new L("--expected-state-version and --expected-action must be provided together");if(!/^[1-9]\d*$/u.test(t)||!Number.isSafeInteger(Number(t)))throw new L("--expected-state-version must be a positive integer");if(!iP.has(r))throw new L("--expected-action is not a recognized Native continuation action");return{stateVersion:Number(t),action:r}}}async function Nt(e,t){let r=await nt({paths:e,state:t});return{...r?{childSummary:r.children.reduce((i,n)=>({...i,[n.status]:(i[n.status]??0)+1}),{total:r.children.length}),readyChildren:r.readyChildren}:{},continuation:Q(t,r)}}function aP(e){return Object.fromEntries(Object.entries(e).filter(([t])=>t!=="state"&&t!=="response"&&t!=="supervisorState"))}function cv(e){return{action:e.action,reason:e.reason,message:e.message}}async function lv(e,t){let r=rv(e,"change name"),i=yt(e,"--summary"),n=yt(e,"--runner-input"),a=st(e,"--confirmed"),o=st(e,"--accept-result"),s=st(e,"--revise-implementation"),c=st(e,"--revise-requirements"),l=st(e,"--retry-verifier"),f=st(e,"--resolve-verifier-blocker"),u=yt(e,"--coordination-mode"),d=u;if(u!==void 0&&!Ta.includes(u))throw new L("--coordination-mode must be multi-session or single-session");let m=yt(e,"--max-parallel"),v=m===void 0?2:Number(m);if(!Number.isSafeInteger(v)||v<1)throw new L("--max-parallel must be a positive integer");let h=nP(e);if([a,o,s,c,l,f].filter(Boolean).length>1)throw new L("--confirmed, --accept-result, --revise-implementation, --revise-requirements, --retry-verifier, and --resolve-verifier-blocker are mutually exclusive");if(d!==void 0&&(a||o||s||c||l||f||n!==void 0))throw new L("--coordination-mode is only valid when preparing a Supervisor Shape confirmation");tv(e);let p=await nv(t);if(!await sn(p.paths,r)){if(n)throw new L("--runner-input is only valid for portable Native changes");if(!i)throw new L("--summary is required");let k=await km({paths:p.paths,name:r});return je("next",{state:xe(k,p.paths),migration:{completed:!0,summary:i},continuation:Q(k)})}let w=await _(p.paths,r),g=Ll(p.paths,w);if(g)return je("next",{state:xe(w,p.paths),recovery:{action:"await-user",reason:"workspace-mismatch",message:g},...await Nt(p.paths,w)});if(n){if(i||a||o||s||c||l||f||d!==void 0||h)throw new L("--runner-input cannot be combined with --summary, continuation expectations, or Agent transition flags");let k=await Hl({paths:p.paths,name:r});if(k.action==="rerun-final-verification")return je("next",{state:xe(k.state,p.paths),...await Nt(p.paths,k.state)});let T=await Vl({paths:p.paths,name:r,preserveRunningExecution:!0}),F=T.state;if(T.action==="await-user"||T.action==="done"||T.reason!=="available")return je("next",{state:xe(F,p.paths),recovery:cv(T),...await Nt(p.paths,F)});if(F.phase==="build"){let bt=await So({paths:p.paths,state:F});if(bt.drifted){let Kl=await Co({paths:p.paths,name:r,reason:bt.reason??"Native confirmed requirements changed"});return je("next",{state:xe(Kl,p.paths),...await Nt(p.paths,Kl)})}let Jt=await W(p.paths,r),Ur=await nt({paths:p.paths,state:F});if(Ur&&!Ur.allDone&&!Jt)throw new L("Native parent Build advances child changes and does not accept a Builder handoff")}let ee=await $m(n,t),j=await Om({paths:p.paths,name:r,input:ee,maxVerifyFailures:p.config.native.max_verify_failures});return je("next",{...aP(j),state:xe(j.state,p.paths),...await Nt(p.paths,j.state),coordination:Z})}let y=await Hl({paths:p.paths,name:r});if(y.action==="rerun-final-verification")return je("next",{state:xe(y.state,p.paths),...await Nt(p.paths,y.state)});let b=await Vl({paths:p.paths,name:r}),N=b.state;if(d!==void 0&&N.phase!=="shape")throw new L("--coordination-mode is only valid when confirming Shape");if(!i)throw new L("--summary is required");let E,P=null;if(a)if(N.phase==="shape"&&N.status==="await-user"&&N.loop.next_action==="confirm-shape"){if(!h)throw new L("--expected-state-version and --expected-action are required for Shape confirmation");E=await em({paths:p.paths,name:r,expectedContinuation:h})}else{if(N.phase==="shape")throw new L("--confirmed is only valid from the persisted Shape user confirmation boundary");if(N.phase==="verify"&&N.status==="await-user"&&N.loop.next_action==="confirm-verifier-unavailable")E=await dm({paths:p.paths,name:r,summary:i,expectedContinuation:h});else throw new L("--confirmed is only valid in Shape or for a user-accepted degraded verification fallback")}else if(o){if(!h&&(N.phase!=="verify"||N.status!=="await-user"||N.loop.next_action!=="confirm-skill-coordinated-pass"))throw new L("--accept-result is only valid for a pending Verify pass decision");E=await um({paths:p.paths,name:r,expectedContinuation:h})}else if(s){if(N.phase!=="verify")throw new L("--revise-implementation is only valid from Verify");E=await xo({paths:p.paths,name:r,reason:i,expectedContinuation:h})}else if(c){if(!h&&N.phase!=="verify"&&N.phase!=="archive")throw new L("--revise-requirements is only valid from Verify or Archive");E=await Co({paths:p.paths,name:r,reason:i,allowedPhases:["verify","archive"],expectedContinuation:h})}else if(l)E=await pm({paths:p.paths,name:r,expectedContinuation:h});else if(f)E=await fm({paths:p.paths,name:r,reason:i,expectedContinuation:h});else{if(b.reason!=="available")return je("next",{state:xe(N,p.paths),recovery:cv(b),...await Nt(p.paths,N)});if(N.phase==="build"){let T=await So({paths:p.paths,state:N});if(T.drifted)E=await Co({paths:p.paths,name:r,reason:T.reason??"Native confirmed requirements changed"});else{let F=await nt({paths:p.paths,state:N});if(F){let ee=F,j=[],bt=await W(p.paths,r);if(bt&&!F.allDone){let Jt=await ph({paths:p.paths,parent:r,maxParallel:v});j=Jt.tasks,(j.length>0||Jt.state.stateVersion!==bt.stateVersion)&&(ee=await nt({paths:p.paths,state:N})??ee)}if(ee.allDone&&!(N.loop.stage==="repairing"&&N.verification_result==="fail"))P=await Eo({paths:p.paths,name:r,trigger:"recovery"}),E=P.state;else return je("next",{state:xe(N,p.paths),childSummary:ee.children.reduce((Jt,Ur)=>({...Jt,[Ur.status]:(Jt[Ur.status]??0)+1}),{total:ee.children.length}),readyChildren:ee.readyChildren,...j.length>0?{supervisorTasks:j}:{},continuation:Q(N,ee)})}}}if(N.phase==="shape"&&(E=await Zh({paths:p.paths,name:r,...d===void 0?{}:{coordinationMode:d},expectedContinuation:h})),E)return je("next",{state:xe(E,p.paths),...P?{parentAdvance:P.parentAdvance}:{},...await Nt(p.paths,E)});let k=N.phase==="shape"?await nt({paths:p.paths,state:N}):null;return{command:"next",exitCode:65,data:{state:xe(N,p.paths),continuation:Q(N,k)},error:{code:"invalid-data",message:"This Native step requires the skill-coordinated --runner-input action returned by continuation; public JSON cannot supply identity, provider, execution ref, or candidate binding"}}}return je("next",{state:xe(E,p.paths),...d===void 0?{}:{coordinationMode:d},...await Nt(p.paths,E)})}async function uv(e,t,r=process.argv.slice(2)){let i=r.indexOf("--"),n=i<0?[...r]:r.slice(0,i),a=i<0?[]:r.slice(i),o=n.includes("--json"),s=n.includes("--verbose"),c,l;try{st(n,"--json"),st(n,"--verbose"),c=yt(n,"--project-root");let u=[...n,...a],d=await iv(c);l=await t(u,d)}catch(u){l=ov(e,u)}let f=sv(l,o,s);return f.stdout&&process.stdout.write(f.stdout),f.stderr&&process.stderr.write(f.stderr+(f.stderr.endsWith(`
260
260
  `)?"":`
261
- `)),f.exitCode}process.exitCode=await cv("next",sv);
261
+ `)),f.exitCode}process.exitCode=await uv("next",lv);