@rpamis/comet 0.4.0-rc.3 → 0.4.0-rc.4
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.
- package/README.md +1 -0
- package/assets/manifest.json +1 -1
- package/assets/skills/comet/scripts/comet-archive.mjs +2 -2
- package/assets/skills/comet/scripts/comet-entry-runtime.mjs +56 -56
- package/assets/skills/comet/scripts/comet-guard.mjs +51 -51
- package/assets/skills/comet/scripts/comet-handoff.mjs +29 -29
- package/assets/skills/comet/scripts/comet-hook-guard.mjs +35 -35
- package/assets/skills/comet/scripts/comet-hook-router.mjs +140 -137
- package/assets/skills/comet/scripts/comet-resume-probe.mjs +34 -34
- package/assets/skills/comet/scripts/comet-runtime.mjs +69 -69
- package/assets/skills/comet/scripts/comet-state.mjs +38 -38
- package/assets/skills/comet/scripts/comet-yaml-validate.mjs +20 -20
- package/assets/skills/comet-native/SKILL.md +6 -7
- package/assets/skills/comet-native/reference/artifacts.md +1 -2
- package/assets/skills/comet-native/reference/clarification.md +6 -6
- package/assets/skills/comet-native/reference/commands.md +2 -0
- package/assets/skills/comet-native/scripts/comet-native-archive.mjs +127 -126
- package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +136 -135
- package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +61 -60
- package/assets/skills/comet-native/scripts/comet-native-init.mjs +30 -29
- package/assets/skills/comet-native/scripts/comet-native-new.mjs +125 -124
- package/assets/skills/comet-native/scripts/comet-native-next.mjs +123 -122
- package/assets/skills/comet-native/scripts/comet-native-root.mjs +16 -15
- package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +169 -168
- package/assets/skills/comet-native/scripts/comet-native-select.mjs +111 -110
- package/assets/skills/comet-native/scripts/comet-native-show.mjs +81 -80
- package/assets/skills/comet-native/scripts/comet-native-spec.mjs +118 -117
- package/assets/skills/comet-native/scripts/comet-native-status.mjs +108 -107
- package/assets/skills-zh/comet-native/SKILL.md +6 -7
- package/assets/skills-zh/comet-native/reference/artifacts.md +1 -2
- package/assets/skills-zh/comet-native/reference/clarification.md +6 -6
- package/assets/skills-zh/comet-native/reference/commands.md +2 -0
- package/dist/domains/comet-memory/personal-memory.d.ts.map +1 -1
- package/dist/domains/comet-memory/personal-memory.js +41 -0
- package/dist/domains/comet-memory/personal-memory.js.map +1 -1
- package/dist/domains/comet-memory/types.d.ts +7 -0
- package/dist/domains/comet-memory/types.d.ts.map +1 -1
- package/dist/domains/comet-native/native-archive-command.d.ts.map +1 -1
- package/dist/domains/comet-native/native-archive-command.js +114 -19
- package/dist/domains/comet-native/native-archive-command.js.map +1 -1
- package/dist/domains/comet-native/native-artifacts.d.ts +1 -0
- package/dist/domains/comet-native/native-artifacts.d.ts.map +1 -1
- package/dist/domains/comet-native/native-artifacts.js +53 -2
- package/dist/domains/comet-native/native-artifacts.js.map +1 -1
- package/dist/domains/comet-native/native-children.d.ts +1 -0
- package/dist/domains/comet-native/native-children.d.ts.map +1 -1
- package/dist/domains/comet-native/native-children.js +1 -0
- package/dist/domains/comet-native/native-children.js.map +1 -1
- package/dist/domains/comet-native/native-cli-help.js +6 -6
- package/dist/domains/comet-native/native-cli-help.js.map +1 -1
- package/dist/domains/comet-native/native-doctor-command.d.ts.map +1 -1
- package/dist/domains/comet-native/native-doctor-command.js +41 -1
- package/dist/domains/comet-native/native-doctor-command.js.map +1 -1
- package/dist/domains/comet-native/native-loop-runtime.d.ts +4 -0
- package/dist/domains/comet-native/native-loop-runtime.d.ts.map +1 -1
- package/dist/domains/comet-native/native-loop-runtime.js +29 -2
- package/dist/domains/comet-native/native-loop-runtime.js.map +1 -1
- package/dist/domains/comet-native/native-next-command.d.ts.map +1 -1
- package/dist/domains/comet-native/native-next-command.js +30 -6
- package/dist/domains/comet-native/native-next-command.js.map +1 -1
- package/dist/domains/comet-native/native-portable-continuation.d.ts +11 -4
- package/dist/domains/comet-native/native-portable-continuation.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-continuation.js +173 -15
- package/dist/domains/comet-native/native-portable-continuation.js.map +1 -1
- package/dist/domains/comet-native/native-portable-recovery.d.ts +1 -1
- package/dist/domains/comet-native/native-portable-recovery.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-recovery.js +26 -1
- package/dist/domains/comet-native/native-portable-recovery.js.map +1 -1
- package/dist/domains/comet-native/native-portable-runtime.d.ts +7 -1
- package/dist/domains/comet-native/native-portable-runtime.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-runtime.js +163 -11
- package/dist/domains/comet-native/native-portable-runtime.js.map +1 -1
- package/dist/domains/comet-native/native-portable-state.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-state.js +6 -0
- package/dist/domains/comet-native/native-portable-state.js.map +1 -1
- package/dist/domains/comet-native/native-portable-status.d.ts +5 -0
- package/dist/domains/comet-native/native-portable-status.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-status.js +21 -1
- package/dist/domains/comet-native/native-portable-status.js.map +1 -1
- package/dist/domains/comet-native/native-portable-types.d.ts +1 -0
- package/dist/domains/comet-native/native-portable-types.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-types.js.map +1 -1
- package/dist/domains/comet-native/native-runner-input.d.ts.map +1 -1
- package/dist/domains/comet-native/native-runner-input.js +12 -4
- package/dist/domains/comet-native/native-runner-input.js.map +1 -1
- package/dist/domains/comet-native/native-supervisor-overlay.d.ts +30 -0
- package/dist/domains/comet-native/native-supervisor-overlay.d.ts.map +1 -0
- package/dist/domains/comet-native/native-supervisor-overlay.js +202 -0
- package/dist/domains/comet-native/native-supervisor-overlay.js.map +1 -0
- package/dist/domains/comet-native/native-supervisor.d.ts.map +1 -1
- package/dist/domains/comet-native/native-supervisor.js +7 -3
- package/dist/domains/comet-native/native-supervisor.js.map +1 -1
- package/dist/domains/comet-native/native-types.d.ts +1 -0
- package/dist/domains/comet-native/native-types.d.ts.map +1 -1
- package/dist/domains/comet-native/native-workspace-finish.d.ts +12 -1
- package/dist/domains/comet-native/native-workspace-finish.d.ts.map +1 -1
- package/dist/domains/comet-native/native-workspace-finish.js +77 -22
- package/dist/domains/comet-native/native-workspace-finish.js.map +1 -1
- package/dist/domains/dashboard/web/assets/{abnfDiagram-VCTEODGH-UcCx24DV.js → abnfDiagram-VCTEODGH-Bql0JkFh.js} +1 -1
- package/dist/domains/dashboard/web/assets/{arc-n8qsRq7W.js → arc-CCUY9L8x.js} +1 -1
- package/dist/domains/dashboard/web/assets/architecture-7GRP2DOG-F2w5dggy.js +1 -0
- package/dist/domains/dashboard/web/assets/{architectureDiagram-5GKGNRK7-D4pJ8CU0.js → architectureDiagram-5GKGNRK7-iYP_D3CC.js} +1 -1
- package/dist/domains/dashboard/web/assets/{blockDiagram-I7D4REHJ-C7n-qrSQ.js → blockDiagram-I7D4REHJ-DyW07-ad.js} +1 -1
- package/dist/domains/dashboard/web/assets/{c4Diagram-7LVT6UL2-cMVrWYOm.js → c4Diagram-7LVT6UL2-DDD_Y9Gj.js} +1 -1
- package/dist/domains/dashboard/web/assets/channel-DLABCQMO.js +1 -0
- package/dist/domains/dashboard/web/assets/{chunk-4HAMMTFA-CE5QrCQd.js → chunk-4HAMMTFA-cZryt4d4.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-75Z2AOVW-BtZqN-pM.js → chunk-75Z2AOVW-Ciqzt_fM.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-DU6HZSFF-CChv0huc.js → chunk-DU6HZSFF-0EtIdyLT.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-F27PBJKO-CDT1ttJ8.js → chunk-F27PBJKO-B09yMHfO.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-GMAD6QVW-y5m6LMR7.js → chunk-GMAD6QVW-D_hJqXpD.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-GVQU2GXP-DkhKkaHd.js → chunk-GVQU2GXP-DIvLb3as.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-IMKFNOWR-BaDSh7Jp.js → chunk-IMKFNOWR-B_oII0H5.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-L3NEJ4N5-B4ztH2fV.js → chunk-L3NEJ4N5-BALKwnUb.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-OSK3NFVY-BhX6NVzA.js → chunk-OSK3NFVY-zA0G74ff.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-P2QGCYS3-BCNdGJkX.js → chunk-P2QGCYS3-B9FFBdWw.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-POPQ4Y6H-DwYVuiXw.js → chunk-POPQ4Y6H-Fwh05sRj.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-PWAF6VOD-Cyg0IO0R.js → chunk-PWAF6VOD-cCaczJjE.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-SHT3W25Y-BZ6skx8I.js → chunk-SHT3W25Y-ffjS5Q53.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-SVP7TREG-CLIGmSO0.js → chunk-SVP7TREG-IDmA7lw7.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-TICWLB2K-BAQBbsn9.js → chunk-TICWLB2K-8Gmmm4In.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-XXDRQBXY-D07UbEpV.js → chunk-XXDRQBXY-DS9V6N2-.js} +1 -1
- package/dist/domains/dashboard/web/assets/classDiagram-ZZMXUADV-DJ9Y8TBe.js +1 -0
- package/dist/domains/dashboard/web/assets/classDiagram-v2-VYDZK3BY-DJ9Y8TBe.js +1 -0
- package/dist/domains/dashboard/web/assets/{cose-bilkent-JH36ORCC-wIi0mUih.js → cose-bilkent-JH36ORCC-DTBreOtW.js} +1 -1
- package/dist/domains/dashboard/web/assets/{cynefin-OW5HDTMX-DBdxyuTN.js → cynefin-OW5HDTMX-DQuEyCa9.js} +1 -1
- package/dist/domains/dashboard/web/assets/{cynefinDiagram-5FMLGOSQ-DzO3jXxV.js → cynefinDiagram-5FMLGOSQ-Bb0YxnR5.js} +1 -1
- package/dist/domains/dashboard/web/assets/{dagre-GXQ25YYZ-CE7H_hZS.js → dagre-GXQ25YYZ-DCdqnZ1z.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-S7CK7UJ4-jUGQk5n-.js → diagram-S7CK7UJ4-CBO5Oebq.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-UQ7AKVKN-DaH_zW8T.js → diagram-UQ7AKVKN-Do5KGiae.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-VSXAHHWV-DmG80db0.js → diagram-VSXAHHWV-4Xskky28.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-VX7I27RA-ltQ6niKn.js → diagram-VX7I27RA-DHaxCMg1.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-Z3DM3KII-x92ex4lK.js → diagram-Z3DM3KII-_b0C8RCs.js} +1 -1
- package/dist/domains/dashboard/web/assets/{dist-Cf0h0n6i.js → dist-D_v6faRz.js} +1 -1
- package/dist/domains/dashboard/web/assets/{ebnfDiagram-PWID7BFC-CI2u976k.js → ebnfDiagram-PWID7BFC-BlWWQsBx.js} +1 -1
- package/dist/domains/dashboard/web/assets/{erDiagram-RLTQ6QDP-DKs90SRd.js → erDiagram-RLTQ6QDP-CaZks0yu.js} +1 -1
- package/dist/domains/dashboard/web/assets/{es-D7xGlyQk.js → es-DMM6Y5Bv.js} +1 -1
- package/dist/domains/dashboard/web/assets/eventmodeling-NTZA5JFV-LE_eXkBk.js +1 -0
- package/dist/domains/dashboard/web/assets/flowDiagram-HODETNUW-Dhg9N1uf.js +1 -0
- package/dist/domains/dashboard/web/assets/{ganttDiagram-EL5Y4UJY-D3z6G60S.js → ganttDiagram-EL5Y4UJY-BSjOQ_Cg.js} +1 -1
- package/dist/domains/dashboard/web/assets/{gitGraph-4MIJSDKK-vT1UnORT.js → gitGraph-4MIJSDKK-DYwq3-1L.js} +1 -1
- package/dist/domains/dashboard/web/assets/{gitGraphDiagram-WWUBYQGX-BJmJ96jv.js → gitGraphDiagram-WWUBYQGX-oVngpACZ.js} +1 -1
- package/dist/domains/dashboard/web/assets/{index-BG3MF8re.js → index-7epoYLF6.js} +31 -31
- package/dist/domains/dashboard/web/assets/index-C5iz4lns.css +1 -0
- package/dist/domains/dashboard/web/assets/{info-A6RAGUB7-DFeLqqen.js → info-A6RAGUB7-CLoje88f.js} +1 -1
- package/dist/domains/dashboard/web/assets/{infoDiagram-27XIBGKW-DxuY43XD.js → infoDiagram-27XIBGKW-sS6zp9EL.js} +1 -1
- package/dist/domains/dashboard/web/assets/{ishikawaDiagram-5VMMS53U-DxillfWQ.js → ishikawaDiagram-5VMMS53U-kETJqqgb.js} +1 -1
- package/dist/domains/dashboard/web/assets/{journeyDiagram-3NMN7TZE-BPngQ3ag.js → journeyDiagram-3NMN7TZE-ByJPB5Tw.js} +1 -1
- package/dist/domains/dashboard/web/assets/{kanban-definition-UXKFOSKX-DHMLEGD4.js → kanban-definition-UXKFOSKX-JKqPn1FZ.js} +1 -1
- package/dist/domains/dashboard/web/assets/{line-D31peBjo.js → line-CnHo6lWD.js} +1 -1
- package/dist/domains/dashboard/web/assets/{linear-B7X50T2m.js → linear-B2pLEjo4.js} +1 -1
- package/dist/domains/dashboard/web/assets/{mermaid-parser.core-CX3Pzygh.js → mermaid-parser.core-OtNk5rQN.js} +3 -3
- package/dist/domains/dashboard/web/assets/{mermaid.core-DlMjBFb6.js → mermaid.core-D1ElL3aM.js} +4 -4
- package/dist/domains/dashboard/web/assets/{mindmap-definition-YA3MSWOX-BKuSGF75.js → mindmap-definition-YA3MSWOX-BxJqN_qn.js} +1 -1
- package/dist/domains/dashboard/web/assets/{packet-AYTQ26CC-B1T8Bds9.js → packet-AYTQ26CC-DM9DL0wE.js} +1 -1
- package/dist/domains/dashboard/web/assets/{pegDiagram-XKGWAZYB-BYgTNxLw.js → pegDiagram-XKGWAZYB-BDe-x6aH.js} +1 -1
- package/dist/domains/dashboard/web/assets/{pie-WAS4IAKB-fqAjmoQw.js → pie-WAS4IAKB-ClmkkApZ.js} +1 -1
- package/dist/domains/dashboard/web/assets/{pieDiagram-E7YTZNPT-BAO0Ufky.js → pieDiagram-E7YTZNPT-DSFQ6yQn.js} +1 -1
- package/dist/domains/dashboard/web/assets/{quadrantDiagram-AXDQQJYC-SA_1-7DT.js → quadrantDiagram-AXDQQJYC-CV2lLCpu.js} +1 -1
- package/dist/domains/dashboard/web/assets/{radar-RG4KPBEZ-Bl_UfUle.js → radar-RG4KPBEZ-BduOvwgQ.js} +1 -1
- package/dist/domains/dashboard/web/assets/{railroad-74A4TZTK-yj6dkiSy.js → railroad-74A4TZTK-BYnUo_HE.js} +1 -1
- package/dist/domains/dashboard/web/assets/railroad-abnf-HS5TGJTU-CPiOAGi2.js +1 -0
- package/dist/domains/dashboard/web/assets/railroad-ebnf-LZEXJU2U-DOuNY-jw.js +1 -0
- package/dist/domains/dashboard/web/assets/railroad-peg-WCYAUIDC-DjNccNww.js +1 -0
- package/dist/domains/dashboard/web/assets/{railroadDiagram-O6MQD6OU-DqV18Y46.js → railroadDiagram-O6MQD6OU-Y0OnScVm.js} +1 -1
- package/dist/domains/dashboard/web/assets/{requirementDiagram-BXWQKSXE-Ca2K5LuT.js → requirementDiagram-BXWQKSXE-Dqs0b-_F.js} +1 -1
- package/dist/domains/dashboard/web/assets/{sankeyDiagram-P5KCCOFB-D9MKl-Nr.js → sankeyDiagram-P5KCCOFB-DafYyCgJ.js} +1 -1
- package/dist/domains/dashboard/web/assets/{sequenceDiagram-WJ2MYXX4-CXfvIzRx.js → sequenceDiagram-WJ2MYXX4-DEu4sb48.js} +1 -1
- package/dist/domains/dashboard/web/assets/{src-CquUPIQx.js → src-je_XM8Ul.js} +1 -1
- package/dist/domains/dashboard/web/assets/{stateDiagram-D77RDMKH-B7iaZHW7.js → stateDiagram-D77RDMKH-vHbZoYCK.js} +1 -1
- package/dist/domains/dashboard/web/assets/stateDiagram-v2-MP3YSRHH-C4dywNHK.js +1 -0
- package/dist/domains/dashboard/web/assets/{swimlanes-42K2YHIH-OK-62yZl.js → swimlanes-42K2YHIH-DxEqhoUX.js} +1 -1
- package/dist/domains/dashboard/web/assets/swimlanesDiagram-VR7AAH4N-CHhHUVep.js +8 -0
- package/dist/domains/dashboard/web/assets/{timeline-definition-24CTP7MA-D0l01B1h.js → timeline-definition-24CTP7MA-B4XpTytf.js} +1 -1
- package/dist/domains/dashboard/web/assets/{treeView-Q6P3EWNA-Bg5u_o3A.js → treeView-Q6P3EWNA-CrismRW3.js} +1 -1
- package/dist/domains/dashboard/web/assets/{treemap-WGGIJYW6-x89ccozk.js → treemap-WGGIJYW6-BGFmknIY.js} +1 -1
- package/dist/domains/dashboard/web/assets/{vennDiagram-4TSXK5OY-DV19Cqhv.js → vennDiagram-4TSXK5OY-DphMzj7N.js} +1 -1
- package/dist/domains/dashboard/web/assets/{wardley-WFR3VGLG-BWoeoVk5.js → wardley-WFR3VGLG-DmeLufag.js} +1 -1
- package/dist/domains/dashboard/web/assets/{wardleyDiagram-VM6X3IG4-D4fCpoIP.js → wardleyDiagram-VM6X3IG4-BUDxONKk.js} +1 -1
- package/dist/domains/dashboard/web/assets/{xychartDiagram-S5SC5T6Z-DALnOMLb.js → xychartDiagram-S5SC5T6Z-BjqVHkW2.js} +1 -1
- package/dist/domains/dashboard/web/index.html +2 -2
- package/dist/domains/project-knowledge/deterministic-extractors.d.ts.map +1 -1
- package/dist/domains/project-knowledge/deterministic-extractors.js +7 -6
- package/dist/domains/project-knowledge/deterministic-extractors.js.map +1 -1
- package/dist/domains/project-knowledge/index-store.d.ts +1 -1
- package/dist/domains/project-knowledge/index-store.d.ts.map +1 -1
- package/dist/domains/project-knowledge/index-store.js +19 -10
- package/dist/domains/project-knowledge/index-store.js.map +1 -1
- package/dist/domains/project-knowledge/learning.d.ts +1 -0
- package/dist/domains/project-knowledge/learning.d.ts.map +1 -1
- package/dist/domains/project-knowledge/learning.js +27 -8
- package/dist/domains/project-knowledge/learning.js.map +1 -1
- package/dist/domains/project-knowledge/local-provider.d.ts +1 -0
- package/dist/domains/project-knowledge/local-provider.d.ts.map +1 -1
- package/dist/domains/project-knowledge/local-provider.js +26 -1
- package/dist/domains/project-knowledge/local-provider.js.map +1 -1
- package/dist/domains/project-knowledge/local-store.d.ts +2 -1
- package/dist/domains/project-knowledge/local-store.d.ts.map +1 -1
- package/dist/domains/project-knowledge/local-store.js +82 -22
- package/dist/domains/project-knowledge/local-store.js.map +1 -1
- package/dist/domains/project-knowledge/plugin.d.ts.map +1 -1
- package/dist/domains/project-knowledge/plugin.js +55 -8
- package/dist/domains/project-knowledge/plugin.js.map +1 -1
- package/dist/domains/project-knowledge/records.d.ts +2 -0
- package/dist/domains/project-knowledge/records.d.ts.map +1 -1
- package/dist/domains/project-knowledge/records.js +8 -0
- package/dist/domains/project-knowledge/records.js.map +1 -1
- package/dist/domains/project-knowledge/types.d.ts +16 -0
- package/dist/domains/project-knowledge/types.d.ts.map +1 -1
- package/dist/domains/workflow-contract/protected-project-path.d.ts +4 -1
- package/dist/domains/workflow-contract/protected-project-path.d.ts.map +1 -1
- package/dist/domains/workflow-contract/protected-project-path.js +25 -1
- package/dist/domains/workflow-contract/protected-project-path.js.map +1 -1
- package/dist/platform/fs/race-safe-read.d.ts +14 -0
- package/dist/platform/fs/race-safe-read.d.ts.map +1 -1
- package/dist/platform/fs/race-safe-read.js +81 -0
- package/dist/platform/fs/race-safe-read.js.map +1 -1
- package/package.json +1 -1
- package/dist/domains/dashboard/web/assets/architecture-7GRP2DOG-B5p4GzJf.js +0 -1
- package/dist/domains/dashboard/web/assets/channel-BZeSeXVb.js +0 -1
- package/dist/domains/dashboard/web/assets/classDiagram-ZZMXUADV-2fcinal6.js +0 -1
- package/dist/domains/dashboard/web/assets/classDiagram-v2-VYDZK3BY-2fcinal6.js +0 -1
- package/dist/domains/dashboard/web/assets/eventmodeling-NTZA5JFV-uARcGZPD.js +0 -1
- package/dist/domains/dashboard/web/assets/flowDiagram-HODETNUW-DXL1E4Bl.js +0 -1
- package/dist/domains/dashboard/web/assets/index-C2Hlo7VZ.css +0 -1
- package/dist/domains/dashboard/web/assets/railroad-abnf-HS5TGJTU-CvouMciM.js +0 -1
- package/dist/domains/dashboard/web/assets/railroad-ebnf-LZEXJU2U-CkYQEX72.js +0 -1
- package/dist/domains/dashboard/web/assets/railroad-peg-WCYAUIDC-B0uYr48F.js +0 -1
- package/dist/domains/dashboard/web/assets/stateDiagram-v2-MP3YSRHH-B6KoHQVe.js +0 -1
- package/dist/domains/dashboard/web/assets/swimlanesDiagram-VR7AAH4N-CjdOls9K.js +0 -8
|
@@ -1,160 +1,160 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __cometCreateRequire } from 'module';
|
|
3
3
|
const require = __cometCreateRequire(import.meta.url);
|
|
4
|
-
var
|
|
5
|
-
`)}}
|
|
6
|
-
`)?
|
|
4
|
+
var nm=Object.create;var ll=Object.defineProperty;var am=Object.getOwnPropertyDescriptor;var om=Object.getOwnPropertyNames;var sm=Object.getPrototypeOf,cm=Object.prototype.hasOwnProperty;var Li=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var b=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var lm=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of om(t))!cm.call(e,n)&&n!==r&&ll(e,n,{get:()=>t[n],enumerable:!(i=am(t,n))||i.enumerable});return e};var Ar=(e,t,r)=>(r=e!=null?nm(sm(e)):{},lm(t||!e||!e.__esModule?ll(r,"default",{value:e,enumerable:!0}):r,e));var C=b(U=>{"use strict";var Za=Symbol.for("yaml.alias"),pl=Symbol.for("yaml.document"),Wi=Symbol.for("yaml.map"),ml=Symbol.for("yaml.pair"),eo=Symbol.for("yaml.scalar"),zi=Symbol.for("yaml.seq"),ze=Symbol.for("yaml.node.type"),Cm=e=>!!e&&typeof e=="object"&&e[ze]===Za,Am=e=>!!e&&typeof e=="object"&&e[ze]===pl,_m=e=>!!e&&typeof e=="object"&&e[ze]===Wi,Im=e=>!!e&&typeof e=="object"&&e[ze]===ml,vl=e=>!!e&&typeof e=="object"&&e[ze]===eo,Tm=e=>!!e&&typeof e=="object"&&e[ze]===zi;function gl(e){if(e&&typeof e=="object")switch(e[ze]){case Wi:case zi:return!0}return!1}function jm(e){if(e&&typeof e=="object")switch(e[ze]){case Za:case Wi:case eo:case zi:return!0}return!1}var $m=e=>(vl(e)||gl(e))&&!!e.anchor;U.ALIAS=Za;U.DOC=pl;U.MAP=Wi;U.NODE_TYPE=ze;U.PAIR=ml;U.SCALAR=eo;U.SEQ=zi;U.hasAnchor=$m;U.isAlias=Cm;U.isCollection=gl;U.isDocument=Am;U.isMap=_m;U.isNode=jm;U.isPair=Im;U.isScalar=vl;U.isSeq=Tm});var jr=b(to=>{"use strict";var q=C(),ae=Symbol("break visit"),wl=Symbol("skip children"),je=Symbol("remove node");function Ji(e,t){let r=yl(t);q.isDocument(e)?Yt(null,e.contents,r,Object.freeze([e]))===je&&(e.contents=null):Yt(null,e,r,Object.freeze([]))}Ji.BREAK=ae;Ji.SKIP=wl;Ji.REMOVE=je;function Yt(e,t,r,i){let n=Nl(e,t,r,i);if(q.isNode(n)||q.isPair(n))return bl(e,i,n),Yt(e,n,r,i);if(typeof n!="symbol"){if(q.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=Yt(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===ae)return ae;o===je&&(t.items.splice(a,1),a-=1)}}}else if(q.isPair(t)){i=Object.freeze(i.concat(t));let a=Yt("key",t.key,r,i);if(a===ae)return ae;a===je&&(t.key=null);let o=Yt("value",t.value,r,i);if(o===ae)return ae;o===je&&(t.value=null)}}return n}async function Gi(e,t){let r=yl(t);q.isDocument(e)?await Xt(null,e.contents,r,Object.freeze([e]))===je&&(e.contents=null):await Xt(null,e,r,Object.freeze([]))}Gi.BREAK=ae;Gi.SKIP=wl;Gi.REMOVE=je;async function Xt(e,t,r,i){let n=await Nl(e,t,r,i);if(q.isNode(n)||q.isPair(n))return bl(e,i,n),Xt(e,n,r,i);if(typeof n!="symbol"){if(q.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await Xt(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===ae)return ae;o===je&&(t.items.splice(a,1),a-=1)}}}else if(q.isPair(t)){i=Object.freeze(i.concat(t));let a=await Xt("key",t.key,r,i);if(a===ae)return ae;a===je&&(t.key=null);let o=await Xt("value",t.value,r,i);if(o===ae)return ae;o===je&&(t.value=null)}}return n}function yl(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 Nl(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(q.isMap(t))return r.Map?.(e,t,i);if(q.isSeq(t))return r.Seq?.(e,t,i);if(q.isPair(t))return r.Pair?.(e,t,i);if(q.isScalar(t))return r.Scalar?.(e,t,i);if(q.isAlias(t))return r.Alias?.(e,t,i)}function bl(e,t,r){let i=t[t.length-1];if(q.isCollection(i))i.items[e]=r;else if(q.isPair(i))e==="key"?i.key=r:i.value=r;else if(q.isDocument(i))i.contents=r;else{let n=q.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}to.visit=Ji;to.visitAsync=Gi});var ro=b(Sl=>{"use strict";var kl=C(),Om=jr(),Hm={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Dm=e=>e.replace(/[!,[\]{}]/g,t=>Hm[t]),$r=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+Dm(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&&kl.isNode(t.contents)){let a={};Om.visit(t.contents,(o,s)=>{kl.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
|
+
`)}};$r.defaultYaml={explicit:!1,version:"1.2"};$r.defaultTags={"!!":"tag:yaml.org,2002:"};Sl.Directives=$r});var Ui=b(Or=>{"use strict";var El=C(),Bm=jr();function Lm(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 Pl(e){let t=new Set;return Bm.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function xl(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function qm(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=Pl(e));let o=xl(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(El.isScalar(o.node)||El.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}}Or.anchorIsValid=Lm;Or.anchorNames=Pl;Or.createNodeAnchors=qm;Or.findNewAnchor=xl});var io=b(Rl=>{"use strict";function Hr(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=Hr(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=Hr(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=Hr(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=Hr(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}Rl.applyReviver=Hr});var st=b(Al=>{"use strict";var Fm=C();function Cl(e,t,r){if(Array.isArray(e))return e.map((i,n)=>Cl(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!Fm.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}Al.toJS=Cl});var Ki=b(Il=>{"use strict";var Vm=io(),_l=C(),Mm=st(),no=class{constructor(t){Object.defineProperty(this,_l.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(!_l.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=Mm.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?Vm.applyReviver(a,{"":s},"",s):s}};Il.NodeBase=no});var Dr=b(Tl=>{"use strict";var Wm=Ui(),zm=jr(),Qt=C(),Jm=Ki(),Gm=st(),ao=class extends Jm.NodeBase{constructor(t){super(Qt.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=[],zm.visit(t,{Node:(a,o)=>{(Qt.isAlias(o)||Qt.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||(Gm.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=Yi(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(Wm.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 Yi(e,t,r){if(Qt.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(Qt.isCollection(t)){let i=0;for(let n of t.items){let a=Yi(e,n,r);a>i&&(i=a)}return i}else if(Qt.isPair(t)){let i=Yi(e,t.key,r),n=Yi(e,t.value,r);return Math.max(i,n)}return 1}Tl.Alias=ao});var B=b(oo=>{"use strict";var Um=C(),Km=Ki(),Ym=st(),Xm=e=>!e||typeof e!="function"&&typeof e!="object",ct=class extends Km.NodeBase{constructor(t){super(Um.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:Ym.toJS(this.value,t,r)}toString(){return String(this.value)}};ct.BLOCK_FOLDED="BLOCK_FOLDED";ct.BLOCK_LITERAL="BLOCK_LITERAL";ct.PLAIN="PLAIN";ct.QUOTE_DOUBLE="QUOTE_DOUBLE";ct.QUOTE_SINGLE="QUOTE_SINGLE";oo.Scalar=ct;oo.isScalarValue=Xm});var Br=b($l=>{"use strict";var Qm=Dr(),xt=C(),jl=B(),Zm="tag:yaml.org,2002:";function ev(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 tv(e,t,r){if(xt.isDocument(e)&&(e=e.contents),xt.isNode(e))return e;if(xt.isPair(e)){let u=r.schema[xt.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 Qm.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=Zm+t.slice(2));let l=ev(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let u=new jl.Scalar(e);return c&&(c.node=u),u}l=e instanceof Map?o[xt.MAP]:Symbol.iterator in Object(e)?o[xt.SEQ]:o[xt.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 jl.Scalar(e);return t?f.tag=t:l.default||(f.tag=l.tag),c&&(c.node=f),f}$l.createNode=tv});var Qi=b(Xi=>{"use strict";var rv=Br(),$e=C(),iv=Ki();function so(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 rv.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 Ol=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,co=class extends iv.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=>$e.isNode(i)||$e.isPair(i)?i.clone(t):i),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(Ol(t))this.add(r);else{let[i,...n]=t,a=this.get(i,!0);if($e.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,so(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($e.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&&$e.isScalar(a)?a.value:a:$e.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!$e.isPair(r))return!1;let i=r.value;return i==null||t&&$e.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 $e.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($e.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,so(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};Xi.Collection=co;Xi.collectionFromPath=so;Xi.isEmptyPath=Ol});var Lr=b(Zi=>{"use strict";var nv=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function lo(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var av=(e,t,r)=>e.endsWith(`
|
|
6
|
+
`)?lo(r,t):r.includes(`
|
|
7
7
|
`)?`
|
|
8
|
-
`+
|
|
9
|
-
`)r===
|
|
10
|
-
`&&m!==" "){let
|
|
11
|
-
`&&
|
|
12
|
-
${t}${e.slice(0,
|
|
13
|
-
${t}${e.slice(
|
|
14
|
-
`);i=t,n=t+1,a=e[n]}return i}
|
|
15
|
-
`){if(a-o>i)return!0;if(o=a+1,n-o<=i)return!1}return!0}function
|
|
8
|
+
`+lo(r,t):(e.endsWith(" ")?"":" ")+r;Zi.indentComment=lo;Zi.lineComment=av;Zi.stringifyComment=nv});var Dl=b(qr=>{"use strict";var ov="flow",uo="block",en="quoted";function sv(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,y=-1;r===uo&&(h=Hl(e,h,t.length),h!==-1&&(u=h+c));for(let g;g=e[h+=1];){if(r===en&&g==="\\"){switch(p=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}y=h}if(g===`
|
|
9
|
+
`)r===uo&&(h=Hl(e,h,t.length)),u=h+t.length+c,d=void 0;else{if(g===" "&&m&&m!==" "&&m!==`
|
|
10
|
+
`&&m!==" "){let w=e[h+1];w&&w!==" "&&w!==`
|
|
11
|
+
`&&w!==" "&&(d=h)}if(h>=u)if(d)l.push(d),u=d+c,d=void 0;else if(r===en){for(;m===" "||m===" ";)m=g,g=e[h+=1],v=!0;let w=h>y+1?h-2:p-1;if(f[w])return e;l.push(w),f[w]=!0,u=w+c,d=void 0}else v=!0}m=g}if(v&&s&&s(),l.length===0)return e;o&&o();let N=e.slice(0,l[0]);for(let g=0;g<l.length;++g){let w=l[g],S=l[g+1]||e.length;w===0?N=`
|
|
12
|
+
${t}${e.slice(0,S)}`:(r===en&&f[w]&&(N+=`${e[w]}\\`),N+=`
|
|
13
|
+
${t}${e.slice(w+1,S)}`)}return N}function Hl(e,t,r){let i=t,n=t+1,a=e[n];for(;a===" "||a===" ";)if(t<n+r)a=e[++t];else{do a=e[++t];while(a&&a!==`
|
|
14
|
+
`);i=t,n=t+1,a=e[n]}return i}qr.FOLD_BLOCK=uo;qr.FOLD_FLOW=ov;qr.FOLD_QUOTED=en;qr.foldFlowLines=sv});var Vr=b(Bl=>{"use strict";var Ee=B(),lt=Dl(),rn=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),nn=e=>/^(%|---|\.\.\.)/m.test(e);function cv(e,t,r){if(!t||t<0)return!1;let i=t-r,n=e.length;if(n<=i)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
|
|
15
|
+
`){if(a-o>i)return!0;if(o=a+1,n-o<=i)return!1}return!0}function Fr(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:i}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(nn(e)?" ":""),o="",s=0;for(let c=0,l=r[c];l;l=r[++c])if(l===" "&&r[c+1]==="\\"&&r[c+2]==="n"&&(o+=r.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(r[c+1]){case"u":{o+=r.slice(s,c);let f=r.substr(c+2,4);switch(f){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:f.substr(0,2)==="00"?o+="\\x"+f.substr(2):o+=r.substr(c,6)}c+=5,s=c+1}break;case"n":if(i||r[c+2]==='"'||r.length<n)c+=1;else{for(o+=r.slice(s,c)+`
|
|
16
16
|
|
|
17
17
|
`;r[c+2]==="\\"&&r[c+3]==="n"&&r[c+4]!=='"';)o+=`
|
|
18
|
-
`,c+=2;o+=a,r[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+r.slice(s):r,i?o:
|
|
19
|
-
`)||/[ \t]\n|\n[ \t]/.test(e))return
|
|
20
|
-
${r}`)+"'";return t.implicitKey?i:
|
|
18
|
+
`,c+=2;o+=a,r[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+r.slice(s):r,i?o:lt.foldFlowLines(o,a,lt.FOLD_QUOTED,rn(t,!1))}function fo(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
19
|
+
`)||/[ \t]\n|\n[ \t]/.test(e))return Fr(e,t);let r=t.indent||(nn(e)?" ":""),i="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
20
|
+
${r}`)+"'";return t.implicitKey?i:lt.foldFlowLines(i,r,lt.FOLD_FLOW,rn(t,!1))}function Zt(e,t){let{singleQuote:r}=t.options,i;if(r===!1)i=Fr;else{let n=e.includes('"'),a=e.includes("'");n&&!a?i=fo:a&&!n?i=Fr:i=r?fo:Fr}return i(e,t)}var ho;try{ho=new RegExp(`(^|(?<!
|
|
21
21
|
))
|
|
22
22
|
+(?!
|
|
23
|
-
|$)`,"g")}catch{
|
|
23
|
+
|$)`,"g")}catch{ho=/\n+(?!\n|$)/g}function tn({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 Zt(r,i);let l=i.indent||(i.forceBlockIndent||nn(r)?" ":""),f=o==="literal"?!0:o==="folded"||t===Ee.Scalar.BLOCK_FOLDED?!1:t===Ee.Scalar.BLOCK_LITERAL?!0:!cv(r,c,l.length);if(!r)return f?`|
|
|
24
24
|
`:`>
|
|
25
|
-
`;let u,
|
|
26
|
-
`&&
|
|
25
|
+
`;let u,d;for(d=r.length;d>0;--d){let S=r[d-1];if(S!==`
|
|
26
|
+
`&&S!==" "&&S!==" ")break}let m=r.substring(d),v=m.indexOf(`
|
|
27
27
|
`);v===-1?u="-":r===m||v!==m.length-1?(u="+",a&&a()):u="",m&&(r=r.slice(0,-m.length),m[m.length-1]===`
|
|
28
|
-
`&&(m=m.slice(0,-1)),m=m.replace(
|
|
29
|
-
`)
|
|
30
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),E=!1,
|
|
31
|
-
${l}${
|
|
32
|
-
${l}${
|
|
33
|
-
`)||
|
|
34
|
-
`)?
|
|
35
|
-
`))return
|
|
36
|
-
${c}`);if(o){let
|
|
37
|
-
${t.indent}${s}`:s}
|
|
38
|
-
${s}:`):(p=`${p}:`,
|
|
39
|
-
`:"",
|
|
40
|
-
${
|
|
28
|
+
`&&(m=m.slice(0,-1)),m=m.replace(ho,`$&${l}`));let h=!1,p,y=-1;for(p=0;p<r.length;++p){let S=r[p];if(S===" ")h=!0;else if(S===`
|
|
29
|
+
`)y=p;else break}let N=r.substring(0,y<p?y+1:p);N&&(r=r.substring(N.length),N=N.replace(/\n+/g,`$&${l}`));let w=(h?l?"2":"1":"")+u;if(e&&(w+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!f){let S=r.replace(/\n+/g,`
|
|
30
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),E=!1,P=rn(i,!0);o!=="folded"&&t!==Ee.Scalar.BLOCK_FOLDED&&(P.onOverflow=()=>{E=!0});let k=lt.foldFlowLines(`${N}${S}${m}`,l,lt.FOLD_BLOCK,P);if(!E)return`>${w}
|
|
31
|
+
${l}${k}`}return r=r.replace(/\n+/g,`$&${l}`),`|${w}
|
|
32
|
+
${l}${N}${r}${m}`}function lv(e,t,r,i){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:f}=t;if(s&&a.includes(`
|
|
33
|
+
`)||f&&/[[\]{},]/.test(a))return Zt(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||f||!a.includes(`
|
|
34
|
+
`)?Zt(a,t):tn(e,t,r,i);if(!s&&!f&&n!==Ee.Scalar.PLAIN&&a.includes(`
|
|
35
|
+
`))return tn(e,t,r,i);if(nn(a)){if(c==="")return t.forceBlockIndent=!0,tn(e,t,r,i);if(s&&c===l)return Zt(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 Zt(a,t)}return s?u:lt.foldFlowLines(u,c,lt.FOLD_FLOW,rn(t,!1))}function uv(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!==Ee.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=Ee.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case Ee.Scalar.BLOCK_FOLDED:case Ee.Scalar.BLOCK_LITERAL:return n||a?Zt(o.value,t):tn(o,t,r,i);case Ee.Scalar.QUOTE_DOUBLE:return Fr(o.value,t);case Ee.Scalar.QUOTE_SINGLE:return fo(o.value,t);case Ee.Scalar.PLAIN:return lv(o,t,r,i);default:return null}},l=c(s);if(l===null){let{defaultKeyType:f,defaultStringType:u}=t.options,d=n&&f||u;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}Bl.stringifyString=uv});var Mr=b(po=>{"use strict";var dv=Ui(),ut=C(),fv=Lr(),hv=Vr();function pv(e,t){let r=Object.assign({blockQuote:!0,commentString:fv.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),i;switch(r.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:e,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:i,options:r}}function mv(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(ut.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 vv(e,t,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=(ut.isScalar(e)||ut.isCollection(e))&&e.anchor;a&&dv.anchorIsValid(a)&&(r.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(i.directives.tagString(o)),n.join(" ")}function gv(e,t,r,i){if(ut.isPair(e))return e.toString(t,r,i);if(ut.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=ut.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=mv(t.doc.schema.tags,a));let o=vv(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):ut.isScalar(a)?hv.stringifyString(a,t,r,i):a.toString(t,r,i);return o?ut.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
|
|
37
|
+
${t.indent}${s}`:s}po.createStringifyContext=pv;po.stringify=gv});var Vl=b(Fl=>{"use strict";var Je=C(),Ll=B(),ql=Mr(),Wr=Lr();function wv({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=Je.isNode(e)&&e.comment||null;if(u){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(Je.isCollection(e)||!Je.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||Je.isCollection(e)||(Je.isScalar(e)?e.type===Ll.Scalar.BLOCK_FOLDED||e.type===Ll.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=ql.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+=Wr.lineComment(p,r.indent,l(d)):h&&n&&n(),p;v&&(d=null),m?(d&&(p+=Wr.lineComment(p,r.indent,l(d))),p=`? ${p}
|
|
38
|
+
${s}:`):(p=`${p}:`,d&&(p+=Wr.lineComment(p,r.indent,l(d))));let y,N,g;Je.isNode(t)?(y=!!t.spaceBefore,N=t.commentBefore,g=t.comment):(y=!1,N=null,g=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!m&&!d&&Je.isScalar(t)&&(r.indentAtStart=p.length+1),h=!1,!f&&c.length>=2&&!r.inFlow&&!m&&Je.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let w=!1,S=ql.stringify(t,r,()=>w=!0,()=>h=!0),E=" ";if(d||y||N){if(E=y?`
|
|
39
|
+
`:"",N){let P=l(N);E+=`
|
|
40
|
+
${Wr.indentComment(P,r.indent)}`}S===""&&!r.inFlow?E===`
|
|
41
41
|
`&&g&&(E=`
|
|
42
42
|
|
|
43
43
|
`):E+=`
|
|
44
|
-
${r.indent}`}else if(!m&&
|
|
45
|
-
`)
|
|
46
|
-
${r.indent}`)}}else(
|
|
47
|
-
`)&&(E="");return p+=E+
|
|
44
|
+
${r.indent}`}else if(!m&&Je.isCollection(t)){let P=S[0],k=S.indexOf(`
|
|
45
|
+
`),T=k!==-1,Z=r.inFlow??t.flow??t.items.length===0;if(T||!Z){let pe=!1;if(T&&(P==="&"||P==="!")){let A=S.indexOf(" ");P==="&"&&A!==-1&&A<k&&S[A+1]==="!"&&(A=S.indexOf(" ",A+1)),(A===-1||k<A)&&(pe=!0)}pe||(E=`
|
|
46
|
+
${r.indent}`)}}else(S===""||S[0]===`
|
|
47
|
+
`)&&(E="");return p+=E+S,r.inFlow?w&&i&&i():g&&!w?p+=Wr.lineComment(p,r.indent,l(g)):h&&n&&n(),p}Fl.stringifyPair=wv});var vo=b(mo=>{"use strict";var Ml=Li("process");function yv(e,...t){e==="debug"&&console.log(...t)}function Nv(e,t){(e==="debug"||e==="warn")&&(typeof Ml.emitWarning=="function"?Ml.emitWarning(t):console.warn(t))}mo.debug=yv;mo.warn=Nv});var ln=b(cn=>{"use strict";var sn=C(),Wl=B(),an="<<",on={identify:e=>e===an||typeof e=="symbol"&&e.description===an,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Wl.Scalar(Symbol(an)),{addToJSMap:zl}),stringify:()=>an},bv=(e,t)=>(on.identify(t)||sn.isScalar(t)&&(!t.type||t.type===Wl.Scalar.PLAIN)&&on.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===on.tag&&r.default);function zl(e,t,r){let i=Jl(e,r);if(sn.isSeq(i))for(let n of i.items)go(e,t,n);else if(Array.isArray(i))for(let n of i)go(e,t,n);else go(e,t,i)}function go(e,t,r){let i=Jl(e,r);if(!sn.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 Jl(e,t){return e&&sn.isAlias(t)?t.resolve(e.doc,e):t}cn.addMergeToJSMap=zl;cn.isMergeKey=bv;cn.merge=on});var yo=b(Kl=>{"use strict";var kv=vo(),Gl=ln(),Sv=Mr(),Ul=C(),wo=st();function Ev(e,t,{key:r,value:i}){if(Ul.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,i);else if(Gl.isMergeKey(e,r))Gl.addMergeToJSMap(e,t,i);else{let n=wo.toJS(r,"",e);if(t instanceof Map)t.set(n,wo.toJS(i,n,e));else if(t instanceof Set)t.add(n);else{let a=Pv(r,n,e),o=wo.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 Pv(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(Ul.isNode(e)&&r?.doc){let i=Sv.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)+'..."'),kv.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)}Kl.addPairToJSMap=Ev});var dt=b(No=>{"use strict";var Yl=Br(),xv=Vl(),Rv=yo(),un=C();function Cv(e,t,r){let i=Yl.createNode(e,void 0,r),n=Yl.createNode(t,void 0,r);return new dn(i,n)}var dn=class e{constructor(t,r=null){Object.defineProperty(this,un.NODE_TYPE,{value:un.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:i}=this;return un.isNode(r)&&(r=r.clone(t)),un.isNode(i)&&(i=i.clone(t)),new e(r,i)}toJSON(t,r){let i=r?.mapAsMap?new Map:{};return Rv.addPairToJSMap(r,i,this)}toString(t,r,i){return t?.doc?xv.stringifyPair(this,t,r,i):JSON.stringify(this)}};No.Pair=dn;No.createPair=Cv});var bo=b(Ql=>{"use strict";var Rt=C(),Xl=Mr(),fn=Lr();function Av(e,t,r){return(t.inFlow??e.flow?Iv:_v)(e,t,r)}function _v({comment:e,items:t},r,{blockItemPrefix:i,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=r,f=Object.assign({},r,{indent:a,type:null}),u=!1,d=[];for(let v=0;v<t.length;++v){let h=t[v],p=null;if(Rt.isNode(h))!u&&h.spaceBefore&&d.push(""),hn(r,d,h.commentBefore,u),h.comment&&(p=h.comment);else if(Rt.isPair(h)){let N=Rt.isNode(h.key)?h.key:null;N&&(!u&&N.spaceBefore&&d.push(""),hn(r,d,N.commentBefore,u))}u=!1;let y=Xl.stringify(h,f,()=>p=null,()=>u=!0);p&&(y+=fn.lineComment(y,a,l(p))),u&&p&&(u=!1),d.push(i+y)}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
|
-
`+
|
|
51
|
-
`)),v<e.length-1?
|
|
50
|
+
`+fn.indentComment(l(e),c),s&&s()):u&&o&&o(),m}function Iv({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(Rt.isNode(h))h.spaceBefore&&u.push(""),hn(t,u,h.commentBefore,!1),h.comment&&(p=h.comment);else if(Rt.isPair(h)){let N=Rt.isNode(h.key)?h.key:null;N&&(N.spaceBefore&&u.push(""),hn(t,u,N.commentBefore,!1),N.comment&&(l=!0));let g=Rt.isNode(h.value)?h.value:null;g?(g.comment&&(p=g.comment),g.commentBefore&&(l=!0)):h.value==null&&N?.comment&&(p=N.comment)}p&&(l=!0);let y=Xl.stringify(h,c,()=>p=null);l||(l=u.length>f||y.includes(`
|
|
51
|
+
`)),v<e.length-1?y+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=u.reduce((N,g)=>N+g.length+2,2)+(y.length+2)>t.options.lineWidth)),l&&(y+=",")),p&&(y+=fn.lineComment(y,i,s(p))),u.push(y),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`${
|
|
55
|
-
`:" ")}return
|
|
54
|
+
${n}${m}`}else return`${d}${o}${u.join(" ")}${o}${m}`}function hn({indent:e,options:{commentString:t}},r,i,n){if(i&&n&&(i=i.replace(/^\n+/,"")),i){let a=fn.indentComment(t(i),e);r.push(a.trimStart())}}Ql.stringifyCollection=Av});var ht=b(So=>{"use strict";var Tv=bo(),jv=yo(),$v=Qi(),ft=C(),pn=dt(),Ov=B();function zr(e,t){let r=ft.isScalar(t)?t.value:t;for(let i of e)if(ft.isPair(i)&&(i.key===t||i.key===r||ft.isScalar(i.key)&&i.key.value===r))return i}var ko=class extends $v.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(ft.MAP,t),this.items=[]}static from(t,r,i){let{keepUndefined:n,replacer:a}=i,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(r,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||n)&&o.items.push(pn.createPair(c,l,i))};if(r instanceof Map)for(let[c,l]of r)s(c,l);else if(r&&typeof r=="object")for(let c of Object.keys(r))s(c,r[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,r){let i;ft.isPair(t)?i=t:!t||typeof t!="object"||!("key"in t)?i=new pn.Pair(t,t?.value):i=new pn.Pair(t.key,t.value);let n=zr(this.items,i.key),a=this.schema?.sortMapEntries;if(n){if(!r)throw new Error(`Key ${i.key} already set`);ft.isScalar(n.value)&&Ov.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=zr(this.items,t);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(t,r){let n=zr(this.items,t)?.value;return(!r&&ft.isScalar(n)?n.value:n)??void 0}has(t){return!!zr(this.items,t)}set(t,r){this.add(new pn.Pair(t,r),!0)}toJSON(t,r,i){let n=i?new i:r?.mapAsMap?new Map:{};r?.onCreate&&r.onCreate(n);for(let a of this.items)jv.addPairToJSMap(r,n,a);return n}toString(t,r,i){if(!t)return JSON.stringify(this);for(let n of this.items)if(!ft.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})),Tv.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:i,onComment:r})}};So.YAMLMap=ko;So.findPair=zr});var er=b(eu=>{"use strict";var Hv=C(),Zl=ht(),Dv={collection:"map",default:!0,nodeClass:Zl.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return Hv.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>Zl.YAMLMap.from(e,t,r)};eu.map=Dv});var pt=b(tu=>{"use strict";var Bv=Br(),Lv=bo(),qv=Qi(),vn=C(),Fv=B(),Vv=st(),Eo=class extends qv.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(vn.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let r=mn(t);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(t,r){let i=mn(t);if(typeof i!="number")return;let n=this.items[i];return!r&&vn.isScalar(n)?n.value:n}has(t){let r=mn(t);return typeof r=="number"&&r<this.items.length}set(t,r){let i=mn(t);if(typeof i!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[i];vn.isScalar(n)&&Fv.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(Vv.toJS(a,String(n++),r));return i}toString(t,r,i){return t?Lv.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(Bv.createNode(s,void 0,i))}}return a}};function mn(e){let t=vn.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}tu.YAMLSeq=Eo});var tr=b(iu=>{"use strict";var Mv=C(),ru=pt(),Wv={collection:"seq",default:!0,nodeClass:ru.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return Mv.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>ru.YAMLSeq.from(e,t,r)};iu.seq=Wv});var Jr=b(nu=>{"use strict";var zv=Vr(),Jv={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),zv.stringifyString(e,t,r,i)}};nu.string=Jv});var gn=b(su=>{"use strict";var au=B(),ou={identify:e=>e==null,createNode:()=>new au.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new au.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&ou.test.test(e)?e:t.options.nullStr};su.nullTag=ou});var Po=b(lu=>{"use strict";var Gv=B(),cu={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new Gv.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&cu.test.test(e)){let i=e[0]==="t"||e[0]==="T";if(t===i)return e}return t?r.options.trueStr:r.options.falseStr}};lu.boolTag=cu});var rr=b(uu=>{"use strict";function Uv({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}uu.stringifyNumber=Uv});var Ro=b(wn=>{"use strict";var Kv=B(),xo=rr(),Yv={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:xo.stringifyNumber},Xv={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():xo.stringifyNumber(e)}},Qv={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 Kv.Scalar(parseFloat(e)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:xo.stringifyNumber};wn.float=Qv;wn.floatExp=Xv;wn.floatNaN=Yv});var Ao=b(Nn=>{"use strict";var du=rr(),yn=e=>typeof e=="bigint"||Number.isInteger(e),Co=(e,t,r,{intAsBigInt:i})=>i?BigInt(e):parseInt(e.substring(t),r);function fu(e,t,r){let{value:i}=e;return yn(i)&&i>=0?r+i.toString(t):du.stringifyNumber(e)}var Zv={identify:e=>yn(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>Co(e,2,8,r),stringify:e=>fu(e,8,"0o")},eg={identify:yn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>Co(e,0,10,r),stringify:du.stringifyNumber},tg={identify:e=>yn(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>Co(e,2,16,r),stringify:e=>fu(e,16,"0x")};Nn.int=eg;Nn.intHex=tg;Nn.intOct=Zv});var pu=b(hu=>{"use strict";var rg=er(),ig=gn(),ng=tr(),ag=Jr(),og=Po(),_o=Ro(),Io=Ao(),sg=[rg.map,ng.seq,ag.string,ig.nullTag,og.boolTag,Io.intOct,Io.int,Io.intHex,_o.floatNaN,_o.floatExp,_o.float];hu.schema=sg});var gu=b(vu=>{"use strict";var cg=B(),lg=er(),ug=tr();function mu(e){return typeof e=="bigint"||Number.isInteger(e)}var bn=({value:e})=>JSON.stringify(e),dg=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:bn},{identify:e=>e==null,createNode:()=>new cg.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:bn},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:bn},{identify:mu,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})=>mu(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:bn}],fg={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},hg=[lg.map,ug.seq].concat(dg,fg);vu.schema=hg});var jo=b(wu=>{"use strict";var Gr=Li("buffer"),To=B(),pg=Vr(),mg={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Gr.Buffer=="function")return Gr.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 Gr.Buffer=="function")s=o instanceof Gr.Buffer?o.toString("base64"):Gr.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=To.Scalar.BLOCK_LITERAL),t!==To.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===To.Scalar.BLOCK_LITERAL?`
|
|
55
|
+
`:" ")}return pg.stringifyString({comment:e,type:t,value:s},i,n,a)}};wu.binary=mg});var En=b(Sn=>{"use strict";var kn=C(),$o=dt(),vg=B(),gg=pt();function yu(e,t){if(kn.isSeq(e))for(let r=0;r<e.items.length;++r){let i=e.items[r];if(!kn.isPair(i)){if(kn.isMap(i)){i.items.length>1&&t("Each pair must have its own sequence indicator");let n=i.items[0]||new $o.Pair(new vg.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]=wn.isPair(i)?i:new xo.Pair(i)}}else t("Expected a sequence for this tag");return e}function hu(e,t,r){let{replacer:i}=r,n=new ag.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof i=="function"&&(o=i.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(xo.createPair(s,c,r))}return n}var og={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:fu,createNode:hu};yn.createPairs=hu;yn.pairs=og;yn.resolvePairs=fu});var Ao=b(Ro=>{"use strict";var pu=C(),Co=it(),Vr=lt(),sg=ut(),mu=Nn(),Pt=class e extends sg.YAMLSeq{constructor(){super(),this.add=Vr.YAMLMap.prototype.add.bind(this),this.delete=Vr.YAMLMap.prototype.delete.bind(this),this.get=Vr.YAMLMap.prototype.get.bind(this),this.has=Vr.YAMLMap.prototype.has.bind(this),this.set=Vr.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(pu.isPair(n)?(a=Co.toJS(n.key,"",r),o=Co.toJS(n.value,a,r)):a=Co.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=mu.createPairs(t,r,i),a=new this;return a.items=n.items,a}};Pt.tag="tag:yaml.org,2002:omap";var cg={collection:"seq",identify:e=>e instanceof Map,nodeClass:Pt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=mu.resolvePairs(e,t),i=[];for(let{key:n}of r.items)pu.isScalar(n)&&(i.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new Pt,r)},createNode:(e,t,r)=>Pt.from(e,t,r)};Ro.YAMLOMap=Pt;Ro.omap=cg});var Nu=b(_o=>{"use strict";var vu=B();function gu({value:e,source:t},r){return t&&(e?wu:yu).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var wu={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 vu.Scalar(!0),stringify:gu},yu={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 vu.Scalar(!1),stringify:gu};_o.falseTag=yu;_o.trueTag=wu});var bu=b(bn=>{"use strict";var lg=B(),Io=Zt(),ug={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:Io.stringifyNumber},dg={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():Io.stringifyNumber(e)}},fg={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 lg.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:Io.stringifyNumber};bn.float=fg;bn.floatExp=dg;bn.floatNaN=ug});var Su=b(Wr=>{"use strict";var ku=Zt(),Mr=e=>typeof e=="bigint"||Number.isInteger(e);function kn(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 To(e,t,r){let{value:i}=e;if(Mr(i)){let n=i.toString(t);return i<0?"-"+r+n.substr(1):r+n}return ku.stringifyNumber(e)}var hg={identify:Mr,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>kn(e,2,2,r),stringify:e=>To(e,2,"0b")},pg={identify:Mr,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>kn(e,1,8,r),stringify:e=>To(e,8,"0")},mg={identify:Mr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>kn(e,0,10,r),stringify:ku.stringifyNumber},vg={identify:Mr,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>kn(e,2,16,r),stringify:e=>To(e,16,"0x")};Wr.int=mg;Wr.intBin=hg;Wr.intHex=vg;Wr.intOct=pg});var $o=b(jo=>{"use strict";var Pn=C(),Sn=st(),En=lt(),xt=class e extends En.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;Pn.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new Sn.Pair(t.key,null):r=new Sn.Pair(t,null),En.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let i=En.findPair(this.items,t);return!r&&Pn.isPair(i)?Pn.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=En.findPair(this.items,t);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new Sn.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(Sn.createPair(o,null,i));return a}};xt.tag="tag:yaml.org,2002:set";var gg={collection:"map",identify:e=>e instanceof Set,nodeClass:xt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>xt.from(e,t,r),resolve(e,t){if(Pn.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new xt,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};jo.YAMLSet=xt;jo.set=gg});var Ho=b(xn=>{"use strict";var wg=Zt();function Oo(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 Eu(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return wg.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 yg={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})=>Oo(e,r),stringify:Eu},Ng={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=>Oo(e,!1),stringify:Eu},Pu={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(Pu.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),d=t[8];if(d&&d!=="Z"){let u=Oo(d,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};xn.floatTime=Ng;xn.intTime=yg;xn.timestamp=Pu});var Ru=b(Cu=>{"use strict";var bg=Xt(),kg=hn(),Sg=Qt(),Eg=qr(),Pg=Po(),xu=Nu(),Do=bu(),Cn=Su(),xg=an(),Cg=Ao(),Rg=Nn(),Ag=$o(),Bo=Ho(),_g=[bg.map,Sg.seq,Eg.string,kg.nullTag,xu.trueTag,xu.falseTag,Cn.intBin,Cn.intOct,Cn.int,Cn.intHex,Do.floatNaN,Do.floatExp,Do.float,Pg.binary,xg.merge,Cg.omap,Rg.pairs,Ag.set,Bo.intTime,Bo.floatTime,Bo.timestamp];Cu.schema=_g});var Bu=b(Fo=>{"use strict";var Tu=Xt(),Ig=hn(),ju=Qt(),Tg=qr(),jg=go(),Lo=yo(),qo=bo(),$g=su(),Og=uu(),$u=Po(),zr=an(),Ou=Ao(),Hu=Nn(),Au=Ru(),Du=$o(),Rn=Ho(),_u=new Map([["core",$g.schema],["failsafe",[Tu.map,ju.seq,Tg.string]],["json",Og.schema],["yaml11",Au.schema],["yaml-1.1",Au.schema]]),Iu={binary:$u.binary,bool:jg.boolTag,float:Lo.float,floatExp:Lo.floatExp,floatNaN:Lo.floatNaN,floatTime:Rn.floatTime,int:qo.int,intHex:qo.intHex,intOct:qo.intOct,intTime:Rn.intTime,map:Tu.map,merge:zr.merge,null:Ig.nullTag,omap:Ou.omap,pairs:Hu.pairs,seq:ju.seq,set:Du.set,timestamp:Rn.timestamp},Hg={"tag:yaml.org,2002:binary":$u.binary,"tag:yaml.org,2002:merge":zr.merge,"tag:yaml.org,2002:omap":Ou.omap,"tag:yaml.org,2002:pairs":Hu.pairs,"tag:yaml.org,2002:set":Du.set,"tag:yaml.org,2002:timestamp":Rn.timestamp};function Dg(e,t,r){let i=_u.get(t);if(i&&!e)return r&&!i.includes(zr.merge)?i.concat(zr.merge):i.slice();let n=i;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(_u.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(zr.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Iu[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Iu).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}Fo.coreKnownTags=Hg;Fo.getTags=Dg});var Wo=b(Lu=>{"use strict";var Vo=C(),Bg=Xt(),Lg=Qt(),qg=qr(),An=Bu(),Fg=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Mo=class e{constructor({compat:t,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?An.getTags(t,"compat"):t?An.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?An.coreKnownTags:{},this.tags=An.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,Vo.MAP,{value:Bg.map}),Object.defineProperty(this,Vo.SCALAR,{value:qg.string}),Object.defineProperty(this,Vo.SEQ,{value:Lg.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Fg:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Lu.Schema=Mo});var Fu=b(qu=>{"use strict";var Vg=C(),zo=Dr(),Jr=jr();function Mg(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=zo.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=a(e.commentBefore);r.unshift(Jr.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(Vg.isNode(e.contents)){if(e.contents.spaceBefore&&i&&r.push(""),e.contents.commentBefore){let d=a(e.contents.commentBefore);r.push(Jr.indentComment(d,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=zo.stringify(e.contents,n,()=>s=null,c);s&&(l+=Jr.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(zo.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
|
|
58
|
-
`)?(r.push("..."),r.push(
|
|
57
|
+
${a.comment}`:i.comment}i=n}e.items[r]=kn.isPair(i)?i:new $o.Pair(i)}}else t("Expected a sequence for this tag");return e}function Nu(e,t,r){let{replacer:i}=r,n=new gg.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof i=="function"&&(o=i.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push($o.createPair(s,c,r))}return n}var wg={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:yu,createNode:Nu};Sn.createPairs=Nu;Sn.pairs=wg;Sn.resolvePairs=yu});var Do=b(Ho=>{"use strict";var bu=C(),Oo=st(),Ur=ht(),yg=pt(),ku=En(),Ct=class e extends yg.YAMLSeq{constructor(){super(),this.add=Ur.YAMLMap.prototype.add.bind(this),this.delete=Ur.YAMLMap.prototype.delete.bind(this),this.get=Ur.YAMLMap.prototype.get.bind(this),this.has=Ur.YAMLMap.prototype.has.bind(this),this.set=Ur.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(bu.isPair(n)?(a=Oo.toJS(n.key,"",r),o=Oo.toJS(n.value,a,r)):a=Oo.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=ku.createPairs(t,r,i),a=new this;return a.items=n.items,a}};Ct.tag="tag:yaml.org,2002:omap";var Ng={collection:"seq",identify:e=>e instanceof Map,nodeClass:Ct,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=ku.resolvePairs(e,t),i=[];for(let{key:n}of r.items)bu.isScalar(n)&&(i.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new Ct,r)},createNode:(e,t,r)=>Ct.from(e,t,r)};Ho.YAMLOMap=Ct;Ho.omap=Ng});var Ru=b(Bo=>{"use strict";var Su=B();function Eu({value:e,source:t},r){return t&&(e?Pu:xu).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var Pu={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 Su.Scalar(!0),stringify:Eu},xu={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 Su.Scalar(!1),stringify:Eu};Bo.falseTag=xu;Bo.trueTag=Pu});var Cu=b(Pn=>{"use strict";var bg=B(),Lo=rr(),kg={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:Lo.stringifyNumber},Sg={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():Lo.stringifyNumber(e)}},Eg={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.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:Lo.stringifyNumber};Pn.float=Eg;Pn.floatExp=Sg;Pn.floatNaN=kg});var _u=b(Yr=>{"use strict";var Au=rr(),Kr=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 qo(e,t,r){let{value:i}=e;if(Kr(i)){let n=i.toString(t);return i<0?"-"+r+n.substr(1):r+n}return Au.stringifyNumber(e)}var Pg={identify:Kr,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=>qo(e,2,"0b")},xg={identify:Kr,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=>qo(e,8,"0")},Rg={identify:Kr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>xn(e,0,10,r),stringify:Au.stringifyNumber},Cg={identify:Kr,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=>qo(e,16,"0x")};Yr.int=Rg;Yr.intBin=Pg;Yr.intHex=Cg;Yr.intOct=xg});var Vo=b(Fo=>{"use strict";var An=C(),Rn=dt(),Cn=ht(),At=class e extends Cn.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;An.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new Rn.Pair(t.key,null):r=new Rn.Pair(t,null),Cn.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let i=Cn.findPair(this.items,t);return!r&&An.isPair(i)?An.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=Cn.findPair(this.items,t);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new Rn.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(Rn.createPair(o,null,i));return a}};At.tag="tag:yaml.org,2002:set";var Ag={collection:"map",identify:e=>e instanceof Set,nodeClass:At,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>At.from(e,t,r),resolve(e,t){if(An.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new At,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Fo.YAMLSet=At;Fo.set=Ag});var Wo=b(_n=>{"use strict";var _g=rr();function Mo(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 Iu(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return _g.stringifyNumber(e);let i="";t<0&&(i="-",t*=r(-1));let n=r(60),a=[t%n];return t<60?a.unshift(0):(t=(t-a[0])/n,a.unshift(t%n),t>=60&&(t=(t-a[0])/n,a.unshift(t))),i+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Ig={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})=>Mo(e,r),stringify:Iu},Tg={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=>Mo(e,!1),stringify:Iu},Tu={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(Tu.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=Mo(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$/,"")??""};_n.floatTime=Tg;_n.intTime=Ig;_n.timestamp=Tu});var Ou=b($u=>{"use strict";var jg=er(),$g=gn(),Og=tr(),Hg=Jr(),Dg=jo(),ju=Ru(),zo=Cu(),In=_u(),Bg=ln(),Lg=Do(),qg=En(),Fg=Vo(),Jo=Wo(),Vg=[jg.map,Og.seq,Hg.string,$g.nullTag,ju.trueTag,ju.falseTag,In.intBin,In.intOct,In.int,In.intHex,zo.floatNaN,zo.floatExp,zo.float,Dg.binary,Bg.merge,Lg.omap,qg.pairs,Fg.set,Jo.intTime,Jo.floatTime,Jo.timestamp];$u.schema=Vg});var zu=b(Ko=>{"use strict";var Lu=er(),Mg=gn(),qu=tr(),Wg=Jr(),zg=Po(),Go=Ro(),Uo=Ao(),Jg=pu(),Gg=gu(),Fu=jo(),Xr=ln(),Vu=Do(),Mu=En(),Hu=Ou(),Wu=Vo(),Tn=Wo(),Du=new Map([["core",Jg.schema],["failsafe",[Lu.map,qu.seq,Wg.string]],["json",Gg.schema],["yaml11",Hu.schema],["yaml-1.1",Hu.schema]]),Bu={binary:Fu.binary,bool:zg.boolTag,float:Go.float,floatExp:Go.floatExp,floatNaN:Go.floatNaN,floatTime:Tn.floatTime,int:Uo.int,intHex:Uo.intHex,intOct:Uo.intOct,intTime:Tn.intTime,map:Lu.map,merge:Xr.merge,null:Mg.nullTag,omap:Vu.omap,pairs:Mu.pairs,seq:qu.seq,set:Wu.set,timestamp:Tn.timestamp},Ug={"tag:yaml.org,2002:binary":Fu.binary,"tag:yaml.org,2002:merge":Xr.merge,"tag:yaml.org,2002:omap":Vu.omap,"tag:yaml.org,2002:pairs":Mu.pairs,"tag:yaml.org,2002:set":Wu.set,"tag:yaml.org,2002:timestamp":Tn.timestamp};function Kg(e,t,r){let i=Du.get(t);if(i&&!e)return r&&!i.includes(Xr.merge)?i.concat(Xr.merge):i.slice();let n=i;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(Du.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(Xr.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Bu[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Bu).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},[])}Ko.coreKnownTags=Ug;Ko.getTags=Kg});var Qo=b(Ju=>{"use strict";var Yo=C(),Yg=er(),Xg=tr(),Qg=Jr(),jn=zu(),Zg=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Xo=class e{constructor({compat:t,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?jn.getTags(t,"compat"):t?jn.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?jn.coreKnownTags:{},this.tags=jn.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,Yo.MAP,{value:Yg.map}),Object.defineProperty(this,Yo.SCALAR,{value:Qg.string}),Object.defineProperty(this,Yo.SEQ,{value:Xg.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Zg:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Ju.Schema=Xo});var Uu=b(Gu=>{"use strict";var ew=C(),Zo=Mr(),Qr=Lr();function tw(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=Zo.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=a(e.commentBefore);r.unshift(Qr.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(ew.isNode(e.contents)){if(e.contents.spaceBefore&&i&&r.push(""),e.contents.commentBefore){let f=a(e.contents.commentBefore);r.push(Qr.indentComment(f,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Zo.stringify(e.contents,n,()=>s=null,c);s&&(l+=Qr.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(Zo.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
|
|
58
|
+
`)?(r.push("..."),r.push(Qr.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(Qr.indentComment(a(c),"")))}return r.join(`
|
|
59
59
|
`)+`
|
|
60
|
-
`}
|
|
60
|
+
`}Gu.stringifyDocument=tw});var Zr=b(Ku=>{"use strict";var rw=Dr(),ir=Qi(),ve=C(),iw=dt(),nw=st(),aw=Qo(),ow=Uu(),es=Ui(),sw=io(),cw=Br(),ts=ro(),rs=class e{constructor(t,r,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ve.NODE_TYPE,{value:ve.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 ts.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,{[ve.NODE_TYPE]:{value:ve.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=ve.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){nr(this.contents)&&this.contents.add(t)}addIn(t,r){nr(this.contents)&&this.contents.addIn(t,r)}createAlias(t,r){if(!t.anchor){let i=es.anchorNames(this);t.anchor=!r||i.has(r)?es.findNewAnchor(r||"a",i):r}return new rw.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=N=>typeof N=="number"||N instanceof String||N instanceof Number,y=r.filter(p).map(String);y.length>0&&(r=r.concat(y)),n=r}else i===void 0&&r&&(i=r,r=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:f}=i??{},{onAnchor:u,setAnchors:d,sourceObjects:m}=es.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:m},h=cw.createNode(t,f,v);return s&&ve.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 iw.Pair(n,a)}delete(t){return nr(this.contents)?this.contents.delete(t):!1}deleteIn(t){return ir.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):nr(this.contents)?this.contents.deleteIn(t):!1}get(t,r){return ve.isCollection(this.contents)?this.contents.get(t,r):void 0}getIn(t,r){return ir.isEmptyPath(t)?!r&&ve.isScalar(this.contents)?this.contents.value:this.contents:ve.isCollection(this.contents)?this.contents.getIn(t,r):void 0}has(t){return ve.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return ir.isEmptyPath(t)?this.contents!==void 0:ve.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,r){this.contents==null?this.contents=ir.collectionFromPath(this.schema,[t],r):nr(this.contents)&&this.contents.set(t,r)}setIn(t,r){ir.isEmptyPath(t)?this.contents=r:this.contents==null?this.contents=ir.collectionFromPath(this.schema,Array.from(t),r):nr(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 ts.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 ts.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 aw.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=nw.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"?sw.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 ow.stringifyDocument(this,t)}};function nr(e){if(ve.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Ku.Document=rs});var ri=b(ti=>{"use strict";var ei=class extends Error{constructor(t,r,i,n){super(),this.name=t,this.code=i,this.message=n,this.pos=r}},is=class extends ei{constructor(t,r,i){super("YAMLParseError",t,r,i)}},ns=class extends ei{constructor(t,r,i){super("YAMLWarning",t,r,i)}},lw=(e,t)=>r=>{if(r.pos[0]===-1)return;r.linePos=r.pos.map(s=>t.linePos(s));let{line:i,col:n}=r.linePos[0];r.message+=` at line ${i}, column ${n}`;let a=n-1,o=e.substring(t.lineStarts[i-1],t.lineStarts[i]).replace(/[\n\r]+$/,"");if(a>=60&&o.length>80){let s=Math.min(a-39,o.length-79);o="…"+o.substring(s),a-=s-1}if(o.length>80&&(o=o.substring(0,79)+"…"),i>1&&/^ *$/.test(o.substring(0,a))){let s=e.substring(t.lineStarts[i-2],t.lineStarts[i-1]);s.length>80&&(s=s.substring(0,79)+`…
|
|
61
61
|
`),o=s+o}if(/[^ ]/.test(o)){let s=1,c=r.linePos[1];c?.line===i&&c.col>n&&(s=Math.max(1,Math.min(c.col-n,80-a)));let l=" ".repeat(a)+"^".repeat(s);r.message+=`:
|
|
62
62
|
|
|
63
63
|
${o}
|
|
64
64
|
${l}
|
|
65
|
-
`}};
|
|
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(
|
|
67
|
-
`+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||
|
|
68
|
-
`+g.comment:
|
|
69
|
-
`+E.comment:l.comment=E.comment),u=E.end;continue}!o&&r.options.strict&&
|
|
70
|
-
`+
|
|
71
|
-
|
|
72
|
-
`+p.comment:l.comment=p.comment),l.range=[i.offset,h,p.offset]}else l.range=[i.offset,h,h];return l}
|
|
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,
|
|
74
|
-
`;for(let h=
|
|
75
|
-
`):p.length>c||
|
|
76
|
-
`:!m&&
|
|
77
|
-
`&&(
|
|
78
|
-
|
|
79
|
-
`),u+=
|
|
80
|
-
`,m=!0):
|
|
65
|
+
`}};ti.YAMLError=ei;ti.YAMLParseError=is;ti.YAMLWarning=ns;ti.prettifyError=lw});var ii=b(Yu=>{"use strict";function uw(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,y=null,N=null,g=null,w=null,S=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:(!w||r!=="seq-item-ind")&&(c=!0):d+=k.source,l=!0,m=!0,(p||y)&&(N=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,S??(S=k.offset),l=!1,f=!1,v=!0;break;case"tag":{y&&a(k,"MULTIPLE_TAGS","A node can have at most one tag"),y=k,S??(S=k.offset),l=!1,f=!1,v=!0;break}case r:(p||y)&&a(k,"BAD_PROP_ORDER",`Anchors and tags must be after the ${k.source} indicator`),w&&a(k,"UNEXPECTED_TOKEN",`Unexpected ${k.source} in ${t??"collection"}`),w=k,l=r==="seq-item-ind"||r==="explicit-key-ind",f=!1;break;case"comma":if(t){g&&a(k,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),g=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:g,found:w,spaceBefore:c,comment:u,hasNewline:m,anchor:p,tag:y,newlineAfterProp:N,end:P,start:S??P}}Yu.resolveProps=uw});var $n=b(Xu=>{"use strict";function as(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(as(t.key)||as(t.value))return!0}return!1;default:return!0}}Xu.containsNewline=as});var os=b(Qu=>{"use strict";var dw=$n();function fw(e,t,r){if(t?.type==="flow-collection"){let i=t.end[0];i.indent===e&&(i.source==="]"||i.source==="}")&&dw.containsNewline(t)&&r(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Qu.flowIndentCheck=fw});var ss=b(ed=>{"use strict";var Zu=C();function hw(e,t,r){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let n=typeof i=="function"?i:(a,o)=>a===o||Zu.isScalar(a)&&Zu.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,r))}ed.mapIncludes=hw});var od=b(ad=>{"use strict";var td=dt(),pw=ht(),rd=ii(),mw=$n(),id=os(),vw=ss(),nd="All mapping items must start at the same column";function gw({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??pw.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=rd.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",nd)),!h.anchor&&!h.tag&&!m){l=h.end,h.comment&&(s.comment?s.comment+=`
|
|
67
|
+
`+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||mw.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",nd);r.atKey=!0;let y=h.end,N=d?e(r,d,h,n):t(r,y,u,null,h,n);r.schema.compat&&id.flowIndentCheck(i.indent,d,n),r.atKey=!1,vw.mapIncludes(r,s.items,N)&&n(y,"DUPLICATE_KEY","Map keys must be unique");let g=rd.resolveProps(m??[],{indicator:"map-value-ind",next:v,offset:N.range[2],onError:n,parentIndent:i.indent,startOnNewline:!d||d.type==="block-scalar"});if(c=g.end,g.found){p&&(v?.type==="block-map"&&!g.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&h.start<g.found.offset-1024&&n(N.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let w=v?e(r,v,g,n):t(r,c,m,null,g,n);r.schema.compat&&id.flowIndentCheck(i.indent,v,n),c=w.range[2];let S=new td.Pair(N,w);r.options.keepSourceTokens&&(S.srcToken=f),s.items.push(S)}else{p&&n(N.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),g.comment&&(N.comment?N.comment+=`
|
|
68
|
+
`+g.comment:N.comment=g.comment);let w=new td.Pair(N);r.options.keepSourceTokens&&(w.srcToken=f),s.items.push(w)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[i.offset,c,l??c],s}ad.resolveBlockMap=gw});var cd=b(sd=>{"use strict";var ww=pt(),yw=ii(),Nw=os();function bw({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??ww.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=yw.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&&Nw.flowIndentCheck(i.indent,u,n),c=m.range[2],s.items.push(m)}return s.range=[i.offset,c,l??c],s}sd.resolveBlockSeq=bw});var ar=b(ld=>{"use strict";function kw(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}}ld.resolveEnd=kw});var hd=b(fd=>{"use strict";var Sw=C(),Ew=dt(),ud=ht(),Pw=pt(),xw=ar(),dd=ii(),Rw=$n(),Cw=ss(),cs="Block collections are not allowed within flow collections",ls=e=>e&&(e.type==="block-map"||e.type==="block-seq");function Aw({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=i.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?ud.YAMLMap:Pw.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 y=i.items[p],{start:N,key:g,sep:w,value:S}=y,E=dd.resolveProps(N,{flow:s,indicator:"explicit-key-ind",next:g??w?.[0],offset:u,onError:n,parentIndent:i.indent,startOnNewline:!1});if(!E.found){if(!E.anchor&&!E.tag&&!w&&!S){p===0&&E.comma?n(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):p<i.items.length-1&&n(E.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),E.comment&&(l.comment?l.comment+=`
|
|
69
|
+
`+E.comment:l.comment=E.comment),u=E.end;continue}!o&&r.options.strict&&Rw.containsNewline(g)&&n(g,"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 N)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];Sw.isPair(k)&&(k=k.value??k.key),k.comment?k.comment+=`
|
|
70
|
+
`+P:k.comment=P,E.comment=E.comment.substring(P.length+1)}}if(!o&&!w&&!E.found){let P=S?e(r,S,E,n):t(r,E.end,w,null,E,n);l.items.push(P),u=P.range[2],ls(S)&&n(P.range,"BLOCK_IN_FLOW",cs)}else{r.atKey=!0;let P=E.end,k=g?e(r,g,E,n):t(r,P,N,null,E,n);ls(g)&&n(k.range,"BLOCK_IN_FLOW",cs),r.atKey=!1;let T=dd.resolveProps(w??[],{flow:s,indicator:"map-value-ind",next:S,offset:k.range[2],onError:n,parentIndent:i.indent,startOnNewline:!1});if(T.found){if(!o&&!E.found&&r.options.strict){if(w)for(let A of w){if(A===T.found)break;if(A.type==="newline"){n(A,"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 S&&("source"in S&&S.source?.[0]===":"?n(S,"MISSING_CHAR",`Missing space after : in ${s}`):n(T.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let Z=S?e(r,S,T,n):T.found?t(r,T.end,w,null,T,n):null;Z?ls(S)&&n(Z.range,"BLOCK_IN_FLOW",cs):T.comment&&(k.comment?k.comment+=`
|
|
71
|
+
`+T.comment:k.comment=T.comment);let pe=new Ew.Pair(k,Z);if(r.options.keepSourceTokens&&(pe.srcToken=y),o){let A=l;Cw.mapIncludes(r,A.items,k)&&n(P,"DUPLICATE_KEY","Map keys must be unique"),A.items.push(pe)}else{let A=new ud.YAMLMap(r.schema);A.flow=!0,A.items.push(pe);let Cr=(Z??k).range;A.range=[k.range[0],Cr[1],Cr[2]],l.items.push(A)}u=Z?Z.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),y=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",y),m&&m.source.length!==1&&v.unshift(m)}if(v.length>0){let p=xw.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}fd.resolveFlowCollection=Aw});var md=b(pd=>{"use strict";var _w=C(),Iw=B(),Tw=ht(),jw=pt(),$w=od(),Ow=cd(),Hw=hd();function us(e,t,r,i,n,a){let o=r.type==="block-map"?$w.resolveBlockMap(e,t,r,i,a):r.type==="block-seq"?Ow.resolveBlockSeq(e,t,r,i,a):Hw.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 Dw(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===Tw.YAMLMap.tagName&&s==="map"||o===jw.YAMLSeq.tagName&&s==="seq")return us(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),us(e,t,r,n,o)}let l=us(e,t,r,n,o,c),f=c.resolve?.(l,d=>n(a,"TAG_RESOLVE_FAILED",d),t.options)??l,u=_w.isNode(f)?f:new Iw.Scalar(f);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}pd.composeCollection=Dw});var fs=b(vd=>{"use strict";var ds=B();function Bw(e,t,r){let i=t.offset,n=Lw(t,e.options.strict,r);if(!n)return{value:"",type:null,comment:"",range:[i,i,i]};let a=n.mode===">"?ds.Scalar.BLOCK_FOLDED:ds.Scalar.BLOCK_LITERAL,o=t.source?qw(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
|
+
`.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,y]=o[h];if(y===""||y==="\r")n.indent===0&&p.length>c&&(c=p.length);else{p.length<c&&r(l+p.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(c=p.length),f=h,c===0&&!e.atRoot&&r(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=p.length+y.length+1}for(let 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
|
+
`;for(let h=f;h<s;++h){let[p,y]=o[h];l+=p.length+y.length+1;let N=y[y.length-1]==="\r";if(N&&(y=y.slice(0,-1)),y&&p.length<c){let w=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;r(l-y.length-(N?2:1),"BAD_INDENT",w),p=""}a===ds.Scalar.BLOCK_LITERAL?(u+=d+p.slice(c)+y,d=`
|
|
75
|
+
`):p.length>c||y[0]===" "?(d===" "?d=`
|
|
76
|
+
`:!m&&d===`
|
|
77
|
+
`&&(d=`
|
|
78
|
+
|
|
79
|
+
`),u+=d+p.slice(c)+y,d=`
|
|
80
|
+
`,m=!0):y===""?d===`
|
|
81
81
|
`?u+=`
|
|
82
|
-
`:
|
|
83
|
-
`:(u+=
|
|
82
|
+
`:d=`
|
|
83
|
+
`:(u+=d+y,d=" ",m=!1)}switch(n.chomp){case"-":break;case"+":for(let h=s;h<o.length;++h)u+=`
|
|
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
|
|
87
|
+
`}let v=i+n.length+t.source.length;return{value:u,type:a,comment:n.comment,range:[i,v,v]}}function Lw({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 qw(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}vd.resolveBlockScalar=Bw});var ps=b(wd=>{"use strict";var hs=B(),Fw=ar();function Vw(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=hs.Scalar.PLAIN,c=Mw(a,l);break;case"single-quoted-scalar":s=hs.Scalar.QUOTE_SINGLE,c=Ww(a,l);break;case"double-quoted-scalar":s=hs.Scalar.QUOTE_DOUBLE,c=zw(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=Fw.resolveEnd(o,f,t,r);return{value:c,type:s,comment:u.comment,range:[i,f,u.offset]}}function Mw(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}`),gd(e)}function Ww(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),gd(e.slice(1,-1)).replace(/''/g,"'")}function gd(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
|
|
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 zw(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}
|
|
93
|
+
`){let{fold:a,offset:o}=Jw(e,i);r+=a,i=o}else if(n==="\\"){let a=e[++i],o=Gw[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+=
|
|
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+=Uw(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
|
|
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 Jw(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
|
|
102
|
-
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function
|
|
101
|
+
`),t+=1,i=e[t+1];return r||(r=" "),{fold:r,offset:t}}var Gw={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
102
|
+
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Uw(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}}wd.resolveFlowScalar=Vw});var bd=b(Nd=>{"use strict";var _t=C(),yd=B(),Kw=fs(),Yw=ps();function Xw(e,t,r,i){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?Kw.resolveBlockScalar(e,t,i):Yw.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[_t.SCALAR]:c?l=Qw(e.schema,n,c,r,i):t.type==="scalar"?l=Zw(e,n,t,i):l=e.schema[_t.SCALAR];let f;try{let u=l.resolve(n,d=>i(r??t,"TAG_RESOLVE_FAILED",d),e.options);f=_t.isScalar(u)?u:new yd.Scalar(u)}catch(u){let d=u instanceof Error?u.message:String(u);i(r??t,"TAG_RESOLVE_FAILED",d),f=new yd.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 Qw(e,t,r,i,n){if(r==="!")return e[_t.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[_t.SCALAR])}function Zw({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[_t.SCALAR];if(r.compat){let s=r.compat.find(c=>c.default&&c.test?.test(i))??r[_t.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}Nd.composeScalar=Xw});var Sd=b(kd=>{"use strict";function ey(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}kd.emptyScalarPosition=ey});var xd=b(vs=>{"use strict";var ty=Dr(),ry=C(),iy=md(),Ed=bd(),ny=ar(),ay=Sd(),oy={composeNode:Pd,composeEmptyNode:ms};function Pd(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=sy(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=Ed.composeScalar(e,t,c,i),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=iy.composeCollection(oy,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=ms(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&&(!ry.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 ms(e,t,r,i,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let f={type:"scalar",offset:ay.emptyScalarPosition(t,r,i),indent:-1,source:""},u=Ed.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 sy({options:e},{offset:t,source:r,end:i},n){let a=new ty.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=ny.resolveEnd(i,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}vs.composeEmptyNode=ms;vs.composeNode=Pd});var Ad=b(Cd=>{"use strict";var cy=Zr(),Rd=xd(),ly=ar(),uy=ii();function dy(e,t,{offset:r,start:i,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new cy.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=uy.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?Rd.composeNode(l,n,f,o):Rd.composeEmptyNode(l,f.end,i,null,f,o);let u=c.contents.range[2],d=ly.resolveEnd(a,u,!1,o);return d.comment&&(c.comment=d.comment),c.range=[r,u,d.offset],c}Cd.composeDoc=dy});var ws=b(Td=>{"use strict";var fy=Li("process"),hy=ro(),py=Zr(),ni=ri(),_d=C(),my=Ad(),vy=ar();function ai(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 Id(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
|
|
106
|
-
${i}`:i;else if(n||t.directives.docStart||!a)t.commentBefore=i;else if(
|
|
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 gs=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,i,n,a)=>{let o=ai(r);a?this.warnings.push(new ni.YAMLWarning(o,i,n)):this.errors.push(new ni.YAMLParseError(o,i,n))},this.directives=new hy.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,r){let{comment:i,afterEmptyLine:n}=Id(this.prelude);if(i){let a=t.contents;if(r)t.comment=t.comment?`${t.comment}
|
|
106
|
+
${i}`:i;else if(n||t.directives.docStart||!a)t.commentBefore=i;else if(_d.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];_d.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:
|
|
109
|
-
${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new
|
|
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:Id(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,r=!1,i=-1){for(let n of t)yield*this.next(n);yield*this.end(r,i)}*next(t){switch(fy.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(r,i,n)=>{let a=ai(t);a[0]+=r,this.onError(a,"BAD_DIRECTIVE",i,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let r=my.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 ni.YAMLParseError(ai(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 ni.YAMLParseError(ai(t),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let r=vy.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 ni.YAMLParseError(ai(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 py.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}}};Td.Composer=gs});var Od=b(On=>{"use strict";var gy=fs(),wy=ps(),yy=ri(),jd=Vr();function Ny(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 yy.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return wy.resolveFlowScalar(e,t,i);case"block-scalar":return gy.resolveBlockScalar({options:{strict:t}},e,i)}}return null}function by(e,t){let{implicitKey:r=!1,indent:i,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=jd.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
|
-
`),
|
|
112
|
-
`,
|
|
113
|
-
`}),{type:"block-scalar",offset:a,indent:i,props:
|
|
111
|
+
`),f=s.substring(0,l),u=s.substring(l+1)+`
|
|
112
|
+
`,d=[{type:"block-scalar-header",offset:a,indent:i,source:f}];return $d(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 ky(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=jd.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">":Sy(e,c);break;case'"':ys(e,c,"double-quoted-scalar");break;case"'":ys(e,c,"single-quoted-scalar");break;default:ys(e,c,"scalar")}}function Sy(e,t){let r=t.indexOf(`
|
|
114
114
|
`),i=t.substring(0,r),n=t.substring(r+1)+`
|
|
115
|
-
`;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=i,e.source=n}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:i}]
|
|
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
|
|
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})}}}
|
|
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}];$d(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
|
|
116
|
+
`});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function $d(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 ys(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})}}}On.createScalarToken=by;On.resolveAsScalar=Ny;On.setScalarValue=ky});var Dd=b(Hd=>{"use strict";var Ey=e=>"type"in e?Dn(e):Hn(e);function Dn(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=Dn(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=Hn(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=Hn(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=Hn(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 Hn({start:e,key:t,sep:r,value:i}){let n="";for(let a of e)n+=a.source;if(t&&(n+=Dn(t)),r)for(let a of r)n+=a.source;return i&&(n+=Dn(i)),n}Hd.stringify=Ey});var Fd=b(qd=>{"use strict";var Ns=Symbol("break visit"),Py=Symbol("skip children"),Bd=Symbol("remove item");function It(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Ld(Object.freeze([]),e,t)}It.BREAK=Ns;It.SKIP=Py;It.REMOVE=Bd;It.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};It.parentCollection=(e,t)=>{let r=It.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 Ld(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=Ld(Object.freeze(e.concat([[n,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===Ns)return Ns;s===Bd&&(a.items.splice(o,1),o-=1)}}typeof i=="function"&&n==="key"&&(i=i(t,e))}}return typeof i=="function"?i(t,e):i}qd.visit=It});var Bn=b(oe=>{"use strict";var bs=Od(),xy=Dd(),Ry=Fd(),ks="\uFEFF",Ss="",Es="",Ps="",Cy=e=>!!e&&"items"in e,Ay=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function _y(e){switch(e){case ks:return"<BOM>";case Ss:return"<DOC>";case Es:return"<FLOW_END>";case Ps:return"<SCALAR>";default:return JSON.stringify(e)}}function Iy(e){switch(e){case ks:return"byte-order-mark";case Ss:return"doc-mode";case Es:return"flow-error-end";case Ps: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}
|
|
120
|
-
`:case"\r":case" ":return!0;default:return!1}}var
|
|
121
|
-
\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}oe.createScalarToken=bs.createScalarToken;oe.resolveAsScalar=bs.resolveAsScalar;oe.setScalarValue=bs.setScalarValue;oe.stringify=xy.stringify;oe.visit=Ry.visit;oe.BOM=ks;oe.DOCUMENT=Ss;oe.FLOW_END=Es;oe.SCALAR=Ps;oe.isCollection=Cy;oe.isScalar=Ay;oe.prettyToken=_y;oe.tokenType=Iy});var Cs=b(Md=>{"use strict";var oi=Bn();function Pe(e){switch(e){case void 0:case" ":case`
|
|
120
|
+
`:case"\r":case" ":return!0;default:return!1}}var Vd=new Set("0123456789ABCDEFabcdef"),Ty=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Ln=new Set(",[]{}"),jy=new Set(` ,[]{}
|
|
121
|
+
\r `),xs=e=>!e||jy.has(e),Rs=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,r=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!r;let i=this.next??"stream";for(;i&&(r||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let t=this.pos,r=this.buffer[t];for(;r===" "||r===" ";)r=this.buffer[++t];return!r||r==="#"||r===`
|
|
122
122
|
`?!0:r==="\r"?this.buffer[t+1]===`
|
|
123
123
|
`:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let r=this.buffer[t];if(this.indentNext>0){let i=0;for(;r===" ";)r=this.buffer[++i+t];if(r==="\r"){let n=this.buffer[i+t+1];if(n===`
|
|
124
124
|
`||!n&&!this.atEnd)return t+i+1}return r===`
|
|
125
|
-
`||i>=this.indentNext||!r&&!this.atEnd?t+i:-1}if(r==="-"||r==="."){let i=this.buffer.substr(t,3);if((i==="---"||i==="...")&&
|
|
126
|
-
`,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===
|
|
125
|
+
`||i>=this.indentNext||!r&&!this.atEnd?t+i:-1}if(r==="-"||r==="."){let i=this.buffer.substr(t,3);if((i==="---"||i==="...")&&Pe(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
|
|
126
|
+
`,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===oi.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let r=t.length,i=t.indexOf("#");for(;i!==-1;){let a=t[i-1];if(a===" "||a===" "){r=i-1;break}else i=t.indexOf("#",i+1)}for(;;){let a=t[r-1];if(a===" "||a===" ")r-=1;else break}let n=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let r=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-r),yield*this.pushNewline(),"stream"}return yield oi.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let r=this.peek(3);if((r==="---"||r==="...")&&Pe(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,r==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Pe(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,r]=this.peek(2);if(!r&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&Pe(r)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let r=yield*this.pushIndicators();switch(t[r]){case"#":yield*this.pushCount(t.length-r);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(xs),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return r+=yield*this.parseBlockScalarHeader(),r+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-r),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,r,i=-1;do t=yield*this.pushNewline(),t>0?(r=yield*this.pushSpaces(!1),this.indentValue=i=r):r=0,r+=yield*this.pushSpaces(!0);while(t+r>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((i!==-1&&i<this.indentNext&&n[0]!=="#"||i===0&&(n.startsWith("---")||n.startsWith("..."))&&Pe(n[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield oi.FLOW_END,yield*this.parseLineStart();let a=0;for(;n[a]===",";)a+=yield*this.pushCount(1),a+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(a+=yield*this.pushIndicators(),n[a]){case void 0:return"flow";case"#":return yield*this.pushCount(n.length-a),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(xs),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Pe(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),r=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;r!==-1&&this.buffer[r+1]==="'";)r=this.buffer.indexOf("'",r+2);else for(;r!==-1;){let a=0;for(;this.buffer[r-1-a]==="\\";)a+=1;if(a%2===0)break;r=this.buffer.indexOf('"',r+1)}let i=this.buffer.substring(0,r),n=i.indexOf(`
|
|
127
127
|
`,this.pos);if(n!==-1){for(;n!==-1;){let a=this.continueScalar(n+1);if(a===-1)break;n=i.indexOf(`
|
|
128
|
-
`,a)}n!==-1&&(r=n-(i[n-1]==="\r"?2:1))}if(r===-1){if(!this.atEnd)return this.setNext("quoted-scalar");r=this.buffer.length}return yield*this.pushToIndex(r+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let r=this.buffer[++t];if(r==="+")this.blockScalarKeep=!0;else if(r>"0"&&r<="9")this.blockScalarIndent=Number(r)-1;else if(r!=="-")break}return yield*this.pushUntil(r=>
|
|
128
|
+
`,a)}n!==-1&&(r=n-(i[n-1]==="\r"?2:1))}if(r===-1){if(!this.atEnd)return this.setNext("quoted-scalar");r=this.buffer.length}return yield*this.pushToIndex(r+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let r=this.buffer[++t];if(r==="+")this.blockScalarKeep=!0;else if(r>"0"&&r<="9")this.blockScalarIndent=Number(r)-1;else if(r!=="-")break}return yield*this.pushUntil(r=>Pe(r)||r==="#")}*parseBlockScalar(){let t=this.pos-1,r=0,i;e:for(let a=this.pos;i=this.buffer[a];++a)switch(i){case" ":r+=1;break;case`
|
|
129
129
|
`:t=a,r=0;break;case"\r":{let o=this.buffer[a+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
|
|
130
130
|
`)break}default:break e}if(!i&&!this.atEnd)return this.setNext("block-scalar");if(r>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=r:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let a=this.continueScalar(t+1);if(a===-1)break;t=this.buffer.indexOf(`
|
|
131
131
|
`,a)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let n=t+1;for(i=this.buffer[n];i===" ";)i=this.buffer[++n];if(i===" "){for(;i===" "||i===" "||i==="\r"||i===`
|
|
132
132
|
`;)i=this.buffer[++n];t=n-1}else if(!this.blockScalarKeep)do{let a=t-1,o=this.buffer[a];o==="\r"&&(o=this.buffer[--a]);let s=a;for(;o===" ";)o=this.buffer[--a];if(o===`
|
|
133
|
-
`&&a>=this.pos&&a+1+r>s)t=a;else break}while(!0);return yield
|
|
133
|
+
`&&a>=this.pos&&a+1+r>s)t=a;else break}while(!0);return yield oi.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(Pe(a)||t&&Ln.has(a))break;r=i}else if(Pe(n)){let a=this.buffer[i+1];if(n==="\r"&&(a===`
|
|
134
134
|
`?(i+=1,n=`
|
|
135
|
-
`,a=this.buffer[i+1]):r=i),a==="#"||t&&
|
|
136
|
-
`){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&
|
|
135
|
+
`,a=this.buffer[i+1]):r=i),a==="#"||t&&Ln.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&&Ln.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield oi.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(xs),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(Pe(i)||r&&Ln.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(;!Pe(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(Ty.has(r))r=this.buffer[++t];else if(r==="%"&&Vd.has(this.buffer[t+1])&&Vd.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)}};
|
|
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)}};Md.Lexer=Rs});var _s=b(Wd=>{"use strict";var As=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}}}};Wd.LineCounter=As});var Ts=b(Kd=>{"use strict";var $y=Li("process"),zd=Bn(),Oy=Cs();function mt(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function Jd(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 Ud(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function qn(e){switch(e.type){case"document":return e.start;case"block-map":{let t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function or(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 Fn(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 Gd(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!mt(t.start,"explicit-key-ind")&&!mt(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Ud(t.value)?t.value.end?Fn(t.value.end,t.sep):t.value.end=t.sep:Fn(t.start,t.sep),delete t.sep)}var Is=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 Oy.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,$y.env.LOG_TOKENS&&console.log("|",zd.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=zd.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"&&Gd(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&&Jd(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":{Jd(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let r=qn(this.peek(2)),i=or(r),n;t.end?(n=t.end,n.push(this.sourceToken),delete t.end):n=[this.sourceToken];let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:i,key:t,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let r=this.source.indexOf(`
|
|
139
139
|
`)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
|
|
140
|
-
`,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else if(r.sep)r.sep.push(this.sourceToken);else{if(this.atIndentedComment(r.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){
|
|
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)){Fn(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(mt(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(Ud(r.key)&&!mt(r.sep,"newline")){let o=or(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(mt(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=or(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]}):mt(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&&!mt(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)){Fn(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||mt(r.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return}if(this.indent>t.indent){let i=this.startBlockValue(t);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let r=t.items[t.items.length-1];if(this.type==="flow-error-end"){let i;do yield*this.pop(),i=this.peek(1);while(i?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!r||r.sep?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return;case"map-value-ind":!r||r.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!r||r.value?t.items.push({start:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let n=this.flowScalar(this.type);!r||r.value?t.items.push({start:[],key:n,sep:[]}):r.sep?this.stack.push(n):Object.assign(r,{key:n,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let i=this.startBlockValue(t);i?this.stack.push(i):(yield*this.pop(),yield*this.step())}else{let i=this.peek(2);if(i.type==="block-map"&&(this.type==="map-value-ind"&&i.indent===t.indent||this.type==="newline"&&!i.items[i.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&i.type!=="flow-collection"){let n=qn(i),a=or(n);Gd(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=
|
|
143
|
-
`,r)}import{createHash as
|
|
142
|
+
`,r)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=qn(t),i=or(r);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let r=qn(t),i=or(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())}}};Kd.Parser=Is});var ef=b(ci=>{"use strict";var Yd=ws(),Hy=Zr(),si=ri(),Dy=vo(),By=C(),Ly=_s(),Xd=Ts();function Qd(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new Ly.LineCounter||null,prettyErrors:t}}function qy(e,t={}){let{lineCounter:r,prettyErrors:i}=Qd(t),n=new Xd.Parser(r?.addNewLine),a=new Yd.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach(si.prettifyError(e,r)),s.warnings.forEach(si.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Zd(e,t={}){let{lineCounter:r,prettyErrors:i}=Qd(t),n=new Xd.Parser(r?.addNewLine),a=new Yd.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 si.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(si.prettifyError(e,r)),o.warnings.forEach(si.prettifyError(e,r))),o}function Fy(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=Zd(e,r);if(!n)return null;if(n.warnings.forEach(a=>Dy.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 Vy(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 By.isDocument(e)&&!i?e.toString(r):new Hy.Document(e,i,r).toString(r)}ci.parse=Fy;ci.parseAllDocuments=qy;ci.parseDocument=Zd;ci.stringify=Vy});var sr=b(_=>{"use strict";var My=ws(),Wy=Zr(),zy=Qo(),js=ri(),Jy=Dr(),vt=C(),Gy=dt(),Uy=B(),Ky=ht(),Yy=pt(),Xy=Bn(),Qy=Cs(),Zy=_s(),eN=Ts(),Vn=ef(),tf=jr();_.Composer=My.Composer;_.Document=Wy.Document;_.Schema=zy.Schema;_.YAMLError=js.YAMLError;_.YAMLParseError=js.YAMLParseError;_.YAMLWarning=js.YAMLWarning;_.Alias=Jy.Alias;_.isAlias=vt.isAlias;_.isCollection=vt.isCollection;_.isDocument=vt.isDocument;_.isMap=vt.isMap;_.isNode=vt.isNode;_.isPair=vt.isPair;_.isScalar=vt.isScalar;_.isSeq=vt.isSeq;_.Pair=Gy.Pair;_.Scalar=Uy.Scalar;_.YAMLMap=Ky.YAMLMap;_.YAMLSeq=Yy.YAMLSeq;_.CST=Xy;_.Lexer=Qy.Lexer;_.LineCounter=Zy.LineCounter;_.Parser=eN.Parser;_.parse=Vn.parse;_.parseAllDocuments=Vn.parseAllDocuments;_.parseDocument=Vn.parseDocument;_.stringify=Vn.stringify;_.visit=tf.visit;_.visitAsync=tf.visitAsync});import{randomUUID as tE}from"node:crypto";import{promises as X}from"node:fs";import ie from"node:path";import{execFileSync as um}from"child_process";import _r from"path";function at(e,t){return um("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function dm(e,t){let r=_r.normalize(e),i=_r.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function j(e){try{let t=_r.resolve(at(e,["rev-parse","--show-toplevel"])),i=at(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?_r.resolve(i.slice(9)):t,a=null;try{a=at(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!dm(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function ul(e){try{at(e,["rev-parse","--is-inside-work-tree"]);let t=at(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:_r.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 le(e){return ul(e).map(t=>t.root)}function Ir(e,t){try{return at(e,["check-ref-format","--branch",t]),at(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function Pt(e,t){try{let r=at(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{randomUUID as fm}from"crypto";import{promises as M}from"fs";import ke from"path";function ot(e){return e!==0&&e!==0n&&e!=="0"}function Te(e,t){return ot(e.dev)&&ot(t.dev)&&ot(e.ino)&&ot(t.ino)}function $(e,t){let r=ot(e.dev)&&ot(t.dev);if(r&&e.dev!==t.dev)return!1;let i=ot(e.ino)&&ot(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}function qi(e,t){let r=ke.relative(e,t);return r===""||!ke.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ke.sep}`)}function hm(e,t){return $({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Fi(e,t){return $({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function pm(e,t){return Fi(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function dl(e){let t=await M.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 M.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Kt(e){for(let t of e){let r=await M.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!hm(t,r)||await M.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function mm(e,t,r){let[i,n]=await Promise.all([M.lstat(e),M.realpath(e),r?Kt(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!Fi(i,t)||r&&!qi(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function vm(e,t){let r=ke.resolve(e),i=ke.resolve(t);if(!qi(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await dl(r)],a=ke.relative(r,i).split(ke.sep).filter(Boolean),o=r;for(let s of a){await Kt(n),o=ke.join(o,s);try{await M.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await dl(o);if(!qi(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Kt(n),n}async function gm(e){let t;try{t=await M.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 wm(e,t,r={}){let i=ke.dirname(e),n=r.containedRoot?await vm(r.containedRoot,i):null;n||await M.mkdir(i,{recursive:!0});let a=ke.join(i,`.${ke.basename(e)}.${fm()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await M.open(a,"wx"),s=await o.stat(),n){let[l,f]=await Promise.all([M.lstat(a),M.realpath(a)]);if(await Kt(n),!l.isFile()||l.isSymbolicLink()||!Fi(s,l)||!qi(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(),!Fi(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 mm(a,c,n),await r.beforeCommit?.(),n){await Kt(n);let l=await M.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!pm(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await M.link(a,e),await M.unlink(a)):await M.rename(a,e),await gm(i)}catch(l){if(await o?.close(),!n)await M.rm(a,{force:!0});else try{await Kt(n),await M.rm(a,{force:!0})}catch{}throw l}}async function ne(e,t,r={}){await wm(e,t,r)}async function G(e,t,r={}){await ne(e,JSON.stringify(t,null,2)+`
|
|
143
|
+
`,r)}import{createHash as km}from"node:crypto";import{promises as Se}from"node:fs";import me from"node:path";import{TextDecoder as Sm}from"node:util";var ym=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),Nm=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function bm(e){return e.toLowerCase().startsWith(".env")}function Tr(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>bm(i))?"environment-file":r.some(i=>Nm.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>ym.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}var Mi=1024*1024;function Qa(e,t){let r=me.relative(e,t);return r===""||!me.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${me.sep}`)}function Em(e){let t=me.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})||me.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=Tr(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 Pm(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function xm(e,t){return $({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Vi(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Te(r,i)?$(r,i):$(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function fl(e){let t=await Se.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Se.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Rm(e,t){let r=me.resolve(e),i=me.resolve(t);if(!Qa(r,i))throw new Error("Native artifact path is outside its root");let n=[await fl(r)],a=r;for(let o of me.relative(r,i).split(me.sep).filter(Boolean)){a=me.join(a,o);let s=await fl(a);if(!Qa(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function hl(e){for(let t of e){let r=await Se.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!xm(t,r)||await Se.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function H(e){let t=Em(e.ref),r=e.maxBytes===null?null:Pm(e.maxBytes??Mi),i=me.resolve(e.root,...t.split("/")),n=await Rm(e.root,me.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await Se.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 Se.realpath(i);if(!Qa(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Se.open(i,"r");try{let[c,l,f]=await Promise.all([s.stat(),Se.lstat(i),Se.realpath(i)]);if(await hl(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||f!==o||!Vi(a,c)||!Vi(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 g=r===null?m.length:r+1-d,w=await s.read(m,0,Math.min(m.length,g),null);if(w.bytesRead===0)break;if(d+=w.bytesRead,r!==null&&d>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);u.push(Buffer.from(m.subarray(0,w.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,h,p]=await Promise.all([s.stat(),Se.lstat(i),Se.realpath(i)]);if(await hl(n),!h.isFile()||h.isSymbolicLink()||p!==o||!Vi(c,v)||!Vi(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let y=Buffer.concat(u,d),N;try{N=new Sm("utf-8",{fatal:!0}).decode(y)}catch(g){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:g})}return{ref:t,size:d,hash:e.includeHash===!1?null:km("sha256").update(y).digest("hex"),text:N}}finally{await s.close()}}var wc=Ar(sr(),1);import vr from"path";var $s={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:"验证预期"}},nf={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:"结论"}},af={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:"结论"}},of=new Map,rf=new Map;for(let e of Object.keys($s)){for(let[t,r]of Object.entries($s[e]))of.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(nf[e]))rf.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(af[e]))rf.set(r.toLocaleLowerCase("en-US"),t)}function tN(e,t){return $s[e][t]}function Os(e,t){return nf[e][t]??af[e][t]}function Hs(e){return of.get(e.trim().toLocaleLowerCase("en-US"))??null}function Mn(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(r=>`# ${tN(e,r)}
|
|
144
144
|
`).join(`
|
|
145
|
-
`)}function Pe(e,t,r){return e==="zh-CN"?r:t}var _s=Sr(nr(),1);import ht from"path";var ii=64*1024,Fn=1024,Vn=64,Zd=1024,ef=64,Is=5,qn={learning:!0,retrieval:!0},nf={provider:"local"},Wy=12e4,tf=6e5,zy=[".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/**"],Jy=["**/.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"],Gy=[...zy,...Jy].sort((e,t)=>e.localeCompare(t,"en"));var ue={include:["**/*"],exclude:[...Gy],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function Uy(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||ht.posix.isAbsolute(r)||ht.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 At(e){let t=Uy(e,"native.artifact_root");return t.length===0?".":t.join("/")}function af(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 Mn(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||ht.posix.isAbsolute(i)||ht.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 We(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function of(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 Ts(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>Fn)throw new Error(`${t} exceeds ${Fn} 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>Vn)throw new Error(`${t} contains more than ${Vn} wildcard tokens`);return e}function rf(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=>Ts(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function As(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 Ky(e){if(e===void 0)return{...ue,include:[...ue.include],exclude:[...ue.exclude]};let t=We(e,"native.snapshot");return{include:rf(t.include,"native.snapshot.include",ue.include),exclude:rf(t.exclude,"native.snapshot.exclude",ue.exclude),max_files:As(t.max_files,ue.max_files,"native.snapshot.max_files"),max_total_bytes:As(t.max_total_bytes,ue.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:As(t.max_duration_ms,ue.max_duration_ms,"native.snapshot.max_duration_ms")}}function Yy(e){if(e===void 0)return;let t=We(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=We(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,d=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 d!="string"||!/^[a-f0-9]{64}$/u.test(d))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:d}}return{id:r,fromArtifactRoot:At(i),toArtifactRoot:At(n),stage:a,...o?{cleanup:o}:{}}}function Xy(e){if(e===void 0)return;let t=We(e,"native.finish");if(t.pull_request===void 0)return{};let r=We(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(ht.posix.isAbsolute(i[0])||ht.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??Wy;if(!Number.isSafeInteger(n)||n<1||n>tf)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${tf}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function Qy(e,t={}){let r=We(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??Is;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=Yy(r.pending_root_move),c=Xy(r.finish);return{artifact_root:At(i),language:of(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:Ky(r.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function Zy(e){let t=We(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:af(t.artifact_layout),language:of(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n}}function eN(e){let r=We(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)=>Mn(i,`hook.allow_paths[${n}]`)))]}}function tN(e){if(e===void 0)return{...qn};let t=We(e,"memory"),r=t.learning??qn.learning,i=t.retrieval??qn.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 js(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function rN(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")||ht.posix.isAbsolute(r)||ht.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>Zd)throw new Error(`${t} exceeds ${Zd} 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>ef)throw new Error(`${t} contains more than ${ef} wildcard tokens`);return r}function iN(e){let r=js(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)=>rN(i,`knowledge.local.include[${n}]`)))]}}function nN(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 aN(e){let t=js(e,"knowledge.remote"),r=nN(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 oN(e){if(e===void 0)return{...nf};let t=js(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:iN(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:aN(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 sN(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function cN(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 d=e.workflows??[e.default_workflow];if(!Array.isArray(d)||d.length===0||d.some(f=>f!=="native"&&f!=="classic"))throw new Error("workflows must contain native and/or classic");let u=[...new Set(d)];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 ni(e,t={}){let r=(0,_s.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=sN(n.ambient_resume),o=n.hook===void 0?void 0:eN(n.hook),s=tN(n.memory),c=oN(n.knowledge),l=n.native===void 0?void 0:Qy(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),d=n.classic===void 0?void 0:Zy(n.classic),u=cN(n,o,s,c,l,d,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:u,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...d?{classic:d}:{}}}function Wn(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...qn},knowledge:{...nf},native:{artifact_root:At(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:Is,snapshot:{...ue,include:[...ue.include],exclude:[...ue.exclude]}}}}import{createHash as uN}from"crypto";import{promises as Gn}from"fs";import pt from"path";import{constants as zn,promises as _t}from"fs";var xe=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}};function $s(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function sf(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function ai(e){return{dev:e.dev,ino:e.ino,birthtime:$s(e)}}function Jn(e,t){let r=ai(e),i=ai(t);return Ie(r,i)?T(r,i):T(r,i)&&$s(e)===$s(t)&&sf(e)===sf(t)&&e.size===t.size}async function It(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 _t.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new xe("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new xe("too-large",`${i} exceeds ${t} bytes`);let o=await _t.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:ai(a)});let s=process.platform==="win32"?zn.O_RDONLY:zn.O_RDONLY|zn.O_NOFOLLOW|zn.O_NONBLOCK,c;try{c=await _t.open(e,s)}catch(l){throw l.code==="ELOOP"?new xe("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,d,u]=await Promise.all([c.stat({bigint:n}),_t.lstat(e,{bigint:n}),_t.realpath(e)]);if(!l.isFile()||!d.isFile()||d.isSymbolicLink()||u!==o||!Jn(a,l)||!Jn(a,d))throw new xe("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:u,identity:ai(l)}),await r.hooks?.afterOpen?.();let f=[],m=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let y=t+1-m,{bytesRead:g}=await c.read(v,0,Math.min(v.length,y),null);if(g===0)break;if(m+=g,m>t)throw new xe("too-large",`${i} exceeds ${t} bytes`);f.push(Buffer.from(v.subarray(0,g)))}await r.hooks?.beforeFinalCheck?.();let[h,p,w]=await Promise.all([c.stat({bigint:n}),_t.lstat(e,{bigint:n}),_t.realpath(e)]);if(!p.isFile()||p.isSymbolicLink()||w!==o||!Jn(a,h)||!Jn(a,p))throw new xe("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:w,identity:ai(h)}),{bytes:Buffer.concat(f,m),stat:h,realPath:w}}finally{await c.close()}}function lN(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Os(e,t){let r=pt.relative(e,t);return r===""||!pt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${pt.sep}`)}async function cf(e,t){let r=pt.resolve(e),i=await Gn.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return Gn.realpath(r)}async function lf(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=pt.join(n,r[a]);let o;try{o=await Gn.lstat(n)}catch(d){if(lN(d))return{exists:!1,kind:"missing"};throw d}let s=pt.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 Gn.realpath(n);if(!Os(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 ar(e,t,r){let i=Mn(t,r.label),n=pt.resolve(e),a=await cf(n,r.label),o=i.split("/"),s=pt.resolve(n,...o);if(!Os(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await lf(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function mt(e,t,r,i){let n=await ar(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 cf(n.projectRoot,i.label);return It(n.target,r,{...i,verify:async(o,s)=>{if(!Os(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await lf(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var oi=".comet/config.yaml";function dN(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Un(e,t={}){return(await Kn(e,t)).document}async function fN(e){try{return(await mt(e,oi,ii,{label:oi})).bytes}catch(t){if(dN(t))return null;throw t}}function hN(e){return e?{exists:!0,sha256:uN("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Kn(e,t={}){let r=await fN(e);return{document:r?ni(r.toString("utf8"),t):null,identity:hN(r)}}async function Hs(e){return(await Un(e))?.config??null}var CC=16*1024;import{existsSync as df,promises as Tt}from"fs";import _ from"path";import wN from"os";var Yn=".comet/config.yaml",yN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function Ls(e){try{return await Tt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function NN(e){try{let t=await Tt.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function sr(e,t){let r=_.relative(e,t);return r===""||!_.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${_.sep}`)}async function or(e){let t=[],r=e;for(;!await Ls(r);){let n=_.dirname(r);if(n===r)break;t.push(_.basename(r)),r=n}let i=await Tt.realpath(r);return _.resolve(i,...t.reverse())}async function qs(e){try{return(await Tt.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Xn(e){let t=_.resolve(e);try{(await Tt.stat(t)).isDirectory()||(t=_.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=_.resolve(wN.homedir());for(;;){if(!(t===i&&r!==i)){let o=_.join(t,...Yn.split("/")),s=t===r||await NN(o);if(await Ls(o)&&s)return t}if(await Ls(_.join(t,".git")))return t;let a=_.dirname(t);if(a===t)return r;t=a}}function Qn(e){return At(e)}async function bN(e,t){let r=Qn(t),i=_.resolve(e,...r.split("/")),n=await Tt.realpath(e),a=await or(i);if(!sr(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function ze(e,t){let r=Qn(t),i=await bN(e,r),n=_.join(i,"comet");if(await qs(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([or(i),or(n)]);if(!sr(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=_.resolve(e),c=_.join(s,".comet","runtime","native");if(await qs(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,d]=await Promise.all([Tt.realpath(s),or(c)]);if(!sr(l,d))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:_.join(e,...Yn.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:_.join(n,"specs"),changesDir:_.join(n,"changes"),archiveDir:_.join(n,"archive"),runtimeDir:c,changesRuntimeDir:_.join(c,"changes"),locksDir:_.join(c,"locks"),transactionsDir:_.join(c,"transactions")}}function ff(e){if(!yN.test(e))throw new Error(`Invalid Native change name: ${e}`)}function ve(e,t){ff(t);let r=_.join(e.changesRuntimeDir,t);if(!V(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function Fs(e,t){ff(t);let r=_.join(e.changesDir,t,"runtime");if(!V(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function $e(e,t){let r=ve(e,t);if(df(r))return r;let i=Fs(e,t);return df(i)?i:r}function Oe(e,t){let r=_.resolve(t);if(V(e.runtimeDir,r))return e.runtimeDir;if(V(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function V(e,t){return sr(_.resolve(e),_.resolve(t))}async function D(e,t){let r=_.resolve(e),i=_.resolve(t);if(!sr(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await qs(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([or(r),or(i)]);if(!sr(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}function SN(e="docs",t="en"){return Wn(e,t)}async function de(e){let t=(await Un(e))?.config??null;return t?.native?t:null}async function ci(e){let t=await de(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 hf(e){let t=await Xn(e.startPath),r=await de(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${Yn} 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?Qn(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??SN(i??"docs"),a=await ze(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}import{promises as Zb}from"fs";import ek from"path";import{AsyncLocalStorage as EN}from"async_hooks";import{randomUUID as vf}from"crypto";import{promises as ge}from"fs";import gf from"os";import Q from"path";var pf=16*1024,wf=".coordinator",PN=5e3,mf=new EN,Zn=new Map;function xN(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function CN(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 yf(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 ea(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Ie(r,i)?T(r,i):T(r,i)&&e.size===t.size}function Vs(e,t){return ea(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function He(e){let t,r;try{let i=await It(e,pf,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof xe?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${pf} 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:CN(JSON.parse(t.toString("utf8")),e),identity:yf(r)}}async function RN(e){return(await He(e))?.owner??null}function Nf(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==gf.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=$N(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function AN(e,t){try{await ge.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await ge.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function Ms(e,t){let r=await He(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Vs(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await ge.mkdir(t,{recursive:!0});let i=Q.join(t,`${Q.basename(e.file)}.${e.owner.id}.${vf()}.removed`);try{await ge.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await He(i);if(!n||n.owner.id!==e.owner.id||!ea(n.identity,e.identity))throw await AN(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await ge.rm(i,{force:!0}),"removed"}function bf(e){return{id:vf(),pid:process.pid,hostname:gf.hostname(),createdAt:new Date().toISOString(),operation:e}}async function kf(e,t){let r;try{r=await ge.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await RN(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)+`
|
|
146
|
-
`,"utf8"),await r.sync(),i=
|
|
147
|
-
${
|
|
145
|
+
`)}function xe(e,t,r){return e==="zh-CN"?r:t}var Bs=Ar(sr(),1);import gt from"path";var li=64*1024,zn=1024,Jn=64,sf=1024,cf=64,Ls=5,Wn={learning:!0,retrieval:!0},df={provider:"local"},rN=12e4,lf=6e5,iN=[".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/**"],nN=["**/.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"],aN=[...iN,...nN].sort((e,t)=>e.localeCompare(t,"en"));var ue={include:["**/*"],exclude:[...aN],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function oN(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||gt.posix.isAbsolute(r)||gt.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 Tt(e){let t=oN(e,"native.artifact_root");return t.length===0?".":t.join("/")}function ff(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 Gn(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||gt.posix.isAbsolute(i)||gt.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 Ge(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function hf(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 qs(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>zn)throw new Error(`${t} exceeds ${zn} 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>Jn)throw new Error(`${t} contains more than ${Jn} wildcard tokens`);return e}function uf(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=>qs(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function Ds(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 sN(e){if(e===void 0)return{...ue,include:[...ue.include],exclude:[...ue.exclude]};let t=Ge(e,"native.snapshot");return{include:uf(t.include,"native.snapshot.include",ue.include),exclude:uf(t.exclude,"native.snapshot.exclude",ue.exclude),max_files:Ds(t.max_files,ue.max_files,"native.snapshot.max_files"),max_total_bytes:Ds(t.max_total_bytes,ue.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Ds(t.max_duration_ms,ue.max_duration_ms,"native.snapshot.max_duration_ms")}}function cN(e){if(e===void 0)return;let t=Ge(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=Ge(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:Tt(i),toArtifactRoot:Tt(n),stage:a,...o?{cleanup:o}:{}}}function lN(e){if(e===void 0)return;let t=Ge(e,"native.finish");if(t.pull_request===void 0)return{};let r=Ge(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(gt.posix.isAbsolute(i[0])||gt.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??rN;if(!Number.isSafeInteger(n)||n<1||n>lf)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${lf}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function uN(e,t={}){let r=Ge(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??Ls;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=cN(r.pending_root_move),c=lN(r.finish);return{artifact_root:Tt(i),language:hf(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:sN(r.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function dN(e){let t=Ge(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:ff(t.artifact_layout),language:hf(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n}}function fN(e){let r=Ge(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)=>Gn(i,`hook.allow_paths[${n}]`)))]}}function hN(e){if(e===void 0)return{...Wn};let t=Ge(e,"memory"),r=t.learning??Wn.learning,i=t.retrieval??Wn.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 Fs(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function pN(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")||gt.posix.isAbsolute(r)||gt.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>sf)throw new Error(`${t} exceeds ${sf} 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>cf)throw new Error(`${t} contains more than ${cf} wildcard tokens`);return r}function mN(e){let r=Fs(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)=>pN(i,`knowledge.local.include[${n}]`)))]}}function vN(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 gN(e){let t=Fs(e,"knowledge.remote"),r=vN(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 wN(e){if(e===void 0)return{...df};let t=Fs(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:mN(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:gN(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 yN(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function NN(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 ui(e,t={}){let r=(0,Bs.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=yN(n.ambient_resume),o=n.hook===void 0?void 0:fN(n.hook),s=hN(n.memory),c=wN(n.knowledge),l=n.native===void 0?void 0:uN(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),f=n.classic===void 0?void 0:dN(n.classic),u=NN(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 Un(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...Wn},knowledge:{...df},native:{artifact_root:Tt(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:Ls,snapshot:{...ue,include:[...ue.include],exclude:[...ue.exclude]}}}}import{createHash as kN}from"crypto";import{promises as Xn}from"fs";import wt from"path";import{constants as Kn,promises as jt}from"fs";var Re=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}};function Vs(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function pf(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function di(e){return{dev:e.dev,ino:e.ino,birthtime:Vs(e)}}function Yn(e,t){let r=di(e),i=di(t);return Te(r,i)?$(r,i):$(r,i)&&Vs(e)===Vs(t)&&pf(e)===pf(t)&&e.size===t.size}async function $t(e,t,r={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let i=r.label??"file",n=r.bigint===!0,a=await jt.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Re("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Re("too-large",`${i} exceeds ${t} bytes`);let o=await jt.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:di(a)});let s=process.platform==="win32"?Kn.O_RDONLY:Kn.O_RDONLY|Kn.O_NOFOLLOW|Kn.O_NONBLOCK,c;try{c=await jt.open(e,s)}catch(l){throw l.code==="ELOOP"?new Re("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,f,u]=await Promise.all([c.stat({bigint:n}),jt.lstat(e,{bigint:n}),jt.realpath(e)]);if(!l.isFile()||!f.isFile()||f.isSymbolicLink()||u!==o||!Yn(a,l)||!Yn(a,f))throw new Re("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:u,identity:di(l)}),await r.hooks?.afterOpen?.();let d=[],m=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let N=t+1-m,{bytesRead:g}=await c.read(v,0,Math.min(v.length,N),null);if(g===0)break;if(m+=g,m>t)throw new Re("too-large",`${i} exceeds ${t} bytes`);d.push(Buffer.from(v.subarray(0,g)))}await r.hooks?.beforeFinalCheck?.();let[h,p,y]=await Promise.all([c.stat({bigint:n}),jt.lstat(e,{bigint:n}),jt.realpath(e)]);if(!p.isFile()||p.isSymbolicLink()||y!==o||!Yn(a,h)||!Yn(a,p))throw new Re("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:y,identity:di(h)}),{bytes:Buffer.concat(d,m),stat:h,realPath:y}}finally{await c.close()}}function bN(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Ms(e,t){let r=wt.relative(e,t);return r===""||!wt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${wt.sep}`)}async function mf(e,t){let r=wt.resolve(e),i=await Xn.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return Xn.realpath(r)}async function vf(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=wt.join(n,r[a]);let o;try{o=await Xn.lstat(n)}catch(f){if(bN(f))return{exists:!1,kind:"missing"};throw f}let s=wt.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 Xn.realpath(n);if(!Ms(t,l))throw new Error(`${i.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function cr(e,t,r){let i=Gn(t,r.label),n=wt.resolve(e),a=await mf(n,r.label),o=i.split("/"),s=wt.resolve(n,...o);if(!Ms(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await vf(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function yt(e,t,r,i){let n=await cr(e,t,{label:i.label,expected:"file"});if(!n.exists){let o=new Error(`${i.label} does not exist`);throw o.code="ENOENT",o}let a=await mf(n.projectRoot,i.label);return $t(n.target,r,{...i,verify:async(o,s)=>{if(!Ms(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await vf(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var fi=".comet/config.yaml";function SN(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Qn(e,t={}){return(await Zn(e,t)).document}async function EN(e){try{return(await yt(e,fi,li,{label:fi})).bytes}catch(t){if(SN(t))return null;throw t}}function PN(e){return e?{exists:!0,sha256:kN("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Zn(e,t={}){let r=await EN(e);return{document:r?ui(r.toString("utf8"),t):null,identity:PN(r)}}async function Ws(e){return(await Qn(e))?.config??null}var YR=16*1024;import{existsSync as wf,promises as Ot}from"fs";import I from"path";import _N from"os";var ea=".comet/config.yaml",IN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function Gs(e){try{return await Ot.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function TN(e){try{let t=await Ot.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function ur(e,t){let r=I.relative(e,t);return r===""||!I.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${I.sep}`)}async function lr(e){let t=[],r=e;for(;!await Gs(r);){let n=I.dirname(r);if(n===r)break;t.push(I.basename(r)),r=n}let i=await Ot.realpath(r);return I.resolve(i,...t.reverse())}async function Us(e){try{return(await Ot.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function ta(e){let t=I.resolve(e);try{(await Ot.stat(t)).isDirectory()||(t=I.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=I.resolve(_N.homedir());for(;;){if(!(t===i&&r!==i)){let o=I.join(t,...ea.split("/")),s=t===r||await TN(o);if(await Gs(o)&&s)return t}if(await Gs(I.join(t,".git")))return t;let a=I.dirname(t);if(a===t)return r;t=a}}function ra(e){return Tt(e)}async function jN(e,t){let r=ra(t),i=I.resolve(e,...r.split("/")),n=await Ot.realpath(e),a=await lr(i);if(!ur(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function Ue(e,t){let r=ra(t),i=await jN(e,r),n=I.join(i,"comet");if(await Us(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([lr(i),lr(n)]);if(!ur(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=I.resolve(e),c=I.join(s,".comet","runtime","native");if(await Us(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,f]=await Promise.all([Ot.realpath(s),lr(c)]);if(!ur(l,f))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:I.join(e,...ea.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:I.join(n,"specs"),changesDir:I.join(n,"changes"),archiveDir:I.join(n,"archive"),runtimeDir:c,changesRuntimeDir:I.join(c,"changes"),locksDir:I.join(c,"locks"),transactionsDir:I.join(c,"transactions")}}function yf(e){if(!IN.test(e))throw new Error(`Invalid Native change name: ${e}`)}function ge(e,t){yf(t);let r=I.join(e.changesRuntimeDir,t);if(!F(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function Ks(e,t){yf(t);let r=I.join(e.changesDir,t,"runtime");if(!F(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function Oe(e,t){let r=ge(e,t);if(wf(r))return r;let i=Ks(e,t);return wf(i)?i:r}function He(e,t){let r=I.resolve(t);if(F(e.runtimeDir,r))return e.runtimeDir;if(F(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function F(e,t){return ur(I.resolve(e),I.resolve(t))}async function D(e,t){let r=I.resolve(e),i=I.resolve(t);if(!ur(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await Us(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([lr(r),lr(i)]);if(!ur(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}function ON(e="docs",t="en"){return Un(e,t)}async function de(e){let t=(await Qn(e))?.config??null;return t?.native?t:null}async function pi(e){let t=await de(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 Nf(e){let t=await ta(e.startPath),r=await de(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${ea} 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?ra(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??ON(i??"docs"),a=await Ue(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}import{promises as uk}from"fs";import dk from"path";import{AsyncLocalStorage as HN}from"async_hooks";import{randomUUID as Sf}from"crypto";import{promises as we}from"fs";import Ef from"os";import ee from"path";var bf=16*1024,Pf=".coordinator",DN=5e3,kf=new HN,ia=new Map;function BN(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function LN(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 xf(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 na(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Te(r,i)?$(r,i):$(r,i)&&e.size===t.size}function Ys(e,t){return na(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function De(e){let t,r;try{let i=await $t(e,bf,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof Re?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${bf} bytes: ${e}`,{cause:i}):i.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:i}):new Error(`Native lock changed while reading: ${e}`,{cause:i}):i}return{file:e,owner:LN(JSON.parse(t.toString("utf8")),e),identity:xf(r)}}async function qN(e){return(await De(e))?.owner??null}function Rf(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==Ef.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=JN(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function FN(e,t){try{await we.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await we.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function Xs(e,t){let r=await De(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Ys(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await we.mkdir(t,{recursive:!0});let i=ee.join(t,`${ee.basename(e.file)}.${e.owner.id}.${Sf()}.removed`);try{await we.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await De(i);if(!n||n.owner.id!==e.owner.id||!na(n.identity,e.identity))throw await FN(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await we.rm(i,{force:!0}),"removed"}function Cf(e){return{id:Sf(),pid:process.pid,hostname:Ef.hostname(),createdAt:new Date().toISOString(),operation:e}}async function Af(e,t){let r;try{r=await we.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await qN(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)+`
|
|
146
|
+
`,"utf8"),await r.sync(),i=xf(await r.stat({bigint:!0}))}finally{await r.close()}let n=await De(e);if(!i||!n||n.owner.id!==t.id||!na(n.identity,i))throw new Error(`Native lock changed after write: ${e}`);return n.identity}async function VN(e,t){let r=await D(e.runtimeDir,e.locksDir);await we.mkdir(r,{recursive:!0});let i=await D(e.runtimeDir,ee.join(r,Pf));await we.mkdir(i,{recursive:!0});let n=Cf(t),a=ee.join(i,`.${n.id}.tmp`),o=ee.join(i,`${n.id}.claim`);try{let s=await Af(a,n);await we.rename(a,o);let c=await De(o);if(!c||!na(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 we.rm(a,{force:!0})}}async function MN(e){let t=ee.dirname(e.file),r=!1,i=ee.basename(e.file);for(let n of await we.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=ee.join(t,n.name);if(ee.resolve(a)!==ee.resolve(e.file))try{let o=await De(a),s=Rf(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Xs(o,t);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function _f(e){let t=await De(e.file);if(t){if(t.owner.id!==e.owner.id||!Ys(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await Xs(t,ee.dirname(e.file))}}async function WN(e,t){let r=Date.now()+DN;for(;;){let i=await VN(e,t);if(!await MN(i))return i;if(await _f(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 zN(e){let t=ia.get(e)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=t.then(()=>i);return ia.set(e,n),await t,()=>{r(),ia.get(e)===n&&ia.delete(e)}}async function If(e,t,r){let i=ee.resolve(e.locksDir),n=kf.getStore();if(n?.has(i))return r();let a=await zN(i);try{let o=await WN(e,t),s=new Map(n??[]);return s.set(i,o),await kf.run(s,async()=>{try{return await r()}finally{await _f(o)}})}finally{a()}}async function aa(e,t,r){return If(e,`acquire ${t}`,async()=>{let i=await D(e.runtimeDir,e.locksDir);await we.mkdir(i,{recursive:!0});let n=await D(e.runtimeDir,ee.join(i,BN(t))),a=Cf(r),o=await Af(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:i,owner:a,identity:o}})}async function oa(e){await De(e.file)&&await If({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${ee.basename(e.file)}`,async()=>{let t=await De(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Ys(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let r=ee.join(e.locksDir,Pf);await Xs(t,r)})}function JN(e){try{return process.kill(e,0),!0}catch(t){let r=t.code;return r==="ESRCH"?!1:r==="EPERM"?!0:null}}async function Tf(e){return Rf(await De(e))}import sc from"node:path";import Sb from"node:path";import Bf from"node:path";import{createHash as GN}from"crypto";function Ce(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function UN(e,t){t.has(e)&&Ce("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)||Ce("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&Ce("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&Ce("symbol properties are not supported"),`[${e.map(i=>Qs(i,t)).join(",")}]`}finally{t.delete(e)}}function KN(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&Ce("only plain objects are supported"),t.has(e)&&Ce("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&Ce("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))&&Ce("accessor properties are not supported"),`${JSON.stringify(o)}:${Qs(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function Qs(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)||Ce("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?UN(e,t):KN(e,t);case"bigint":case"function":case"symbol":case"undefined":return Ce(`${typeof e} values are not supported`)}return Ce("unsupported value type")}function Zs(e){return Qs(e,new Set)}function V(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 GN("sha256").update(`${e}
|
|
147
|
+
${Zs(t)}`).digest("hex")}var YN="comet.native.acceptance.v1";var _C=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),ca=Object.freeze({maxCriteria:1024});function Of(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 jf(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 $f(e){return e.includes("-->")||e.includes("--!>")}function*sa(e){let t=null,r=!1,i=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
|
|
148
148
|
`),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
|
|
149
|
-
`,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!r&&i===null,index:s},s+=1,t!==null)t=
|
|
150
|
-
`),[],i)),"Brief",i)}function
|
|
151
|
-
`),o.context,i)),o=null}};for(let{line:c,body:l}of ia(e)){let d=l?Rf(c):null,u=d?/^Scenario\s*:\s*(.*)$/iu.exec(d.text):null;if(u){for(s();a.at(-1)&&a.at(-1).level>=d.level;)a.pop();let f=li(u[1]);if(f.length===0)throw new Error("Scenario title must not be empty");o={level:d.level,title:f,body:[],context:a.map(m=>m.text)}}else if(d){for(o!==null&&d.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=d.level;)a.pop();a.push(d)}else o!==null&&l&&o.body.push(c)}return s(),_f(n,"Specification",i)}var qN=/^A[1-9]\d*$/u;function Tf(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||If.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||If.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function FN(e,t){return e.localeCompare(t,"en")}function aa(e){let t=Tf(e.briefSource??"brief.md","Native brief source"),r=[...e.specs??[]].sort((a,o)=>FN(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=Js(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of r){let o=Tf(a.source,`Native spec source for ${a.capability}`);i.push(...Gs(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=li(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 jf(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(!qN.test(t[r])||t[r]!==`A${r+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function $f(e,t){return e.length===t.length&&e.every((r,i)=>r.source===t[i]?.source&&r.text===t[i]?.text)}var ca=Sr(nr(),1);import{promises as VN}from"node:fs";var cr="comet.native.v4",ui="comet.native.local-execution.v4";var Of=["multi-session","single-session"];function Us(){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 MN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,WN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,zN=/^A[1-9][0-9]*$/u,JN=/^[a-f0-9]{64}$/u,GN=new Set(["schema","name","language","phase","status","state_version","brief","children_contract_hash","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),sa=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 Z(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ee(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 W(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 Ys(e,t){return e===null?null:W(e,t)}function UN(e,t){let r=W(e,t);if(!JN.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function lr(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function j(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 KN(e,t){return e===null?null:j(e,t,Number.MIN_SAFE_INTEGER)}function L(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function De(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function la(e,t){return De(e,t,(r,i)=>W(r,`${t}[${i}]`))}function jt(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function ur(e,t){let r=W(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function Xs(e,t,r=!1){let i=W(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 we(e,t){let r=Z(e,t);return ee(r,new Set(["text","truncated"]),t),{text:W(r.text,`${t}.text`,{empty:!0}),truncated:lr(r.truncated,`${t}.truncated`)}}function YN(e,t){let r=`Native spec_changes[${t}]`,i=Z(e,r);ee(i,new Set(["capability","operation","source"]),r);let n=W(i.capability,`${r}.capability`);if(!WN.test(n))throw new Error(`${r}.capability is invalid`);let a=L(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:Xs(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 XN(e){let t="Native workspace",r=Z(e,t);ee(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=L(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=Ys(r.change_branch,`${t}.change_branch`),a=Ys(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:L(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 QN(e){let t="Native loop",r=Z(e,t);ee(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=la(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);jt(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:L(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:L(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:j(r.goal_cycle,`${t}.goal_cycle`,1),iteration:j(r.iteration,`${t}.iteration`),attempt:j(r.attempt,`${t}.attempt`),retry_epoch:j(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:j(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:j(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:j(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:Ys(r.next_action,`${t}.next_action`)}}function ZN(e,t){let r=`Native acceptance[${t}]`,i=Z(e,r);ee(i,new Set(["id","source","text","result","reason"]),r);let n=W(i.id,`${r}.id`);if(!zN.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:Xs(i.source,`${r}.source`),text:W(i.text,`${r}.text`),result:L(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:we(i.reason,`${r}.reason`)}}function eb(e,t){let r=`Native builder_handoff.checks[${t}]`,i=Z(e,r);return ee(i,new Set(["name","result","note"]),r),{name:we(i.name,`${r}.name`),result:L(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:we(i.note,`${r}.note`)}}function tb(e){let t="Native builder_handoff",r=Z(e,t);ee(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=la(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);jt(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:Z(r.review,`${t}.review`);return n&&ee(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:W(r.candidate_id,`${t}.candidate_id`),identity_provider:W(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:W(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:j(r.iteration,`${t}.iteration`,1),summary:we(r.summary,`${t}.summary`),addressed_acceptance_ids:i,checks:De(r.checks,`${t}.checks`,eb),checks_truncated:lr(r.checks_truncated,`${t}.checks_truncated`),known_limits:De(r.known_limits,`${t}.known_limits`,(a,o)=>we(a,`${t}.known_limits[${o}]`)),known_limits_truncated:lr(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:L(n.status,["passed"],`${t}.review.status`),summary:we(n.summary,`${t}.review.summary`),reviewer_execution_ref:W(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:ur(r.submitted_at,`${t}.submitted_at`)}}function rb(e,t){let r=`Native blockers[${t}]`,i=Z(e,r);ee(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=la(i.acceptance_ids,`${r}.acceptance_ids`);return jt(n,`${r}.acceptance_ids`),{owner:L(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:we(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:L(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function ib(e,t){let r=`Native verification.checks[${t}]`,i=Z(e,r);return ee(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:W(i.id,`${r}.id`),name:we(i.name,`${r}.name`),argv_display:De(i.argv_display,`${r}.argv_display`,(n,a)=>we(n,`${r}.argv_display[${a}]`)),argv_truncated:lr(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:Xs(i.cwd_ref,`${r}.cwd_ref`,!0),status:L(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:KN(i.exit_code,`${r}.exit_code`),duration_ms:j(i.duration_ms,`${r}.duration_ms`)}}function nb(e){let t="Native verification",r=Z(e,t);ee(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=De(r.checks,`${t}.checks`,ib);jt(i.map(a=>a.id),`${t}.checks IDs`);let n=W(r.identity_provider,`${t}.identity_provider`);return{candidate_id:W(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:W(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:j(r.iteration,`${t}.iteration`,1),attempt:j(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":L(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:L(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:we(r.summary,`${t}.summary`),risks:De(r.risks,`${t}.risks`,(a,o)=>we(a,`${t}.risks[${o}]`)),risks_truncated:lr(r.risks_truncated,`${t}.risks_truncated`),completed_at:ur(r.completed_at,`${t}.completed_at`)}}function Hf(e,t){let r=`Native history[${t}]`,i=Z(e,r);ee(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=la(i.unresolved_ids,`${r}.unresolved_ids`);return jt(n,`${r}.unresolved_ids`),{goal_cycle:j(i.goal_cycle,`${r}.goal_cycle`,1),iteration:j(i.iteration,`${r}.iteration`),attempt:j(i.attempt,`${r}.attempt`),outcome:L(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:we(i.summary,`${r}.summary`),completed_at:ur(i.completed_at,`${r}.completed_at`)}}function ab(e){let t="Native history_overflow.outcome_counts",r=Z(e,t),i=["pass","fail","blocked","execution-error","recovery"];return ee(r,new Set(i),t),{pass:j(r.pass,`${t}.pass`),fail:j(r.fail,`${t}.fail`),blocked:j(r.blocked,`${t}.blocked`),"execution-error":j(r["execution-error"],`${t}.execution-error`),recovery:j(r.recovery,`${t}.recovery`)}}function ob(e){let t="Native history_overflow",r=Z(e,t);ee(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=j(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:ur(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:ur(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=ab(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 sb(e){let t=new Set(e.acceptance.map(r=>r.id));for(let r of e.loop.previous_unresolved_ids)if(!t.has(r))throw new Error(`Native loop references unknown acceptance ID ${r}`);for(let r of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(r))throw new Error(`Native builder handoff references unknown ID ${r}`);for(let r of e.blockers)for(let i of r.acceptance_ids)if(!t.has(i))throw new Error(`Native blocker references unknown ID ${i}`);if(e.builder_handoff){if(!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let i=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!i&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function cb(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let r=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(r!==null&&e.loop.stage!==r)throw new Error(`Native status ${e.status} requires loop stage ${r}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(i=>i.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(i=>i.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function oe(e){let t=Z(e,"Native portable state");if(ee(t,GN,"Native portable state"),t.schema!==cr)throw new Error(`Native portable state schema must be ${cr}`);let r=W(t.name,"Native state name");if(!MN.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=De(t.spec_changes,"Native spec_changes",YN);jt(i.map(s=>s.capability),"Native spec change capabilities");let n=De(t.acceptance,"Native acceptance",ZN);jt(n.map(s=>s.id),"Native acceptance IDs");let a=De(t.history,"Native history",Hf);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:cr,name:r,language:L(t.language,["en","zh-CN"],"Native state language"),phase:L(t.phase,["shape","build","verify","archive"],"Native state phase"),status:L(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:j(t.state_version,"Native state_version",1),brief:"brief.md",...t.children_contract_hash===void 0?{}:{children_contract_hash:UN(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:L(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:XN(t.workspace),loop:QN(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:tb(t.builder_handoff),blockers:De(t.blockers,"Native blockers",rb),verification:t.verification===null?null:nb(t.verification),history:a,history_overflow:ob(t.history_overflow),verification_result:L(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:L(t.verification_report,["verification.md"],"Native verification_report"),archived:lr(t.archived,"Native archived"),created_at:ur(t.created_at,"Native created_at")};return sb(o),cb(o),o}function $t(e,t){let r=oe(e),i=Hf(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 oe({...r,history:n,history_overflow:a})}function lb(e,t){let r=(0,ca.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 X(e){let t=await VN.readFile(e,"utf8");return oe(lb(t,"Native portable state"))}async function ua(e,t,r={}){let i=oe(t);await re(e,(0,ca.stringify)(i),r)}var oa=new Map;async function ub(e,t){let r=oa.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);oa.set(e,a),await r;try{return await t()}finally{i(),oa.get(e)===a&&oa.delete(e)}}async function Ot(e){return ub(e.file,async()=>{let t=j(e.expectedStateVersion,"Native expected state version",1),r=oe(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await X(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new sa(t,i.state_version);return await ua(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await X(e.file);if(n.state_version!==t)throw new sa(t,n.state_version)}}),r})}function db(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function Je(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(db(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 Ge="comet.native.v3",Be="comet.native.v2",Le="comet.native.v1";var da="comet.native.portable-migration.v1",hb=new Set(["schema","id","change","fromSchema","status","createdAt"]),pb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,mb=/^[a-z0-9][a-z0-9-]{7,127}$/u,vb=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),gb=new Set([Le,Be,Ge]);function wb(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function yb(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 Nb(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 bb(e){return e.schema===Le?di(e):e.schema===Be?fi(e):hi(e)}function kb(e){return fb.posix.normalize(e.replaceAll("\\","/"))}function Sb(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:kb(t.source)})}function Eb(e){return e==="shape"?"shape":"build"}function Pb(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function xb(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 Df(e){let t=bb(e.state);jf(e.acceptance);let r=Eb(t.phase),i=r==="shape"?0:1,n=yb(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 oe({schema:cr,name:t.name,language:t.language,phase:r,status:"active",state_version:1,brief:"brief.md",spec_changes:Sb(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:Pb(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:Je(xb(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:Us(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function Qs(e){let t=wb(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!hb.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==da)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!mb.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!pb.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!gb.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!vb.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:da,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:Nb(t.createdAt,"Native portable migration transaction createdAt")}}function Bf(e){switch(Qs(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 fa="comet.native.archive-transaction.v4",Lf="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",Cb=new RegExp(`^portable-archive-(${Lf})\\.json$`,"u"),Rb=new RegExp(`^portable-migration-(${Lf})\\.json$`,"u"),Ab=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,_b=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Ib=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),Tb=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),jb=new Set(["capability","operation","source","content"]),qf=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Ff(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Vf(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 $b(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=Ff(e,r);if(Vf(i,jb,r),typeof i.capability!="string"||!qf.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 Ob(e){let t=Ff(e,"Native portable Archive transaction");if(Vf(t,Tb,"Native portable Archive transaction"),t.schema!==fa)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!Ab.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!qf.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"||!_b.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"||!Ib.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($b);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:fa,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:r,created_at:t.created_at}}function ha(e){let t=Cb.exec(e);if(t)return{kind:"archive",change:t[1]};let r=Rb.exec(e);return r?{kind:"migration",change:r[1]}:null}function Ht(e,t){let r=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,i=ha(r);if(!i||i.kind!==t.kind||i.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return Zs.join(e.transactionsDir,r)}async function ec(e,t){let r=ha(t);if(!r)return null;let i=await H({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=Zs.join(e.transactionsDir,t);if(r.kind==="archive"){let s=Ob(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=Qs(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 vt(e,t){let r=Ht(e,t);try{return await ec(e,Zs.basename(r))}catch(i){if(i.code==="ENOENT")return null;throw i}}function Mf(e){return e.kind==="archive"||e.journal.status!=="committed"}import Ue from"path";import{TextDecoder as Mb}from"util";import{createHash as Hb}from"node:crypto";import{constants as pa,promises as Re}from"node:fs";import Ae from"node:path";function va(e,t){let r=Ae.relative(e,t);return r===""||!Ae.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ae.sep}`)}function Db(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function Bb(e,t){return T({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Lb(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function ma(e,t){return T({...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 tc(e,t){let r=await Re.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await Re.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function qb(e,t,r){let i=Ae.resolve(e),n=Ae.resolve(t);if(!va(i,n))throw new Error(`${r} is outside its managed root`);let a=[await tc(i,r)],o=i;for(let s of Ae.relative(i,n).split(Ae.sep).filter(Boolean)){await Dt(a,r),o=Ae.join(o,s);let c=await tc(o,r);if(!va(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await Dt(a,r),a}async function Dt(e,t){for(let r of e){let i=await Re.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!Bb(r,i)||await Re.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function Fb(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 dr(e){let t=Db(e.maxBytes),r=Ae.resolve(e.file),i=await qb(e.root,Ae.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(d=>tc(Ae.resolve(d),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Dt(i,e.label);let a=await Re.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=Lb(a),s=await Re.realpath(r);if(!va(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(d=>va(d.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?pa.O_RDONLY:pa.O_RDONLY|pa.O_NOFOLLOW|pa.O_NONBLOCK,l=await Re.open(r,c);try{let d=await l.stat();await e.hooks?.afterOpen?.();let[u,f]=await Promise.all([Re.lstat(r),Re.realpath(r)]);if(await Dt(i,e.label),await Dt(n,e.label),!d.isFile()||!u.isFile()||u.isSymbolicLink()||f!==s||!ma(o,d)||!ma(o,u))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let m=await Fb(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,h,p]=await Promise.all([l.stat(),Re.lstat(r),Re.realpath(r)]);if(await Dt(i,e.label),await Dt(n,e.label),!h.isFile()||h.isSymbolicLink()||p!==s||!ma(o,v)||!ma(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:m,hash:Hb("sha256").update(m).digest("hex"),size:m.length}}finally{await l.close()}}var Wb=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),zb=new Set(["id","type","source","target","staged","backup"]),Jb=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),Gb=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var Jf=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var Ub=256*1024,zR=1024*1024,JR=16*1024;var GR=64*1024*1024;var Kb=new Mb("utf-8",{fatal:!0});function wa(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ya(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 Gf(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function rc(e,t){if(typeof e!="string"||e.length===0||Ue.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function ga(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function Wf(e,t){if(rc(e,t),e.includes("\\")||e!==Ue.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 Yb(e,t){let r=wa(e,`transaction operations[${t}]`);if(ya(r,zb,`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`);rc(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&rc(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 Uf(e){let t=wa(e,"Native Archive transaction journal");if(ya(t,Jb,"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"||!Jf.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(!Gf(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(ga(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=wa(s,`Archive transaction operations[${c}]`);if(ya(l,Gb,`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`);Wf(l.target,`Archive transaction operation ${l.id} target`);for(let d of["source","staged","backup"])l[d]!==void 0&&Wf(l[d],`Archive transaction operation ${l.id} ${d}`);if(l.expectedTargetHash!==null&&ga(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(ga(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`);ga(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 Xb(e){let t=wa(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Uf(t);if(ya(t,Wb,"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"||!Jf.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!Ue.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!Ue.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(!Gf(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(Yb),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 Qb(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return Ue.join(e.transactionsDir,t)}function Kf(e,t){let r=Qb(e,t);return{directory:r,journal:Ue.join(r,"transaction.json"),events:Ue.join(r,"events.jsonl"),staged:Ue.join(r,"staged"),backups:Ue.join(r,"backups")}}async function nc(e,t){let r=Kf(e,t);return await Promise.all(Object.values(r).map(i=>D(e.runtimeDir,i))),r}async function ac(e,t,r={}){let i=await nc(e,t),n=await dr({root:e.runtimeDir,file:i.journal,maxBytes:Ub,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(Kb.decode(n.bytes)),o=Xb(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function tk(e,t,r){let i;try{i=await Zb.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 ac(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of i)if(ha(n.name))try{let a=await ec(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(Mf(a))return!0}catch{return!0}return!1}async function rk(e,t){let r=Date.now()+5e3,i=ek.join(e.locksDir,"root-move.lock");for(;;)try{return await ta(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await Pf(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 U(e,t,r,i){let n=await rk(e,t);try{if(await ci(e.projectRoot),await tk(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{await ra(n)}}import{createHash as ik}from"crypto";function ye(e){return ik("sha256").update(e).digest("hex")}var pA={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024};var mA=8*1024*1024;var vA=64*1024,gA=64*1024;var wA={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},yA={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};var NA=(1n<<256n)-1n;var uk=Sr(nr(),1);var HA=4*1024*1024;var dk=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 Yf(e,t){return(...r)=>{let i=dk;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 FA=Yf("hookWritePolicy",async e=>(await Hs(e))?.hook??{allow_paths:[]});var B_=256*1024;var X_={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 fr from"node:path";var pi=/^[a-f0-9]{64}$/u,Qf=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,pk=16*1024,fI=process.platform;function mk(e,t){let r=fr.relative(e,t);return fr.isAbsolute(r)||r===".."||r.startsWith(`..${fr.sep}`)?null:r.replaceAll("\\","/")||"."}function Zf(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function eh(e,t){if(e.length===0||Zf(e)||e.includes("\\")||fr.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=fr.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function vk(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 oc(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||Zf(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(oc(e.changeBranch,"Native workspace change branch"),oc(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 wk(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"||!Qf.test(t.baseCommit)||typeof t.targetCommit!="string"||!Qf.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");oc(t.targetBranch,"Native workspace Git target branch")}function yk(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"||!pi.test(String(t.projectRootId))||!pi.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");vk(t.capturedAt),eh(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&&!pi.test(String(t.projectRootPathId))||a&&!pi.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!pi.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&wk(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 Nk(e,t){return fr.join($e(e,t),"workspace.json")}function bk(e,t){let r=Nk(e,t),i=Oe(e,r),n=mk(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:eh(n,"Native workspace file ref")}}async function kk(e,t){try{let r=bk(e,t),i=await H({root:r.root,ref:r.ref,maxBytes:pk});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function mi(e,t){let r=await kk(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(yk(r),r)}var rh=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],Pk=new Set(rh),ih=new Set([...rh,"minimum_runtime_version","revision"]),xk=new Set([...ih,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),Ck=new Set(["capability","operation","source","base_hash"]),Rk=new Set(["shape","build","verify","archive"]),Ak=new Set(["implicit","confirmed"]),_k=new Set(["pending","pass","fail"]),Bt="comet-state.yaml",cc=/^[a-f0-9]{64}$/u,nh=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Ik=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,lc=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"},pr=class extends Error{constructor(r,i){super(r!==Ge||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"},Na=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"},vi=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"},ba=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"},DI=Ln("en");function wi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function ah(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 dc(e){if(!nh.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Tk(e){if(!nh.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function oh(e,t){if(e.length===0||hr.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function jk(e,t){let r=wi(e,`spec_changes[${t}]`);if(ah(r,Ck,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(Tk(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"&&oh(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"||!cc.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"||!cc.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 $k(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 fc(e,t){if(ah(e,t,Bt),typeof e.name!="string")throw new Error("Native change name is required");if(dc(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"||!Rk.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&&!Ak.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(jk),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"||!_k.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"&&oh(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!$k(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 di(e){let t=wi(e,Bt);if(t.schema!==Le)throw new Error(`Expected ${Le}`);return{schema:Le,...fc(t,Pk)}}function gi(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function sc(e,t,r){if(e===null)return null;let i=typeof e=="string"?Ik.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 Ok(e){if(e==null)return null;if(typeof e!="string"||!cc.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function Hk(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 fi(e){let t=wi(e,Bt);if(t.schema!==Be)throw new Error(`Expected ${Be}`);if(gi(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Be} minimum_runtime_version must be 2`);return{schema:Be,minimum_runtime_version:2,revision:gi(t.revision,"Native v2 revision"),...fc(t,ih)}}function hi(e){let t=wi(e,Bt);if(t.schema!==Ge){if(t.schema===Le||t.schema===Be){let o=t.schema===Le?di(t):fi(t);throw new lc(o.name,o.schema)}throw new pr(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=gi(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new pr(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=gi(t.revision,"Native revision"),n=fc(t,xk),a=Ok(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Ge,minimum_runtime_version:3,revision:i,verification_protocol:Hk(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:sc(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:sc(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:sc(t.partial_allowance,"Native partial_allowance","allowances")}}function Dk(e){let t=wi(e,Bt);if(t.schema===Le){let n=di(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Ge}`}}if(t.schema===Be){let n=fi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Ge}`}}if(t.schema!==Ge){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 pr(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=gi(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new pr(t.schema,r).message};let i=hi(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}function fe(e,t){dc(t);let r=hr.join(e.changesDir,t);if(!V(e.changesDir,r))throw new Error("Native change path escaped");return r}async function Bk(e,t=hr.dirname(e)){let r=hr.relative(t,e).split(hr.sep).join("/"),i=await H({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,uc.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 ka(e,t){let r=hr.join(fe(e,t),Bt);await D(e.nativeRoot,r);let i=Dk(await Bk(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}import{promises as qt}from"node:fs";import Xe from"node:path";var bc=Sr(nr(),1);import{promises as Nc}from"node:fs";import se from"node:path";import{execFileSync as Lk}from"node:child_process";var qk=3e4,Fk=8*1024*1024,hc=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 sh(e,t){try{return Lk("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:qk,maxBuffer:Fk,windowsHide:!0})}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new hc(e,t,i)}}function P(e,t){return sh(e,t).trim()}function wt(e){return P(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function pc(e){let t=sh(e,["status","--porcelain=v1","-z","--untracked-files=all"]);if(!t)return[];let r=t.split("\0").filter(Boolean),i=[];for(let n=0;n<r.length;n+=1){let a=r[n];if(a.length<4)throw new Error("Git status returned an invalid porcelain record");if(i.push(a.slice(3).replaceAll("\\","/")),a[0]==="R"||a[0]==="C"||a[1]==="R"||a[1]==="C"){let o=r[n+1];if(!o)throw new Error("Git status returned an incomplete rename record");i.push(o.replaceAll("\\","/")),n+=1}}return[...new Set(i)].sort()}function ch(e,t){try{let i=P(e,["config","--get",`branch.${t}.remote`]);if(i&&i!==".")return i}catch{}let r=P(e,["remote"]).split(/\r?\n/u).map(i=>i.trim()).filter(Boolean);if(r.includes("origin"))return"origin";if(r.length===1)return r[0];throw new Error(r.length===0?"Native workspace finish requires a configured Git remote":`Native workspace finish requires an unambiguous Git remote: ${r.join(", ")}`)}import K from"node:path";import{promises as Pa}from"node:fs";import Sa from"node:path";function lh(...e){if(e.length===0)return Sa.resolve();if(Sa.win32.isAbsolute(e[0])){let t=Sa.win32.resolve(...e);return process.platform==="win32"?t:t.replace(/\\/gu,"/")}return Sa.resolve(...e)}var Ea=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};var vc="comet.native.supervisor.v2",Vk=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function Mk(e,t){let r=K.relative(K.resolve(e),K.resolve(t));return r===""||!K.isAbsolute(r)&&!r.startsWith(`..${K.sep}`)}function Wk(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native Supervisor parent name: ${e}`);return`comet/supervisor/${e}/integration`}function zk(e,t,r){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(r))throw new Error("Native Supervisor parent and child names are invalid");return lh(e,".worktrees",`${t}-${r}`)}function hh(e,t){return K.join(ve(e,t),"supervisor")}function ph(e,t){return K.join(hh(e,t),"state.json")}function mh(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native Supervisor state must be an object");let t=e;if(t.schema!==vc)throw new Error(`Native Supervisor state schema must be ${vc}`);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(mr(t.integration.targetCommit,"Native Supervisor target commit"),mr(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&&mr(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(mr(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 yt(e,t){try{let r=await Pa.readFile(ph(e,t),"utf8"),i=JSON.parse(r);return mh(i),i}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Lt(e,t){mh(t),await Pa.mkdir(e.changesRuntimeDir,{recursive:!0}),await J(ph(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function mr(e,t){if(!Vk.test(e))throw new Error(`${t} must be a Git commit`)}function yi(e){return structuredClone(e)}function gc(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function vh(e){mr(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:vc,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 wc(e){let t=Wk(e.parent),r=kt(e.paths.projectRoot,t);if(!r)return null;let i=kt(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=le(e.paths.projectRoot).map(o=>K.resolve(o)).find(o=>I(o).currentBranch===t);if(!n)return null;let a=vh({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 gc(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function xa(e){if(!wt(e.integration.worktree))throw new Error("Native Supervisor integration worktree must be clean");let t=P(e.integration.worktree,["rev-parse","--show-toplevel"]);if(K.resolve(t)!==K.resolve(e.integration.worktree))throw new Error("Native Supervisor integration worktree identity is invalid");let r=P(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 P(e.integration.worktree,["rev-parse","HEAD"])}async function Jk(e){let t=kt(e.paths.projectRoot,e.state.integration.targetBranch);if(!t||t===e.state.integration.targetCommit)return null;let r=e.state;if(xa(r)!==r.integration.headCommit)throw new Error("Native Supervisor integration head changed before target refresh");try{P(r.integration.worktree,["merge","--no-edit",r.integration.targetBranch])}catch(o){throw new Error(`Native Supervisor target drift requires conflict resolution in ${r.integration.worktree}`,{cause:o})}let n=P(r.integration.worktree,["rev-parse","HEAD"]),a=yi(r);return a.integration.headCommit=n,a.finalVerification={status:"pending",summary:null},gc(a,{kind:"target-refreshed",child:null,runId:null,summary:`Target ${r.integration.targetBranch} was refreshed before delivery`}),a.stateVersion+=1,await Lt(e.paths,a),a}function Gk(e,t){if(mr(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=yi(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 gh(e){let t=xa(e);if(t===e.integration.headCommit)return e;try{P(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=yi(e);return r.integration.headCommit=t,gc(r,{kind:"integration-head-reconciled",child:null,runId:null,summary:"Parent-level commits were included in final verification"}),r.stateVersion+=1,r}function wh(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=xa(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 Gk(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)}})}async function Ni(e){let r=await yt(e.paths,e.state.parent)??e.state;if(r.stateVersion!==e.state.stateVersion)throw new Error("Native Supervisor state changed before delivery; reload status first");if(r.finalVerification.status!=="passed")throw new Error("Native Supervisor delivery requires a passed final verification");if(!r.children.every(({status:v})=>v==="integrated"||v==="archived"))throw new Error("Native Supervisor delivery requires every child to be integrated");let n=le(e.paths.projectRoot).map(v=>K.resolve(v)).find(v=>I(v).currentBranch===r.integration.targetBranch);if(!n)throw new Error(`Native Supervisor target branch worktree is unavailable: ${r.integration.targetBranch}`);if(!wt(n))throw new Error(`Native Supervisor target worktree is not clean: ${n}`);let a=P(n,["rev-parse","HEAD"]);if((()=>{try{return P(n,["merge-base","--is-ancestor",r.integration.headCommit,a]),!0}catch{return!1}})()){let v=await dh({paths:e.paths,state:r,targetCommit:a});if(await fh({paths:e.paths,plan:v}),r.children.every(({status:p})=>p==="archived"))return await mc(e.paths,r.parent),{state:r,targetRoot:n,targetCommit:a};let h=yi(r);for(let p of h.children)p.status="archived";return h.stateVersion+=1,await Lt(e.paths,h),await mc(e.paths,r.parent),{state:h,targetRoot:n,targetCommit:a}}let c=xa(r);if(c!==r.integration.headCommit)throw new Error("Native Supervisor integration head changed after final verification");let l=kt(e.paths.projectRoot,r.integration.targetBranch),d=(()=>{if(!l)return!1;try{return P(r.integration.worktree,["merge-base","--is-ancestor",l,c]),!0}catch{return!1}})();if(l!==c&&!d&&l!==r.integration.targetCommit&&await Jk({paths:e.paths,state:r}))throw new Error("Native Supervisor target changed; parent integration checks must be rerun before delivery");let u=await dh({paths:e.paths,state:r,targetCommit:c});l!==c&&P(n,["merge","--ff-only",r.integration.branch]);let f=P(n,["rev-parse","HEAD"]);if(f!==c)throw new Error("Native Supervisor target did not receive the verified integration head");let m=yi(r);for(let v of m.children)v.status="archived";return await fh({paths:e.paths,plan:u}),m.stateVersion+=1,await Lt(e.paths,m),await mc(e.paths,r.parent),{state:m,targetRoot:n,targetCommit:f}}function yh(e,t){return K.join(hh(e,t),"cleanup.json")}function uh(e){let t=le(e.paths.projectRoot).map(s=>K.resolve(s)),r=K.resolve(process.cwd()),i=[{root:e.state.integration.worktree,branch:e.state.integration.branch},...e.state.children.map(({name:s})=>({root:zk(e.paths.projectRoot,e.state.parent,s),branch:`comet/supervisor/${e.state.parent}/${s}`}))].map(s=>({...s,root:K.resolve(s.root)})),n=e.targetCommit,a=[e.state.integration.branch,...e.state.children.map(({name:s})=>`comet/supervisor/${e.state.parent}/${s}`)],o=i.flatMap(s=>{let c=t.find(l=>l===s.root);return c?[{...s,root:c}]:[]});for(let s of o){if(Mk(s.root,r))throw new Error(`Native Supervisor cannot clean the current worktree: ${s.root}`);if(!wt(s.root))throw new Error(`Native Supervisor cleanup requires a clean worktree: ${s.root}`);let c=I(s.root).currentBranch;if(!c)throw new Error(`Native Supervisor worktree is detached: ${s.root}`);if(c!==s.branch)throw new Error(`Native Supervisor cleanup found unexpected branch ${c} for ${s.root}; expected ${s.branch}`);try{P(e.paths.projectRoot,["merge-base","--is-ancestor",c,n])}catch{throw new Error(`Native Supervisor cleanup found unintegrated branch ${c}`)}}for(let s of a)if(Pr(e.paths.projectRoot,s))try{P(e.paths.projectRoot,["merge-base","--is-ancestor",s,n])}catch{throw new Error(`Native Supervisor cleanup found unintegrated branch ${s}`)}return{parent:e.state.parent,targetCommit:e.targetCommit,worktrees:o.map(({root:s})=>s),expectedBranches:Object.fromEntries(o.map(({root:s,branch:c})=>[s,c])),branches:a}}async function dh(e){let t=yh(e.paths,e.state.parent);try{let i=JSON.parse(await Pa.readFile(t,"utf8"));if(i.parent===e.state.parent&&i.targetCommit===e.targetCommit&&Array.isArray(i.worktrees)&&i.expectedBranches&&typeof i.expectedBranches=="object"&&Array.isArray(i.branches)){let n=uh(e);return{parent:i.parent,targetCommit:i.targetCommit,worktrees:[...new Set([...i.worktrees,...n.worktrees])],expectedBranches:{...i.expectedBranches,...n.expectedBranches},branches:[...new Set([...i.branches,...n.branches])]}}}catch(i){if(i.code!=="ENOENT")throw i}let r=uh(e);return await J(t,r,{containedRoot:e.paths.changesRuntimeDir}),r}async function fh(e){for(let t of e.plan.worktrees){if(!le(e.paths.projectRoot).map(a=>K.resolve(a)).includes(K.resolve(t)))continue;let i=e.plan.expectedBranches[t];if(!i)throw new Error(`Native Supervisor cleanup has no expected branch for ${t}`);let n=I(t).currentBranch;if(n!==i)throw new Error(`Native Supervisor cleanup found unexpected branch ${n??"(detached)"} for ${t}; expected ${i}`);P(e.paths.projectRoot,["worktree","remove",t])}for(let t of e.plan.branches)Pr(e.paths.projectRoot,t)&&P(e.paths.projectRoot,["branch","-d",t])}async function mc(e,t){await Pa.rm(yh(e,t),{force:!0})}function Nh(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 bh="children.yaml",vr="comet.native.children.v1",gr="comet.native.children.v2",Rh=gr,Uk=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,kh=new Set(["schema","children"]),Kk=new Set(["schema","acceptance_index","children"]),Yk=new Set(["name","depends_on","covers"]),Xk=new Set(["name","summary","depends_on"]),Qk=new Set(["name","depends_on","covers"]);function Ra(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function Ca(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 Sh(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 yc(e,t){let r=se.normalize(se.resolve(e)),i=se.normalize(se.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function Zk(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 Eh(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 eS(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===Rh&&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 d=s.get(l),u=e.acceptance_index[l];d&&u&&(u.source!==d.source||u.text!==d.text)&&i.mismatched.push(l)}let c=new Set(o);for(let l of e.children)i.unknownCovers.push(...l.covers.filter(d=>!c.has(d)));return i.uncovered=o.filter(l=>!Ph(e.children,l)),xh(i)?i:null}if(e.schema===vr&&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=>!Ph(e.children,a)),xh(i)?i:null}return null}function Ph(e,t){return e.some(r=>r.covers.includes(t))}function xh(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function kc(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 tS(e){let t=Ra(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=Ra(n,`Native children acceptance_index.${i}`);if(Ca(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 rS(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 d=c.get(l);if(!d)continue;let u=e[l];if(u.source!==d.source||u.text!==d.text){let f=["source","text"].filter(m=>u[m]!==d[m]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${f.join(", ")} exactly from the current acceptance catalog`)}}}function iS(e,t,r={}){let i=(0,bc.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=Ra(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==vr&&a!==gr)throw Ca(n,kh,"Native children contract"),new Error(`Native children schema must be ${vr} or ${gr}`);let o=a===vr?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(Ca(n,o==="indexed-v2"?Kk:kh,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let c=n.children.map((f,m)=>{let v=Ra(f,`Native child ${m}`);if(Ca(v,o==="indexed-v2"?Qk:o==="summary-v2"?Xk:Yk,`Native ${s} child fields (child ${m})`),typeof v.name!="string"||!Uk.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:Sh(v.depends_on,`Native child ${v.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?Sh(v.covers,`Native child ${v.name} covers`):[]}}),l=c.map(({name:f})=>f);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let d=new Set(l);for(let f of c){let m=f.depends_on.filter(v=>!d.has(v));if(m.length>0)throw new Error(`Native child ${f.name} depends on unknown child: ${m.join(", ")}`)}Zk(c);let u=r.policy==="advisory";if(a===Rh){if(o==="indexed-v2"){let f=tS(n.acceptance_index);u||rS(f,t,r);let m=Object.keys(f);return u||Eh(c,m,m),{schema:gr,acceptance_index:f,children:c}}return{schema:gr,children:c}}return t&&!u&&Eh(c,t),{schema:vr,children:c}}async function Aa(e){let t=se.join(e.changeDir,bh);try{await Nc.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await H({root:e.changeDir,ref:bh}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=iS(r.text,e.acceptanceIds,n);return{contract:a,size:r.size,drift:i?eS(a,e.acceptanceIds,e.validation??{}):null}}function nS(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 aS(e){let t=nS(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 Ah(e){try{let t=await H({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return aS(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Sc(e){return ae("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 _h(e){let t=le(e.projectRoot);t.some(i=>yc(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>se.resolve(n)))]){let n=await de(i);n&&r.push({projectRoot:i,paths:await ze(i,n.native.artifact_root),parent:yc(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function Ih(e){let t=await _h(e.paths),r=[],i=[],n=new Map;for(let a of t){let o;try{o=await Nc.readdir(a.paths.changesDir,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of o){if(!s.isDirectory()||s.isSymbolicLink()||s.name===e.childName)continue;let c=se.join(a.paths.changesDir,s.name),l;try{l=await X(se.join(c,"comet-state.yaml"))}catch{continue}if(l.phase!=="build"||l.status!=="active")continue;let d=await Aa({changeDir:c,...l.acceptance.length>0?{acceptanceIds:l.acceptance.map(({id:u})=>u)}:{}});!d||d.contract.schema!==vr||d.contract.children.some(({name:u})=>u===e.childName)&&n.set(l.name,[...n.get(l.name)??[],{source:a,state:l}])}}for(let[a,o]of n){let s=e.targetBranch===null?[]:o.filter(({state:m})=>m.workspace.target_branch===e.targetBranch);if(e.targetBranch===null){i.push(`Native Supervisor Child ${e.childName} has no target branch to match parent ${a}`);continue}let c=s.find(({source:m,state:v})=>I(m.projectRoot).currentBranch===v.workspace.change_branch);if(!c){let m=o.find(({state:v})=>v.workspace.target_branch!==e.targetBranch);if(m)i.push(`Native Supervisor parent ${a} targets ${m.state.workspace.target_branch??"(missing)"}, not ${e.targetBranch}`);else{let v=s[0]?.state??o[0].state;i.push(`Native Supervisor parent ${a} is not bound to branch ${v.workspace.change_branch}`)}continue}let{source:l,state:d}=c,u=l.paths,f=await Ec({paths:u,state:d});if(!f)i.push(`Native Supervisor parent ${a} has no readable Child inspection`);else if(!f.confirmed)i.push(`Native Supervisor parent ${a} requires Shape confirmation`);else if(f.allDone)r.push({paths:u,state:d,inspection:f});else{let m=f.children.filter(({status:v})=>v!=="done").map(({name:v,status:h,message:p})=>`${v}=${h}${p?` (${p})`:""}`).join(", ");i.push(`Native Supervisor parent ${a} is not ready to advance: ${m||"Child facts are incomplete"}`)}}return n.size===0&&i.push(`Native Supervisor Child ${e.childName} has no active v1 parent declaring it`),n.size>1&&i.push(`Native Supervisor Child ${e.childName} has multiple active parents: ${[...n.keys()].join(", ")}`),r.length===1&&i.length===0?{candidate:r[0],blockers:i}:(r.length>1&&i.push(`Native Supervisor Child ${e.childName} has multiple eligible parents: ${r.map(({state:a})=>a.name).join(", ")}`),{candidate:null,blockers:i})}async function oS(e,t){let r=se.join(e.paths.changesDir,t,"comet-state.yaml");try{return await X(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function sS(e,t){let r;try{r=await Nc.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=se.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await X(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function cS(e,t,r){let i=se.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${se.sep}`))return null;let n=i.split(se.sep).join("/");try{let a=(0,bc.parseDocument)(P(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:oe(a.toJS({mapAsMap:!1}))}catch{return null}}function lS(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 Ch(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Ec(e){let t=se.join(e.paths.changesDir,e.state.name),r=await Ah(t),i=await Aa({changeDir:t,validation:kc(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=Sc({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===gr){let p=await yt(e.paths,e.state.name);if(!p){let g=e.state.workspace.target_branch??e.state.workspace.change_branch;if(g){let N=await wc({paths:e.paths,parent:e.state.name,targetBranch:g,contract:i.contract});N&&(p=N,await Lt(e.paths,N))}}if(p){let g=Nh(p);return e.state.children_contract_hash!==n||i.drift?{...g,schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:!1,readyChildren:[],allDone:!1,children:g.children.map(N=>({...N,message:i.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...g,schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o}}let w=new Map(i.contract.children.map(g=>[g.name,g])),y=i.contract.children.map(g=>({name:g.name,summary:g.summary,dependsOn:[...g.depends_on],covers:[],status:o&&g.depends_on.every(N=>i.contract.children.filter(({name:k})=>k!==g.name).every(({name:k})=>k!==N))?"ready":"pending",phase:null,projectRoot:null,message:o?null:"Parent Shape confirmation is required"}));for(let g of y){if(g.status!=="ready")continue;w.get(g.name).depends_on.length>0&&(g.status="pending")}return{schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:y,readyChildren:y.filter(({status:g})=>g==="ready").map(({name:g})=>g),allDone:!1}}let s=await _h(e.paths),c=new Set(i.contract.children.map(({name:p})=>p)),l=new Map,d=new Map;for(let p of s){let w=p.parent&&a?`refs/heads/${a}`:"HEAD";for(let y of await sS(p,c)){let g={...y,source:p,committedState:cS(p,y.file,w)};l.set(y.state.name,[...l.get(y.state.name)??[],g])}for(let y of c){let g=await oS(p,y);g&&d.set(y,[...d.get(y)??[],{source:p,state:g}])}}let u=new Map;for(let p of i.contract.children){let w=(l.get(p.name)??[]).find(({source:N,committedState:k})=>N.parent&&k?.name===p.name&&Ch(k,a));if(w){u.set(p.name,{kind:"done",phase:w.state.phase,projectRoot:w.source.projectRoot,message:null});continue}let y=l.get(p.name)?.[0];if(y){u.set(p.name,{kind:"blocked",phase:y.state.phase,projectRoot:y.source.projectRoot,message:`Native child ${p.name} is archived but not merged into parent branch ${a??"(missing)"}`});continue}let g=d.get(p.name)??[];g.length>1?u.set(p.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${p.name} has multiple active workspace owners`}):g[0]&&u.set(p.name,lS(g[0].state,g[0].source,a))}let f=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 y=f.get(p),N=y.depends_on.map(v).every(({status:ce})=>ce==="done"),k=u.get(p),E=k?.kind==="active"&&N?y.depends_on.filter(ce=>!(l.get(ce)??[]).some(({source:et,committedState:O})=>yc(et.projectRoot,k.projectRoot)&&O?.name===ce&&Ch(O,a))):[],R,S=k?.message??null;k?.kind==="done"?(R=N?"done":"blocked",N||(S=`Native child ${p} was merged before its dependencies`)):k?.kind==="active"?(R=N&&E.length===0?"active":"blocked",N?E.length>0&&(S=`Native child ${p} does not include merged dependencies: ${E.join(", ")}`):S=`Native child ${p} started before its dependencies merged`):k?.kind==="blocked"?R="blocked":(R=o&&N?"ready":"pending",o||(S="Parent Shape confirmation is required"));let $={name:p,summary:y.summary,dependsOn:[...y.depends_on],covers:[...y.covers],status:R,phase:k?.phase??null,projectRoot:k?.projectRoot??null,message:S};return m.set(p,$),$},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")}}import{existsSync as uS}from"node:fs";import bi from"node:path";var dS=/[&|<>()^%"!\r\n]/u,kT=["$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 Th(e,t){let r=t.toLowerCase();return Object.entries(e).find(([i,n])=>i.toLowerCase()===r&&n!==void 0)?.[1]}function fS(e){let t=(Th(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function hS(e,t,r){let n=bi.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(Th(t,"PATH")??"").split(bi.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=bi.win32.extname(e)?[e]:fS(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(c=>s?bi.join(s,c):bi.resolve(r,c)))}function jh(e,t,r){return hS(e,t,r).find(i=>uS(i))??e}function $h(e){if(e.some(t=>dS.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}var Si="skill-coordinated";function gS(e){return e.state_version+1}function wS(e){return e.map(t=>({...t,result:"pending",reason:null}))}function yS(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:Je(e.summary),completed_at:e.completedAt}}function Pc(e){let t=oe(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=$t(t,yS({state:t,outcome:"recovery",summary:e.reason,completedAt:r})),n=new Set(t.loop.previous_unresolved_ids),a=n.size===0?wS(t.acceptance):t.acceptance.map(o=>n.has(o.id)?{...o,result:"pending",reason:null}:o);return oe({...i,phase:"build",status:"active",state_version:gS(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 Hh}from"node:fs";import Ei from"node:path";function _a(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ia(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 qe(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 Oh(e,t){return e===null?null:qe(e,t)}function ja(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 NS(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 bS(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Ta(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function xc(e,t){if(e===null)return null;let r=qe(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function Cc(e,t){let r=qe(e,t);if(!Ei.isAbsolute(r))throw new Error(`${t} must be absolute`);return Ei.resolve(r)}function kS(e,t){let r=`Native local checks[${t}]`,i=_a(e,r);if(Ia(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,d)=>qe(l,`${r}.argv[${d}]`,!0)),a=Ta(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=xc(i.startedAt,`${r}.startedAt`),s=xc(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=ja(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);return{id:qe(i.id,`${r}.id`),name:qe(i.name,`${r}.name`),operationId:qe(i.operationId,`${r}.operationId`),status:a,repeatable:bS(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:ja(i.executionCount,`${r}.executionCount`),argv:n,cwd:Cc(i.cwd,`${r}.cwd`),exitCode:NS(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:qe(i.log,`${r}.log`)}}function Rc(e){let t="Native local execution state",r=_a(e,t);if(Ia(r,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),r.schema!==ui)throw new Error(`Native local execution schema must be ${ui}`);let i=_a(r.workspace,"Native local workspace");Ia(i,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(r.execution!==null){let o=_a(r.execution,"Native local execution");Ia(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=xc(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:qe(o.operationId,"Native local execution.operationId"),stage:Ta(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Ta(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Oh(o.executionId,"Native local execution.executionId"),status:Ta(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:ja(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(kS);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:ui,change:qe(r.change,"Native local change"),basedOnStateVersion:ja(r.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:Cc(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Cc(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Oh(i.branch,"Native local workspace.branch")},execution:n,checks:a}}function Ke(e){return Rc({schema:ui,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:Ei.resolve(e.projectRoot),worktreeRoot:Ei.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function Ac(e){let t;try{t=await Hh.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 Rc(r)}async function Fe(e,t,r={}){let i=Rc(t);await Hh.mkdir(Ei.dirname(e),{recursive:!0}),await J(e,i,r)}import{promises as SS}from"node:fs";function Nt(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
|
|
152
|
-
`).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function
|
|
153
|
-
`),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
|
|
154
|
-
`),s=e.blockers.length===0?`_${n("None.","无。")}_`:e.blockers.map(u=>`- **${u.owner}**: ${
|
|
155
|
-
`),c=e.verification.risks.length===0?`_${n("None reported.","未报告风险。")}_`:e.verification.risks.map(u=>`- ${
|
|
156
|
-
`),l=e.history.length===0?`_${n("No previous iterations.","没有之前的迭代。")}_`:[`| ${n("Goal cycle","目标周期")} | ${n("Iteration","迭代")} | ${n("Attempt","尝试")} | ${n("Outcome","结果")} | ${n("Unresolved","未解决项")} | ${n("Summary","摘要")} | ${n("Completed","完成时间")} |`,"| ---: | ---: | ---: | --- | --- | --- | --- |",...e.history.map(u=>`| ${u.goal_cycle} | ${u.iteration} | ${u.attempt} | ${u.outcome} | ${u.unresolved_ids.join(", ")||"—"} | ${
|
|
157
|
-
`),
|
|
149
|
+
`,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=jf(l,t);else if(r)$f(l)&&(r=!1);else if(i!==null)new RegExp(`</${i}\\s*>`,"iu").test(l)&&(i=null);else{let u=jf(l,null);if(u!==null)t=u;else{let d=l.trimStart();if(d.startsWith("<!--")&&!$f(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 mi(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function Hf(e,t,r,i=[],n="content-hash"){let a=mi(r),o=t.replaceAll("\\","/").trim(),s=i.map(mi);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-${V(YN,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function Df(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 XN(e){let t=null,r=null,i=0,n=0;for(let{line:a,body:o,index:s}of sa(e)){n=s+1;let c=o?Of(a):null;c?.level===1&&(Hs(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 ec(e,t="brief.md",r=ca.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let n=XN(e);if(n===null)return[];let a=null;for(let{line:l,body:f,index:u}of sa(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 sa(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(),Df(o.map(l=>Hf("brief-example",t,l.join(`
|
|
150
|
+
`),[],i)),"Brief",i)}function tc(e,t="spec.md",r=ca.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(Hf("spec-scenario",t,[o.title,...o.body].join(`
|
|
151
|
+
`),o.context,i)),o=null}};for(let{line:c,body:l}of sa(e)){let f=l?Of(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=mi(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(),Df(n,"Specification",i)}var QN=/^A[1-9]\d*$/u;function Lf(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||Bf.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||Bf.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function ZN(e,t){return e.localeCompare(t,"en")}function la(e){let t=Lf(e.briefSource??"brief.md","Native brief source"),r=[...e.specs??[]].sort((a,o)=>ZN(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=ec(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of r){let o=Lf(a.source,`Native spec source for ${a.capability}`);i.push(...tc(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=mi(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 qf(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(!QN.test(t[r])||t[r]!==`A${r+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function Ff(e,t){return e.length===t.length&&e.every((r,i)=>r.source===t[i]?.source&&r.text===t[i]?.text)}var fa=Ar(sr(),1);import{promises as eb}from"node:fs";var dr="comet.native.v4",vi="comet.native.local-execution.v4";var Vf=["multi-session","single-session"];function rc(){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 tb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,rb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ib=/^A[1-9][0-9]*$/u,nb=/^[a-f0-9]{64}$/u,ab=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"]),da=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 te(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function re(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 W(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 nc(e,t){return e===null?null:W(e,t)}function Mf(e,t){let r=W(e,t);if(!nb.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function fr(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function O(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 ob(e,t){return e===null?null:O(e,t,Number.MIN_SAFE_INTEGER)}function L(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Be(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 Be(e,t,(r,i)=>W(r,`${t}[${i}]`))}function Ht(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function hr(e,t){let r=W(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function ac(e,t,r=!1){let i=W(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 ye(e,t){let r=te(e,t);return re(r,new Set(["text","truncated"]),t),{text:W(r.text,`${t}.text`,{empty:!0}),truncated:fr(r.truncated,`${t}.truncated`)}}function sb(e,t){let r=`Native spec_changes[${t}]`,i=te(e,r);re(i,new Set(["capability","operation","source"]),r);let n=W(i.capability,`${r}.capability`);if(!rb.test(n))throw new Error(`${r}.capability is invalid`);let a=L(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:ac(i.source,`${r}.source`);if(a==="remove"&&o!==null)throw new Error(`${r} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${r} ${a} requires a source`);return{capability:n,operation:a,source:o}}function cb(e){let t="Native workspace",r=te(e,t);re(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=L(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=nc(r.change_branch,`${t}.change_branch`),a=nc(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:L(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 lb(e){let t="Native loop",r=te(e,t);re(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`);Ht(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:L(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:L(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:O(r.goal_cycle,`${t}.goal_cycle`,1),iteration:O(r.iteration,`${t}.iteration`),attempt:O(r.attempt,`${t}.attempt`),retry_epoch:O(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:O(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:O(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:O(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:nc(r.next_action,`${t}.next_action`)}}function ub(e,t){let r=`Native acceptance[${t}]`,i=te(e,r);re(i,new Set(["id","source","text","result","reason"]),r);let n=W(i.id,`${r}.id`);if(!ib.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:ac(i.source,`${r}.source`),text:W(i.text,`${r}.text`),result:L(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:ye(i.reason,`${r}.reason`)}}function db(e,t){let r=`Native builder_handoff.checks[${t}]`,i=te(e,r);return re(i,new Set(["name","result","note"]),r),{name:ye(i.name,`${r}.name`),result:L(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:ye(i.note,`${r}.note`)}}function fb(e){let t="Native builder_handoff",r=te(e,t);re(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`);Ht(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:te(r.review,`${t}.review`);return n&&re(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:W(r.candidate_id,`${t}.candidate_id`),identity_provider:W(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:W(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:O(r.iteration,`${t}.iteration`,1),summary:ye(r.summary,`${t}.summary`),addressed_acceptance_ids:i,checks:Be(r.checks,`${t}.checks`,db),checks_truncated:fr(r.checks_truncated,`${t}.checks_truncated`),known_limits:Be(r.known_limits,`${t}.known_limits`,(a,o)=>ye(a,`${t}.known_limits[${o}]`)),known_limits_truncated:fr(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:L(n.status,["passed"],`${t}.review.status`),summary:ye(n.summary,`${t}.review.summary`),reviewer_execution_ref:W(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:hr(r.submitted_at,`${t}.submitted_at`)}}function hb(e,t){let r=`Native blockers[${t}]`,i=te(e,r);re(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=ha(i.acceptance_ids,`${r}.acceptance_ids`);return Ht(n,`${r}.acceptance_ids`),{owner:L(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:ye(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:L(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function pb(e,t){let r=`Native verification.checks[${t}]`,i=te(e,r);return re(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:W(i.id,`${r}.id`),name:ye(i.name,`${r}.name`),argv_display:Be(i.argv_display,`${r}.argv_display`,(n,a)=>ye(n,`${r}.argv_display[${a}]`)),argv_truncated:fr(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:ac(i.cwd_ref,`${r}.cwd_ref`,!0),status:L(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:ob(i.exit_code,`${r}.exit_code`),duration_ms:O(i.duration_ms,`${r}.duration_ms`)}}function mb(e){let t="Native verification",r=te(e,t);re(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=Be(r.checks,`${t}.checks`,pb);Ht(i.map(a=>a.id),`${t}.checks IDs`);let n=W(r.identity_provider,`${t}.identity_provider`);return{candidate_id:W(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:W(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:O(r.iteration,`${t}.iteration`,1),attempt:O(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":L(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:L(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:ye(r.summary,`${t}.summary`),risks:Be(r.risks,`${t}.risks`,(a,o)=>ye(a,`${t}.risks[${o}]`)),risks_truncated:fr(r.risks_truncated,`${t}.risks_truncated`),completed_at:hr(r.completed_at,`${t}.completed_at`)}}function Wf(e,t){let r=`Native history[${t}]`,i=te(e,r);re(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=ha(i.unresolved_ids,`${r}.unresolved_ids`);return Ht(n,`${r}.unresolved_ids`),{goal_cycle:O(i.goal_cycle,`${r}.goal_cycle`,1),iteration:O(i.iteration,`${r}.iteration`),attempt:O(i.attempt,`${r}.attempt`),outcome:L(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:ye(i.summary,`${r}.summary`),completed_at:hr(i.completed_at,`${r}.completed_at`)}}function vb(e){let t="Native history_overflow.outcome_counts",r=te(e,t),i=["pass","fail","blocked","execution-error","recovery"];return re(r,new Set(i),t),{pass:O(r.pass,`${t}.pass`),fail:O(r.fail,`${t}.fail`),blocked:O(r.blocked,`${t}.blocked`),"execution-error":O(r["execution-error"],`${t}.execution-error`),recovery:O(r.recovery,`${t}.recovery`)}}function gb(e){let t="Native history_overflow",r=te(e,t);re(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=O(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:hr(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:hr(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=vb(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 wb(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 yb(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 se(e){let t=te(e,"Native portable state");if(re(t,ab,"Native portable state"),t.schema!==dr)throw new Error(`Native portable state schema must be ${dr}`);let r=W(t.name,"Native state name");if(!tb.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=Be(t.spec_changes,"Native spec_changes",sb);Ht(i.map(s=>s.capability),"Native spec change capabilities");let n=Be(t.acceptance,"Native acceptance",ub);Ht(n.map(s=>s.id),"Native acceptance IDs");let a=Be(t.history,"Native history",Wf);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:dr,name:r,language:L(t.language,["en","zh-CN"],"Native state language"),phase:L(t.phase,["shape","build","verify","archive"],"Native state phase"),status:L(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:O(t.state_version,"Native state_version",1),brief:"brief.md",...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:Mf(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:Mf(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:L(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:cb(t.workspace),loop:lb(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:fb(t.builder_handoff),blockers:Be(t.blockers,"Native blockers",hb),verification:t.verification===null?null:mb(t.verification),history:a,history_overflow:gb(t.history_overflow),verification_result:L(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:L(t.verification_report,["verification.md"],"Native verification_report"),archived:fr(t.archived,"Native archived"),created_at:hr(t.created_at,"Native created_at")};return wb(o),yb(o),o}function Dt(e,t){let r=se(e),i=Wf(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 se({...r,history:n,history_overflow:a})}function Nb(e,t){let r=(0,fa.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 Q(e){let t=await eb.readFile(e,"utf8");return se(Nb(t,"Native portable state"))}async function pa(e,t,r={}){let i=se(t);await ne(e,(0,fa.stringify)(i),r)}var ua=new Map;async function bb(e,t){let r=ua.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);ua.set(e,a),await r;try{return await t()}finally{i(),ua.get(e)===a&&ua.delete(e)}}async function Bt(e){return bb(e.file,async()=>{let t=O(e.expectedStateVersion,"Native expected state version",1),r=se(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await Q(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new da(t,i.state_version);return await pa(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Q(e.file);if(n.state_version!==t)throw new da(t,n.state_version)}}),r})}function kb(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function Ke(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(kb(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 Ye="comet.native.v3",Le="comet.native.v2",qe="comet.native.v1";var ma="comet.native.portable-migration.v1",Eb=new Set(["schema","id","change","fromSchema","status","createdAt"]),Pb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,xb=/^[a-z0-9][a-z0-9-]{7,127}$/u,Rb=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),Cb=new Set([qe,Le,Ye]);function Ab(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function _b(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 Ib(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 Tb(e){return e.schema===qe?gi(e):e.schema===Le?wi(e):yi(e)}function jb(e){return Sb.posix.normalize(e.replaceAll("\\","/"))}function $b(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:jb(t.source)})}function Ob(e){return e==="shape"?"shape":"build"}function Hb(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function Db(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 zf(e){let t=Tb(e.state);qf(e.acceptance);let r=Ob(t.phase),i=r==="shape"?0:1,n=_b(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 se({schema:dr,name:t.name,language:t.language,phase:r,status:"active",state_version:1,brief:"brief.md",spec_changes:$b(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:Hb(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:Ke(Db(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:rc(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function oc(e){let t=Ab(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!Eb.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==ma)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!xb.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!Pb.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!Cb.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!Rb.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:ma,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:Ib(t.createdAt,"Native portable migration transaction createdAt")}}function Jf(e){switch(oc(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 va="comet.native.archive-transaction.v4",Gf="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",Bb=new RegExp(`^portable-archive-(${Gf})\\.json$`,"u"),Lb=new RegExp(`^portable-migration-(${Gf})\\.json$`,"u"),qb=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Fb=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Vb=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),Mb=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),Wb=new Set(["capability","operation","source","content"]),Uf=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Kf(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Yf(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 zb(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=Kf(e,r);if(Yf(i,Wb,r),typeof i.capability!="string"||!Uf.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 Jb(e){let t=Kf(e,"Native portable Archive transaction");if(Yf(t,Mb,"Native portable Archive transaction"),t.schema!==va)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!qb.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Uf.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"||!Fb.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"||!Vb.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(zb);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:va,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 ga(e){let t=Bb.exec(e);if(t)return{kind:"archive",change:t[1]};let r=Lb.exec(e);return r?{kind:"migration",change:r[1]}:null}function Lt(e,t){let r=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,i=ga(r);if(!i||i.kind!==t.kind||i.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return sc.join(e.transactionsDir,r)}async function cc(e,t){let r=ga(t);if(!r)return null;let i=await H({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=sc.join(e.transactionsDir,t);if(r.kind==="archive"){let s=Jb(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=oc(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 Nt(e,t){let r=Lt(e,t);try{return await cc(e,sc.basename(r))}catch(i){if(i.code==="ENOENT")return null;throw i}}function Xf(e){return e.kind==="archive"||e.journal.status!=="committed"}import Xe from"path";import{TextDecoder as ek}from"util";import{createHash as Gb}from"node:crypto";import{constants as wa,promises as Ae}from"node:fs";import _e from"node:path";function Na(e,t){let r=_e.relative(e,t);return r===""||!_e.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${_e.sep}`)}function Ub(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function Kb(e,t){return $({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Yb(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function ya(e,t){return $({...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 lc(e,t){let r=await Ae.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await Ae.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function Xb(e,t,r){let i=_e.resolve(e),n=_e.resolve(t);if(!Na(i,n))throw new Error(`${r} is outside its managed root`);let a=[await lc(i,r)],o=i;for(let s of _e.relative(i,n).split(_e.sep).filter(Boolean)){await qt(a,r),o=_e.join(o,s);let c=await lc(o,r);if(!Na(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await qt(a,r),a}async function qt(e,t){for(let r of e){let i=await Ae.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!Kb(r,i)||await Ae.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function Qb(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 pr(e){let t=Ub(e.maxBytes),r=_e.resolve(e.file),i=await Xb(e.root,_e.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(f=>lc(_e.resolve(f),e.label)));await e.hooks?.afterParentChainCaptured?.(),await qt(i,e.label);let a=await Ae.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=Yb(a),s=await Ae.realpath(r);if(!Na(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(f=>Na(f.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?wa.O_RDONLY:wa.O_RDONLY|wa.O_NOFOLLOW|wa.O_NONBLOCK,l=await Ae.open(r,c);try{let f=await l.stat();await e.hooks?.afterOpen?.();let[u,d]=await Promise.all([Ae.lstat(r),Ae.realpath(r)]);if(await qt(i,e.label),await qt(n,e.label),!f.isFile()||!u.isFile()||u.isSymbolicLink()||d!==s||!ya(o,f)||!ya(o,u))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let m=await Qb(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,h,p]=await Promise.all([l.stat(),Ae.lstat(r),Ae.realpath(r)]);if(await qt(i,e.label),await qt(n,e.label),!h.isFile()||h.isSymbolicLink()||p!==s||!ya(o,v)||!ya(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:m,hash:Gb("sha256").update(m).digest("hex"),size:m.length}}finally{await l.close()}}var tk=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),rk=new Set(["id","type","source","target","staged","backup"]),ik=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),nk=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var eh=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var ak=256*1024,pA=1024*1024,mA=16*1024;var vA=64*1024*1024;var ok=new ek("utf-8",{fatal:!0});function ka(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Sa(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 uc(e,t){if(typeof e!="string"||e.length===0||Xe.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function ba(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function Qf(e,t){if(uc(e,t),e.includes("\\")||e!==Xe.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 sk(e,t){let r=ka(e,`transaction operations[${t}]`);if(Sa(r,rk,`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`);uc(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&uc(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=ka(e,"Native Archive transaction journal");if(Sa(t,ik,"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(ba(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let r=t.operations.map((s,c)=>{let l=ka(s,`Archive transaction operations[${c}]`);if(Sa(l,nk,`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`);Qf(l.target,`Archive transaction operation ${l.id} target`);for(let f of["source","staged","backup"])l[f]!==void 0&&Qf(l[f],`Archive transaction operation ${l.id} ${f}`);if(l.expectedTargetHash!==null&&ba(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(ba(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);ba(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),i=r.map(s=>s.id);if(new Set(i).size!==i.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=r.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||r.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of r.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:r}}function ck(e){let t=ka(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return rh(t);if(Sa(t,tk,"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"||!Xe.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!Xe.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(sk),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 lk(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return Xe.join(e.transactionsDir,t)}function ih(e,t){let r=lk(e,t);return{directory:r,journal:Xe.join(r,"transaction.json"),events:Xe.join(r,"events.jsonl"),staged:Xe.join(r,"staged"),backups:Xe.join(r,"backups")}}async function fc(e,t){let r=ih(e,t);return await Promise.all(Object.values(r).map(i=>D(e.runtimeDir,i))),r}async function hc(e,t,r={}){let i=await fc(e,t),n=await pr({root:e.runtimeDir,file:i.journal,maxBytes:ak,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(ok.decode(n.bytes)),o=ck(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function fk(e,t,r){let i;try{i=await uk.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 hc(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(ga(n.name))try{let a=await cc(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(Xf(a))return!0}catch{return!0}return!1}async function hk(e,t){let r=Date.now()+5e3,i=dk.join(e.locksDir,"root-move.lock");for(;;)try{return await aa(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await Tf(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 K(e,t,r,i){let n=await hk(e,t);try{if(await pi(e.projectRoot),await fk(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{await oa(n)}}import{createHash as pk}from"crypto";function Ne(e){return pk("sha256").update(e).digest("hex")}var DA={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024};var BA=8*1024*1024;var LA=64*1024,qA=64*1024;var FA={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},VA={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};var MA=(1n<<256n)-1n;var bk=Ar(sr(),1);var a_=4*1024*1024;var kk=null;function Sk(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function nh(e,t){return(...r)=>{let i=kk;if(i===null)return t(...r);let n=Sk(`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 u_=nh("hookWritePolicy",async e=>(await Ws(e))?.hook??{allow_paths:[]});var sI=256*1024;var NI={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 mr from"node:path";var Ni=/^[a-f0-9]{64}$/u,oh=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,Pk=16*1024,OI=process.platform;function xk(e,t){let r=mr.relative(e,t);return mr.isAbsolute(r)||r===".."||r.startsWith(`..${mr.sep}`)?null:r.replaceAll("\\","/")||"."}function sh(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function ch(e,t){if(e.length===0||sh(e)||e.includes("\\")||mr.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=mr.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function Rk(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 pc(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||sh(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function Ck(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(pc(e.changeBranch,"Native workspace change branch"),pc(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 Ak(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"||!oh.test(t.baseCommit)||typeof t.targetCommit!="string"||!oh.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");pc(t.targetBranch,"Native workspace Git target branch")}function _k(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"||!Ni.test(String(t.projectRootId))||!Ni.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");Rk(t.capturedAt),ch(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&&!Ni.test(String(t.projectRootPathId))||a&&!Ni.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Ni.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&Ak(t.git),t.schema==="comet.native.workspace.v2"){if(t.isolation!==void 0||t.changeBranch!==void 0||t.targetBranch!==void 0||t.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof t.isolation!="string"||t.changeBranch===void 0||t.targetBranch===void 0||t.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(Ck(t),t.finish!==null&&!new Set(["merge","push","pull-request","keep"]).has(t.finish))throw new Error("Native workspace finish must be merge, push, pull-request, keep, or null")}function Ik(e,t){return mr.join(Oe(e,t),"workspace.json")}function Tk(e,t){let r=Ik(e,t),i=He(e,r),n=xk(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:ch(n,"Native workspace file ref")}}async function jk(e,t){try{let r=Tk(e,t),i=await H({root:r.root,ref:r.ref,maxBytes:Pk});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function bi(e,t){let r=await jk(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(_k(r),r)}var uh=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],Hk=new Set(uh),dh=new Set([...uh,"minimum_runtime_version","revision"]),Dk=new Set([...dh,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),Bk=new Set(["capability","operation","source","base_hash"]),Lk=new Set(["shape","build","verify","archive"]),qk=new Set(["implicit","confirmed"]),Fk=new Set(["pending","pass","fail"]),Ft="comet-state.yaml",vc=/^[a-f0-9]{64}$/u,fh=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Vk=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,gc=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"},gr=class extends Error{constructor(r,i){super(r!==Ye||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"},Ea=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"},ki=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"},Pa=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"},oT=Mn("en");function Ei(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function hh(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 yc(e){if(!fh.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Mk(e){if(!fh.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function ph(e,t){if(e.length===0||vr.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function Wk(e,t){let r=Ei(e,`spec_changes[${t}]`);if(hh(r,Bk,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(Mk(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"&&ph(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"||!vc.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"||!vc.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 zk(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 Nc(e,t){if(hh(e,t,Ft),typeof e.name!="string")throw new Error("Native change name is required");if(yc(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"||!Lk.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&&!qk.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(Wk),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"||!Fk.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"&&ph(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!zk(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 gi(e){let t=Ei(e,Ft);if(t.schema!==qe)throw new Error(`Expected ${qe}`);return{schema:qe,...Nc(t,Hk)}}function Si(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function mc(e,t,r){if(e===null)return null;let i=typeof e=="string"?Vk.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 Jk(e){if(e==null)return null;if(typeof e!="string"||!vc.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function Gk(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 wi(e){let t=Ei(e,Ft);if(t.schema!==Le)throw new Error(`Expected ${Le}`);if(Si(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Le} minimum_runtime_version must be 2`);return{schema:Le,minimum_runtime_version:2,revision:Si(t.revision,"Native v2 revision"),...Nc(t,dh)}}function yi(e){let t=Ei(e,Ft);if(t.schema!==Ye){if(t.schema===qe||t.schema===Le){let o=t.schema===qe?gi(t):wi(t);throw new gc(o.name,o.schema)}throw new gr(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=Si(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new gr(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=Si(t.revision,"Native revision"),n=Nc(t,Dk),a=Jk(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Ye,minimum_runtime_version:3,revision:i,verification_protocol:Gk(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:mc(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:mc(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:mc(t.partial_allowance,"Native partial_allowance","allowances")}}function Uk(e){let t=Ei(e,Ft);if(t.schema===qe){let n=gi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Ye}`}}if(t.schema===Le){let n=wi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Ye}`}}if(t.schema!==Ye){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 gr(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=Si(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new gr(t.schema,r).message};let i=yi(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}function fe(e,t){yc(t);let r=vr.join(e.changesDir,t);if(!F(e.changesDir,r))throw new Error("Native change path escaped");return r}async function Kk(e,t=vr.dirname(e)){let r=vr.relative(t,e).split(vr.sep).join("/"),i=await H({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,wc.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 xa(e,t){let r=vr.join(fe(e,t),Ft);await D(e.nativeRoot,r);let i=Uk(await Kk(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}import{promises as Wt}from"node:fs";import et from"node:path";import Xk from"path";var Qk=["outcome","scope","nonGoals","acceptanceExamples"],mT=[...Qk,"constraints","decisions","openQuestions","verificationExpectations"];function mh(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}function Ra(e,t){return Xk.join(e.specsDir,t,"spec.md")}var Cc=Ar(sr(),1);import{promises as Rc}from"node:fs";import ce from"node:path";import{execFileSync as Zk}from"node:child_process";var eS=3e4,tS=8*1024*1024,bc=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 vh(e,t){try{return Zk("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:eS,maxBuffer:tS,windowsHide:!0})}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new bc(e,t,i)}}function x(e,t){return vh(e,t).trim()}function Vt(e){return x(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function Ca(e){let t=vh(e,["status","--porcelain=v1","-z","--untracked-files=all"]);if(!t)return[];let r=t.split("\0").filter(Boolean),i=[];for(let n=0;n<r.length;n+=1){let a=r[n];if(a.length<4)throw new Error("Git status returned an invalid porcelain record");if(i.push(a.slice(3).replaceAll("\\","/")),a[0]==="R"||a[0]==="C"||a[1]==="R"||a[1]==="C"){let o=r[n+1];if(!o)throw new Error("Git status returned an incomplete rename record");i.push(o.replaceAll("\\","/")),n+=1}}return[...new Set(i)].sort()}function gh(e,t){try{let i=x(e,["config","--get",`branch.${t}.remote`]);if(i&&i!==".")return i}catch{}let r=x(e,["remote"]).split(/\r?\n/u).map(i=>i.trim()).filter(Boolean);if(r.includes("origin"))return"origin";if(r.length===1)return r[0];throw new Error(r.length===0?"Native workspace finish requires a configured Git remote":`Native workspace finish requires an unambiguous Git remote: ${r.join(", ")}`)}import Y from"node:path";import{promises as Ia}from"node:fs";import Aa from"node:path";function wh(...e){if(e.length===0)return Aa.resolve();if(Aa.win32.isAbsolute(e[0])){let t=Aa.win32.resolve(...e);return process.platform==="win32"?t:t.replace(/\\/gu,"/")}return Aa.resolve(...e)}var _a=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};var Sc="comet.native.supervisor.v2",rS=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function iS(e,t){let r=Y.relative(Y.resolve(e),Y.resolve(t));return r===""||!Y.isAbsolute(r)&&!r.startsWith(`..${Y.sep}`)}function nS(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native Supervisor parent name: ${e}`);return`comet/supervisor/${e}/integration`}function aS(e,t,r){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(r))throw new Error("Native Supervisor parent and child names are invalid");return wh(e,".worktrees",`${t}-${r}`)}function kh(e,t){return Y.join(ge(e,t),"supervisor")}function Ta(e,t){return Y.join(kh(e,t),"state.json")}function Sh(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!==Sc)throw new Error(`Native Supervisor state schema must be ${Sc}`);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(wr(t.integration.targetCommit,"Native Supervisor target commit"),wr(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&&wr(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(wr(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 Fe(e,t){try{let r=await Ia.readFile(Ta(e,t),"utf8"),i=JSON.parse(r);return Sh(i),i}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Mt(e,t){Sh(t),await Ia.mkdir(e.changesRuntimeDir,{recursive:!0}),await G(Ta(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function wr(e,t){if(!rS.test(e))throw new Error(`${t} must be a Git commit`)}function Pi(e){return structuredClone(e)}function Ec(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function Eh(e){wr(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:Sc,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 Pc(e){let t=nS(e.parent),r=Pt(e.paths.projectRoot,t);if(!r)return null;let i=Pt(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=le(e.paths.projectRoot).map(o=>Y.resolve(o)).find(o=>j(o).currentBranch===t);if(!n)return null;let a=Eh({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 Ec(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function ja(e){if(!Vt(e.integration.worktree))throw new Error("Native Supervisor integration worktree must be clean");let t=x(e.integration.worktree,["rev-parse","--show-toplevel"]);if(Y.resolve(t)!==Y.resolve(e.integration.worktree))throw new Error("Native Supervisor integration worktree identity is invalid");let r=x(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 x(e.integration.worktree,["rev-parse","HEAD"])}async function oS(e){let t=Pt(e.paths.projectRoot,e.state.integration.targetBranch);if(!t||t===e.state.integration.targetCommit)return null;let r=e.state;if(ja(r)!==r.integration.headCommit)throw new Error("Native Supervisor integration head changed before target refresh");try{x(r.integration.worktree,["merge","--no-edit",r.integration.targetBranch])}catch(o){throw new Error(`Native Supervisor target drift requires conflict resolution in ${r.integration.worktree}`,{cause:o})}let n=x(r.integration.worktree,["rev-parse","HEAD"]),a=Pi(r);return a.integration.headCommit=n,a.finalVerification={status:"pending",summary:null},Ec(a,{kind:"target-refreshed",child:null,runId:null,summary:`Target ${r.integration.targetBranch} was refreshed before delivery`}),a.stateVersion+=1,await Mt(e.paths,a),a}function sS(e,t){if(wr(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=Pi(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 Ph(e){let t=ja(e);if(t===e.integration.headCommit)return e;try{x(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=Pi(e);return r.integration.headCommit=t,Ec(r,{kind:"integration-head-reconciled",child:null,runId:null,summary:"Parent-level commits were included in final verification"}),r.stateVersion+=1,r}function xh(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=ja(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 sS(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)}})}async function xi(e){let r=await Fe(e.paths,e.state.parent)??e.state;if(r.stateVersion!==e.state.stateVersion)throw new Error("Native Supervisor state changed before delivery; reload status first");if(r.finalVerification.status!=="passed")throw new Error("Native Supervisor delivery requires a passed final verification");if(!r.children.every(({status:v})=>v==="integrated"||v==="archived"))throw new Error("Native Supervisor delivery requires every child to be integrated");let n=le(e.paths.projectRoot).map(v=>Y.resolve(v)).find(v=>j(v).currentBranch===r.integration.targetBranch);if(!n)throw new Error(`Native Supervisor target branch worktree is unavailable: ${r.integration.targetBranch}`);if(!Vt(n))throw new Error(`Native Supervisor target worktree is not clean: ${n}`);let a=x(n,["rev-parse","HEAD"]);if((()=>{try{return x(n,["merge-base","--is-ancestor",r.integration.headCommit,a]),!0}catch{return!1}})()){let v=await Nh({paths:e.paths,state:r,targetCommit:a});if(await bh({paths:e.paths,plan:v,targetRoot:n}),r.children.every(({status:p})=>p==="archived"))return await kc(e.paths,r.parent),{state:r,targetRoot:n,targetCommit:a};let h=Pi(r);for(let p of h.children)p.status="archived";return h.stateVersion+=1,await Mt(e.paths,h),await kc(e.paths,r.parent),{state:h,targetRoot:n,targetCommit:a}}let c=ja(r);if(c!==r.integration.headCommit)throw new Error("Native Supervisor integration head changed after final verification");let l=Pt(e.paths.projectRoot,r.integration.targetBranch),f=(()=>{if(!l)return!1;try{return x(r.integration.worktree,["merge-base","--is-ancestor",l,c]),!0}catch{return!1}})();if(l!==c&&!f&&l!==r.integration.targetCommit&&await oS({paths:e.paths,state:r}))throw new Error("Native Supervisor target changed; parent integration checks must be rerun before delivery");let u=await Nh({paths:e.paths,state:r,targetCommit:c});l!==c&&x(n,["merge","--ff-only",r.integration.branch]);let d=x(n,["rev-parse","HEAD"]);if(d!==c)throw new Error("Native Supervisor target did not receive the verified integration head");let m=Pi(r);for(let v of m.children)v.status="archived";return await bh({paths:e.paths,plan:u,targetRoot:n}),m.stateVersion+=1,await Mt(e.paths,m),await kc(e.paths,r.parent),{state:m,targetRoot:n,targetCommit:d}}function Rh(e,t){return Y.join(kh(e,t),"cleanup.json")}function yh(e){let t=le(e.paths.projectRoot).map(s=>Y.resolve(s)),r=Y.resolve(process.cwd()),i=[{root:e.state.integration.worktree,branch:e.state.integration.branch},...e.state.children.map(({name:s})=>({root:aS(e.paths.projectRoot,e.state.parent,s),branch:`comet/supervisor/${e.state.parent}/${s}`}))].map(s=>({...s,root:Y.resolve(s.root)})),n=e.targetCommit,a=[e.state.integration.branch,...e.state.children.map(({name:s})=>`comet/supervisor/${e.state.parent}/${s}`)],o=i.flatMap(s=>{let c=t.find(l=>l===s.root);return c?[{...s,root:c}]:[]});for(let s of o){if(iS(s.root,r))throw new Error(`Native Supervisor cannot clean the current worktree: ${s.root}`);if(!Vt(s.root))throw new Error(`Native Supervisor cleanup requires a clean worktree: ${s.root}`);let c=j(s.root).currentBranch;if(!c)throw new Error(`Native Supervisor worktree is detached: ${s.root}`);if(c!==s.branch)throw new Error(`Native Supervisor cleanup found unexpected branch ${c} for ${s.root}; expected ${s.branch}`);try{x(e.paths.projectRoot,["merge-base","--is-ancestor",c,n])}catch{throw new Error(`Native Supervisor cleanup found unintegrated branch ${c}`)}}for(let s of a)if(Ir(e.paths.projectRoot,s))try{x(e.paths.projectRoot,["merge-base","--is-ancestor",s,n])}catch{throw new Error(`Native Supervisor cleanup found unintegrated branch ${s}`)}return{parent:e.state.parent,targetCommit:e.targetCommit,worktrees:o.map(({root:s})=>s),expectedBranches:Object.fromEntries(o.map(({root:s,branch:c})=>[s,c])),branches:a}}async function Nh(e){let t=Rh(e.paths,e.state.parent);try{let i=JSON.parse(await Ia.readFile(t,"utf8"));if(i.parent===e.state.parent&&i.targetCommit===e.targetCommit&&Array.isArray(i.worktrees)&&i.expectedBranches&&typeof i.expectedBranches=="object"&&Array.isArray(i.branches)){let n=yh(e);return{parent:i.parent,targetCommit:i.targetCommit,worktrees:[...new Set([...i.worktrees,...n.worktrees])],expectedBranches:{...i.expectedBranches,...n.expectedBranches},branches:[...new Set([...i.branches,...n.branches])]}}}catch(i){if(i.code!=="ENOENT")throw i}let r=yh(e);return await G(t,r,{containedRoot:e.paths.changesRuntimeDir}),r}async function bh(e){for(let t of e.plan.worktrees){if(!le(e.paths.projectRoot).map(a=>Y.resolve(a)).includes(Y.resolve(t)))continue;let i=e.plan.expectedBranches[t];if(!i)throw new Error(`Native Supervisor cleanup has no expected branch for ${t}`);let n=j(t).currentBranch;if(n!==i)throw new Error(`Native Supervisor cleanup found unexpected branch ${n??"(detached)"} for ${t}; expected ${i}`);x(e.paths.projectRoot,["worktree","remove",t])}for(let t of e.plan.branches)Ir(e.paths.projectRoot,t)&&x(e.targetRoot,["branch","-d",t])}async function kc(e,t){await Ia.rm(Rh(e,t),{force:!0})}function Ch(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 Ah="children.yaml",yr="comet.native.children.v1",Nr="comet.native.children.v2",Hh=Nr,cS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,_h=new Set(["schema","children"]),lS=new Set(["schema","acceptance_index","children"]),uS=new Set(["name","depends_on","covers"]),dS=new Set(["name","summary","depends_on"]),fS=new Set(["name","depends_on","covers"]);function Oa(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function $a(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 Ih(e,t){if(!Array.isArray(e)||!e.every(r=>typeof r=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((r,i)=>r.localeCompare(i,"en"))}function xc(e,t){let r=ce.normalize(ce.resolve(e)),i=ce.normalize(ce.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function hS(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 Th(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 pS(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===Hh&&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=>!jh(e.children,l)),$h(i)?i:null}if(e.schema===yr&&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=>!jh(e.children,a)),$h(i)?i:null}return null}function jh(e,t){return e.some(r=>r.covers.includes(t))}function $h(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function Ac(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 mS(e){let t=Oa(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=Oa(n,`Native children acceptance_index.${i}`);if($a(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 vS(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 gS(e,t,r={}){let i=(0,Cc.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=Oa(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==yr&&a!==Nr)throw $a(n,_h,"Native children contract"),new Error(`Native children schema must be ${yr} or ${Nr}`);let o=a===yr?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if($a(n,o==="indexed-v2"?lS:_h,"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=Oa(d,`Native child ${m}`);if($a(v,o==="indexed-v2"?fS:o==="summary-v2"?dS:uS,`Native ${s} child fields (child ${m})`),typeof v.name!="string"||!cS.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:Ih(v.depends_on,`Native child ${v.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?Ih(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(", ")}`)}hS(c);let u=r.policy==="advisory";if(a===Hh){if(o==="indexed-v2"){let d=mS(n.acceptance_index);u||vS(d,t,r);let m=Object.keys(d);return u||Th(c,m,m),{schema:Nr,acceptance_index:d,children:c}}return{schema:Nr,children:c}}return t&&!u&&Th(c,t),{schema:yr,children:c}}async function br(e){let t=ce.join(e.changeDir,Ah);try{await Rc.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await H({root:e.changeDir,ref:Ah}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=gS(r.text,e.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?pS(a,e.acceptanceIds,e.validation??{}):null}}function wS(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 yS(e){let t=wS(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 Dh(e){try{let t=await H({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return yS(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function _c(e){return V("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 Bh(e){let t=le(e.projectRoot);t.some(i=>xc(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>ce.resolve(n)))]){let n=await de(i);n&&r.push({projectRoot:i,paths:await Ue(i,n.native.artifact_root),parent:xc(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function Lh(e){let t=await Bh(e.paths),r=[],i=[],n=new Map;for(let a of t){let o;try{o=await Rc.readdir(a.paths.changesDir,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of o){if(!s.isDirectory()||s.isSymbolicLink()||s.name===e.childName)continue;let c=ce.join(a.paths.changesDir,s.name),l;try{l=await Q(ce.join(c,"comet-state.yaml"))}catch{continue}if(l.phase!=="build"||l.status!=="active")continue;let f=await br({changeDir:c,...l.acceptance.length>0?{acceptanceIds:l.acceptance.map(({id:u})=>u)}:{}});!f||f.contract.schema!==yr||f.contract.children.some(({name:u})=>u===e.childName)&&n.set(l.name,[...n.get(l.name)??[],{source:a,state:l}])}}for(let[a,o]of n){let s=e.targetBranch===null?[]:o.filter(({state:m})=>m.workspace.target_branch===e.targetBranch);if(e.targetBranch===null){i.push(`Native Supervisor Child ${e.childName} has no target branch to match parent ${a}`);continue}let c=s.find(({source:m,state:v})=>j(m.projectRoot).currentBranch===v.workspace.change_branch);if(!c){let m=o.find(({state:v})=>v.workspace.target_branch!==e.targetBranch);if(m)i.push(`Native Supervisor parent ${a} targets ${m.state.workspace.target_branch??"(missing)"}, not ${e.targetBranch}`);else{let v=s[0]?.state??o[0].state;i.push(`Native Supervisor parent ${a} is not bound to branch ${v.workspace.change_branch}`)}continue}let{source:l,state:f}=c,u=l.paths,d=await Ic({paths:u,state:f});if(!d)i.push(`Native Supervisor parent ${a} has no readable Child inspection`);else if(!d.confirmed)i.push(`Native Supervisor parent ${a} requires Shape confirmation`);else if(d.allDone)r.push({paths:u,state:f,inspection:d});else{let m=d.children.filter(({status:v})=>v!=="done").map(({name:v,status:h,message:p})=>`${v}=${h}${p?` (${p})`:""}`).join(", ");i.push(`Native Supervisor parent ${a} is not ready to advance: ${m||"Child facts are incomplete"}`)}}return n.size===0&&i.push(`Native Supervisor Child ${e.childName} has no active v1 parent declaring it`),n.size>1&&i.push(`Native Supervisor Child ${e.childName} has multiple active parents: ${[...n.keys()].join(", ")}`),r.length===1&&i.length===0?{candidate:r[0],blockers:i}:(r.length>1&&i.push(`Native Supervisor Child ${e.childName} has multiple eligible parents: ${r.map(({state:a})=>a.name).join(", ")}`),{candidate:null,blockers:i})}async function NS(e,t){let r=ce.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Q(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function bS(e,t){let r;try{r=await Rc.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=ce.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await Q(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function kS(e,t,r){let i=ce.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${ce.sep}`))return null;let n=i.split(ce.sep).join("/");try{let a=(0,Cc.parseDocument)(x(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:se(a.toJS({mapAsMap:!1}))}catch{return null}}function SS(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 Oh(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Ic(e){let t=ce.join(e.paths.changesDir,e.state.name),r=await Dh(t),i=await br({changeDir:t,validation:Ac(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=_c({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===Nr){let p=await Fe(e.paths,e.state.name);if(!p){let g=e.state.workspace.target_branch??e.state.workspace.change_branch;if(g){let w=await Pc({paths:e.paths,parent:e.state.name,targetBranch:g,contract:i.contract});w&&(p=w,await Mt(e.paths,w))}}if(p){let g=Ch(p);return e.state.children_contract_hash!==n||i.drift?{...g,schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:!1,readyChildren:[],allDone:!1,children:g.children.map(w=>({...w,message:i.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...g,schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o}}let y=new Map(i.contract.children.map(g=>[g.name,g])),N=i.contract.children.map(g=>({name:g.name,summary:g.summary,dependsOn:[...g.depends_on],covers:[],status:o&&g.depends_on.every(w=>i.contract.children.filter(({name:S})=>S!==g.name).every(({name:S})=>S!==w))?"ready":"pending",phase:null,projectRoot:null,message:o?null:"Parent Shape confirmation is required"}));for(let g of N){if(g.status!=="ready")continue;y.get(g.name).depends_on.length>0&&(g.status="pending")}return{schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:N,readyChildren:N.filter(({status:g})=>g==="ready").map(({name:g})=>g),allDone:!1}}let s=await Bh(e.paths),c=new Set(i.contract.children.map(({name:p})=>p)),l=new Map,f=new Map;for(let p of s){let y=p.parent&&a?`refs/heads/${a}`:"HEAD";for(let N of await bS(p,c)){let g={...N,source:p,committedState:kS(p,N.file,y)};l.set(N.state.name,[...l.get(N.state.name)??[],g])}for(let N of c){let g=await NS(p,N);g&&f.set(N,[...f.get(N)??[],{source:p,state:g}])}}let u=new Map;for(let p of i.contract.children){let y=(l.get(p.name)??[]).find(({source:w,committedState:S})=>w.parent&&S?.name===p.name&&Oh(S,a));if(y){u.set(p.name,{kind:"done",phase:y.state.phase,projectRoot:y.source.projectRoot,message:null});continue}let N=l.get(p.name)?.[0];if(N){u.set(p.name,{kind:"blocked",phase:N.state.phase,projectRoot:N.source.projectRoot,message:`Native child ${p.name} is archived but not merged into parent branch ${a??"(missing)"}`});continue}let g=f.get(p.name)??[];g.length>1?u.set(p.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${p.name} has multiple active workspace owners`}):g[0]&&u.set(p.name,SS(g[0].state,g[0].source,a))}let d=new Map(i.contract.children.map(p=>[p.name,p])),m=new Map,v=p=>{let y=m.get(p);if(y)return y;let N=d.get(p),w=N.depends_on.map(v).every(({status:Z})=>Z==="done"),S=u.get(p),E=S?.kind==="active"&&w?N.depends_on.filter(Z=>!(l.get(Z)??[]).some(({source:pe,committedState:A})=>xc(pe.projectRoot,S.projectRoot)&&A?.name===Z&&Oh(A,a))):[],P,k=S?.message??null;S?.kind==="done"?(P=w?"done":"blocked",w||(k=`Native child ${p} was merged before its dependencies`)):S?.kind==="active"?(P=w&&E.length===0?"active":"blocked",w?E.length>0&&(k=`Native child ${p} does not include merged dependencies: ${E.join(", ")}`):k=`Native child ${p} started before its dependencies merged`):S?.kind==="blocked"?P="blocked":(P=o&&w?"ready":"pending",o||(k="Parent Shape confirmation is required"));let T={name:p,summary:N.summary,dependsOn:[...N.depends_on],covers:[...N.covers],status:P,phase:S?.phase??null,projectRoot:S?.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")}}import{existsSync as ES}from"node:fs";import Ri from"node:path";var PS=/[&|<>()^%"!\r\n]/u,ej=["$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 qh(e,t){let r=t.toLowerCase();return Object.entries(e).find(([i,n])=>i.toLowerCase()===r&&n!==void 0)?.[1]}function xS(e){let t=(qh(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function RS(e,t,r){let n=Ri.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(qh(t,"PATH")??"").split(Ri.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=Ri.win32.extname(e)?[e]:xS(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(c=>s?Ri.join(s,c):Ri.resolve(r,c)))}function Fh(e,t,r){return RS(e,t,r).find(i=>ES(i))??e}function Vh(e){if(e.some(t=>PS.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}var Ai="skill-coordinated";function IS(e){return e.state_version+1}function TS(e){return e.map(t=>({...t,result:"pending",reason:null}))}function jS(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:Ke(e.summary),completed_at:e.completedAt}}function Tc(e){let t=se(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=Dt(t,jS({state:t,outcome:"recovery",summary:e.reason,completedAt:r})),n=new Set(t.loop.previous_unresolved_ids),a=n.size===0?TS(t.acceptance):t.acceptance.map(o=>n.has(o.id)?{...o,result:"pending",reason:null}:o);return se({...i,phase:"build",status:"active",state_version:IS(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 Wh}from"node:fs";import _i from"node:path";function Ha(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Da(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 Ve(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 Mh(e,t){return e===null?null:Ve(e,t)}function La(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 $S(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 OS(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Ba(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function jc(e,t){if(e===null)return null;let r=Ve(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function $c(e,t){let r=Ve(e,t);if(!_i.isAbsolute(r))throw new Error(`${t} must be absolute`);return _i.resolve(r)}function HS(e,t){let r=`Native local checks[${t}]`,i=Ha(e,r);if(Da(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)=>Ve(l,`${r}.argv[${f}]`,!0)),a=Ba(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=jc(i.startedAt,`${r}.startedAt`),s=jc(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=La(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);return{id:Ve(i.id,`${r}.id`),name:Ve(i.name,`${r}.name`),operationId:Ve(i.operationId,`${r}.operationId`),status:a,repeatable:OS(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:La(i.executionCount,`${r}.executionCount`),argv:n,cwd:$c(i.cwd,`${r}.cwd`),exitCode:$S(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:Ve(i.log,`${r}.log`)}}function Oc(e){let t="Native local execution state",r=Ha(e,t);if(Da(r,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),r.schema!==vi)throw new Error(`Native local execution schema must be ${vi}`);let i=Ha(r.workspace,"Native local workspace");Da(i,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(r.execution!==null){let o=Ha(r.execution,"Native local execution");Da(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=jc(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Ve(o.operationId,"Native local execution.operationId"),stage:Ba(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Ba(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Mh(o.executionId,"Native local execution.executionId"),status:Ba(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:La(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(HS);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:vi,change:Ve(r.change,"Native local change"),basedOnStateVersion:La(r.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:$c(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:$c(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Mh(i.branch,"Native local workspace.branch")},execution:n,checks:a}}function Qe(e){return Oc({schema:vi,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:_i.resolve(e.projectRoot),worktreeRoot:_i.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function Hc(e){let t;try{t=await Wh.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 Oc(r)}async function Me(e,t,r={}){let i=Oc(t);await Wh.mkdir(_i.dirname(e),{recursive:!0}),await G(e,i,r)}import{promises as DS}from"node:fs";function kt(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
|
|
152
|
+
`).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function Ze(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function BS(e){return e.archived?xe(e.language,"Archived","已归档"):e.phase==="verify"&&e.loop.next_action==="confirm-skill-coordinated-pass"?xe(e.language,"Verification passed; your confirmation is required","验收通过,需要你确认"):e.phase==="archive"&&e.loop.next_action==="archive"?xe(e.language,"Verification passed; ready to archive","验收通过,可归档"):xe(e.language,"Verification passed","验收通过")}function LS(e){let t=e.language;return e.verification?.assurance==="semantic-verification-unavailable"?xe(t,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查"):e.verification_result==="pass"?BS(e):e.verification_result==="blocked"?xe(t,"Blocked","已阻塞"):e.verification_result==="fail"?xe(t,"Failed","未通过"):xe(t,"Pending","待处理")}function qS(e){let t=e.verification?.assurance??(e.builder_handoff?.identity_provider===Ai?Ai:"host-attested"),r=t===Ai&&(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 FS(e,t){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let r=e.language,i=u=>Os(r,u),n=(u,d)=>xe(r,u,d),a=e.acceptance.map(u=>`| ${Ze(u.id)} | ${Ze(u.result)} | ${Ze(u.source)} | ${Ze(u.text)} | ${Ze(kt(u.reason))} |`).join(`
|
|
153
|
+
`),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(kt).join(" ");return`| ${Ze(kt(u.name))} | ${Ze(d||"—")} | ${Ze(u.cwd_ref)} | ${u.status} | ${u.exit_code??"—"} | ${u.duration_ms} ms |`})].join(`
|
|
154
|
+
`),s=e.blockers.length===0?`_${n("None.","无。")}_`:e.blockers.map(u=>`- **${u.owner}**: ${kt(u.reason)}${u.acceptance_ids.length>0?` (acceptance: ${u.acceptance_ids.join(", ")})`:""} — next: \`${u.resolution_action}\``).join(`
|
|
155
|
+
`),c=e.verification.risks.length===0?`_${n("None reported.","未报告风险。")}_`:e.verification.risks.map(u=>`- ${kt(u)}`).join(`
|
|
156
|
+
`),l=e.history.length===0?`_${n("No previous iterations.","没有之前的迭代。")}_`:[`| ${n("Goal cycle","目标周期")} | ${n("Iteration","迭代")} | ${n("Attempt","尝试")} | ${n("Outcome","结果")} | ${n("Unresolved","未解决项")} | ${n("Summary","摘要")} | ${n("Completed","完成时间")} |`,"| ---: | ---: | ---: | --- | --- | --- | --- |",...e.history.map(u=>`| ${u.goal_cycle} | ${u.iteration} | ${u.attempt} | ${u.outcome} | ${u.unresolved_ids.join(", ")||"—"} | ${Ze(kt(u.summary))} | ${u.completed_at} |`)].join(`
|
|
157
|
+
`),f=t?.finalVerification.layers?`
|
|
158
158
|
## ${n("Supervisor evidence layers","Supervisor 分层证据")}
|
|
159
159
|
|
|
160
160
|
- ${n("Child verification","Child 验证")}: ${t.finalVerification.layers.childVerification}
|
|
@@ -170,13 +170,13 @@ generated_from_state_version: ${e.state_version}
|
|
|
170
170
|
|
|
171
171
|
## ${i("currentResult")}
|
|
172
172
|
|
|
173
|
-
- ${n("Result","结果")}: **${
|
|
174
|
-
- ${n("Verification status","验证情况")}: **${
|
|
173
|
+
- ${n("Result","结果")}: **${LS(e)}**
|
|
174
|
+
- ${n("Verification status","验证情况")}: **${qS(e)}**
|
|
175
175
|
- ${n("Goal cycle","目标周期")}: ${e.loop.goal_cycle}
|
|
176
176
|
- ${n("Iteration","迭代")}: ${e.verification.iteration}
|
|
177
177
|
- ${n("Verifier attempt","验证器尝试次数")}: ${e.verification.attempt}
|
|
178
178
|
- ${n("Completed","完成时间")}: ${e.verification.completed_at}
|
|
179
|
-
- ${n("Summary","摘要")}: ${
|
|
179
|
+
- ${n("Summary","摘要")}: ${kt(e.verification.summary)}
|
|
180
180
|
|
|
181
181
|
## ${i("acceptance")}
|
|
182
182
|
|
|
@@ -200,35 +200,36 @@ ${c}
|
|
|
200
200
|
|
|
201
201
|
${l}
|
|
202
202
|
|
|
203
|
-
${
|
|
203
|
+
${f}
|
|
204
204
|
|
|
205
205
|
${e.history_overflow.dropped_entries>0?`${n("Earlier history entries folded into summary","更早的历史记录已折叠到摘要中")}: ${e.history_overflow.dropped_entries}.
|
|
206
206
|
|
|
207
207
|
`:""}## ${i("conclusion")}
|
|
208
208
|
|
|
209
|
-
${
|
|
210
|
-
`}function RS(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 Pi(e){let t;try{t=await SS.readFile(e.file,"utf8")}catch(i){if(i.code==="ENOENT")return"missing";throw i}let r=RS(t);return r===null?"invalid":r===e.stateVersion?"aligned":"stale"}async function xi(e){await re(e.file,CS(e.state,e.supervisor))}var Dh=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,AS="comet-state.yaml",_S="state.json",Fj=Ln("en");function Ne(e,t){if(!Dh.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=Xe.join(e.changesDir,t);if(!V(e.changesDir,r))throw new Error("Native change path escaped");return r}function he(e,t){return Xe.join(Ne(e,t),AS)}function bt(e,t){return Xe.join(ve(e,t),_S)}async function Ci(e,t){try{let r=await qt.readFile(he(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function _c(e){return I(e).currentBranch}async function _e(e,t){return X(he(e,t))}async function Ic(e){let t=await Ot({file:he(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=Xe.join(Ne(e.paths,t.name),"verification.md");await D(e.paths.nativeRoot,r),await qt.rm(r,{force:!0})}return t}async function IS(e){let t=Ne(e.paths,e.state.name),r=Xe.join(t,"specs"),i=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await qt.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(!Dh.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=Xe.join(t,...s.split("/")),l=await qt.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let d=Xe.join(e.paths.specsDir,o.name,"spec.md"),u="create";try{let f=await qt.lstat(d);if(!f.isFile()||f.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);u="modify"}catch(f){if(f.code!=="ENOENT")throw f}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 TS(e){let t=Ne(e.paths,e.state.name),r=await H({root:t,ref:"brief.md",maxBytes:null,includeHash:!1}),i=[];for(let n of e.specChanges){if(n.source===null)continue;let a=await H({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}return aa({briefMarkdown:r.text,specs:i})}async function Tc(e){let t=await IS(e),r=e.ignoreSpecOperationFor??(e.state.children_contract_hash?new Set(e.state.spec_changes.map(({capability:c})=>c)):void 0);if(!(t.length===e.state.spec_changes.length&&t.every((c,l)=>{let d=e.state.spec_changes[l];return d!==void 0&&c.capability===d.capability&&c.source===d.source&&(c.operation===d.operation||r?.has(c.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n=await TS({...e,specChanges:t}),a=e.state.acceptance.map(({source:c,text:l})=>({source:c,text:l}));if(!$f(a,n))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let o;try{o=await Aa({changeDir:Ne(e.paths,e.state.name),acceptanceIds:n.map(({id:c})=>c),validation:kc({...e.state,acceptance:n})})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return(o?Sc({acceptance:n,children:o.contract}):null)===(e.state.children_contract_hash??null)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native child declarations changed"}}async function jS(e){let t=await _e(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 Ec({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}}}async function Bh(e){let t=await Ih({paths:e.childPaths,childName:e.childState.name,targetBranch:e.childState.workspace.target_branch});if(!t.candidate)return{parentState:null,parentAdvance:{trigger:"v1-archive",parent:null,advanced:!1,message:null,blocker:t.blockers.length>0?t.blockers.join("; "):null}};let r=await jS({paths:t.candidate.paths,name:t.candidate.state.name,trigger:"v1-archive"});return{parentState:r.state,parentAdvance:r.parentAdvance}}async function Lh(e){let t=await _e(e.paths,e.name),r=await yt(e.paths,e.name),i=await vt(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 qt.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=gh(r);if(n||a.stateVersion!==r.stateVersion){let o=await $S({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 qt.rm(n.file,{force:!0}),{state:o,action:"rerun-final-verification"}}return await Lt(e.paths,wh(r,t)),{state:t,action:"recorded-final-verification"}}async function qh(e){return U(e.paths,`set portable workspace finish ${e.name}`,async()=>{let t=await _e(e.paths,e.name);if(t.workspace.isolation==="current")throw new Error("Native current-workspace isolation does not accept a finish action");let r={...t,state_version:t.state_version+1,workspace:{...t.workspace,finish:e.finish}},i=await Ic({paths:e.paths,previous:t,next:r});return await Fe(bt(e.paths,t.name),Ke({portableState:i,projectRoot:e.paths.projectRoot,branch:_c(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),i.verification!==null&&await xi({file:Xe.join(Ne(e.paths,t.name),"verification.md"),state:i}),i})}async function Fh(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let i={...$t(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:Je(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"confirm-shape"}};delete i.children_contract_hash;let n=await Ic({paths:e.paths,previous:t,next:i});return await Fe(bt(e.paths,t.name),Ke({portableState:n,projectRoot:e.paths.projectRoot,branch:_c(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function $S(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={...$t(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:Je(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 Ic({paths:e.paths,previous:t,next:i});return await Fe(bt(e.paths,t.name),Ke({portableState:n,projectRoot:e.paths.projectRoot,branch:_c(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function $a(e){if(e.state.verification===null)return"not-applicable";let t=Xe.join(Ne(e.paths,e.state.name),"verification.md");return await Pi({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await xi({file:t,state:e.state}),"rebuilt")}import{promises as OS}from"fs";import HS from"path";var jc="comet.selection.v2",DS=16*1024;function Oa(e){return HS.join(e,".comet","current-change.json")}function BS(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Vh(e){return e===null||typeof e=="string"}function LS(e){let t;try{t=JSON.parse(e)}catch(r){throw new Error(`current change selection contains invalid JSON: ${r instanceof Error?r.message:String(r)}`,{cause:r})}if(!BS(t))throw new Error("current change selection must be a JSON object");if(t.version===1){if(typeof t.change!="string")throw new Error("legacy current change selection change must be a string");if(t.branch!==void 0&&!Vh(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:jc,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==jc)throw new Error(`current change selection schema must be ${jc}`);if(t.workflow!=="native"&&t.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof t.change!="string")throw new Error("current change selection change must be a string");if(!Vh(t.branch))throw new Error("current change selection branch must be a string or null");if(t.workflow==="native"&&t.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:t,legacy:!1}}async function Mh(e){let t;try{let i=Oa(e),{bytes:n}=await It(i,DS,{label:"current change selection"});t=n.toString("utf8")}catch(i){if(i.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${i instanceof Error?i.message:String(i)}`,{cause:i})}return{status:"selected",...LS(t)}}async function Wh(e){await OS.rm(Oa(e),{force:!0})}async function zh(e,t,r){let i=await Mh(e);return i.status!=="selected"||i.selection.workflow!==t||i.selection.change!==r?!1:(await Wh(e),!0)}var Zj=16*1024;function $c(e){return Oa(e.projectRoot)}async function Ha(e,t){return await ci(e.projectRoot),zh(e.projectRoot,"native",t)}var Ri=class extends Error{peers;constructor(t){super(t.length===0?"Native Archive serial capability decision is stale":`Native Archive requires a serial capability decision: ${t.join(", ")}`),this.name="NativePortableArchiveOrderRequiredError",this.peers=[...t]}};function Oc(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function Hc(e,t){if(!/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error("Native portable Archive ref is invalid");let r=te.join(e.archiveDir,t);if(!V(e.archiveDir,r))throw new Error("Native Archive path escaped");return r}async function Da(e){try{return await Y.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Jh(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}async function Gh(e,t){let r;try{r=await Y.readdir(e.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return null;throw n}let i=[];for(let n of r){if(!n.isDirectory()||n.isSymbolicLink())continue;let a=te.join(e.archiveDir,n.name);try{let o=await X(te.join(a,"comet-state.yaml"));o.name===t&&i.push({dir:a,state:o})}catch{}}if(i.length>1)throw new Error(`Multiple Native portable archives exist for ${t}`);return i[0]??null}async function Dc(e,t){let r=await vt(e,{kind:"archive",change:t});return r?.kind==="archive"?r.journal:null}async function Uh(e,t){return await Dc(e,t)!==null||await Gh(e,t)!==null}async function Ft(e,t){await Y.mkdir(e.transactionsDir,{recursive:!0}),await J(Ht(e,{kind:"archive",change:t.change}),t,{containedRoot:e.runtimeDir})}async function Kh(e){let t=new Set(e.state.spec_changes.map(({capability:a})=>a));if(t.size===0)return[];let r=le(e.paths.projectRoot);r.some(a=>Jh(a,e.paths.projectRoot))||r.push(e.paths.projectRoot);let i=[];for(let a of r){let o=await de(a);if(!o)continue;let s=await ze(a,o.native.artifact_root);i.some(c=>Jh(c.changesDir,s.changesDir))||i.push(s)}i.length===0&&i.push(e.paths);let n=new Set;for(let a of i){let o;try{o=await Y.readdir(a.changesDir,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of o)if(!(!s.isDirectory()||s.isSymbolicLink()||s.name===e.state.name))try{let c=await X(te.join(a.changesDir,s.name,"comet-state.yaml"));c.status!=="done"&&c.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.name)}catch{let c=await ka(a,s.name).catch(()=>null);c?.state&&c.state.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.state.name)}}return[...n].sort((a,o)=>a.localeCompare(o,"en"))}function FS(e){if(e===void 0)return null;if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error("Native Archive serial capability decision is invalid");return e}async function VS(e){let t=te.join(e.paths.specsDir,e.change.capability),r=te.join(t,"spec.md");if(!V(e.paths.specsDir,r))throw new Error("Native canonical spec path escaped");if(e.change.operation==="remove"){let n;try{n=await Y.lstat(e.paths.specsDir)}catch(c){if(c.code==="ENOENT")return;throw c}if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native canonical specs root is unsafe");let a;try{a=await Y.lstat(t)}catch(c){if(c.code==="ENOENT")return;throw c}if(!a.isDirectory()||a.isSymbolicLink())throw new Error(`Canonical Native capability directory is unsafe: ${e.change.capability}`);let[o,s]=await Promise.all([Y.realpath(e.paths.specsDir),Y.realpath(t)]);if(!V(o,s))throw new Error("Native canonical capability path escaped");try{let c=await Y.lstat(r);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await Y.unlink(r)}catch(c){if(c.code!=="ENOENT")throw c}await Y.rmdir(t).catch(c=>{if(c.code!=="ENOENT"&&c.code!=="ENOTEMPTY")throw c});return}if(e.change.source===null||e.change.content===null)throw new Error(`Native ${e.change.operation} spec requires frozen source content`);let i=te.join(Ne(e.paths,e.state.name),e.change.source);await re(i,e.change.content,{containedRoot:e.paths.nativeRoot}),await Y.mkdir(t,{recursive:!0}),await re(r,e.change.content,{containedRoot:e.paths.nativeRoot})}function Bc(e){if(e.phase!=="archive"||e.status!=="active"||e.loop.stage!=="archive-ready"||e.verification_result!=="pass"||e.verification?.verdict!=="pass"||e.verification_report!=="verification.md")throw new Error(`Native change ${e.name} is not archive-ready`)}async function MS(e,t){let r=Ne(e,t.name),i=[];for(let n of t.spec_changes){if(n.source===null){i.push({...n,content:null});continue}let a=await H({root:r,ref:n.source,maxBytes:null,includeHash:!1});i.push({...n,content:a.text})}return i}function WS(e,t){if(t.archived){if(t.status!=="done"||t.loop.stage!=="done"||t.state_version!==e.start_state_version+1)throw new Error("Native Archive transaction no longer matches the finalized portable state");return}if(t.state_version!==e.start_state_version)throw new Error("Native Archive transaction is stale for the current portable state");if(Bc(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function Lc(e){let t=await _e(e.paths,e.name),r=[];try{Bc(t)}catch(o){r.push(o.message)}if(await Dc(e.paths,e.name)===null)try{let o=await Tc({paths:e.paths,state:t});o.drifted&&r.push(o.reason??"Native confirmed requirements changed")}catch(o){r.push(o.message)}let n=t.verification===null?"missing":await Pi({file:te.join(Ne(e.paths,t.name),"verification.md"),stateVersion:t.state_version});n!=="aligned"&&r.push(`verification.md is ${n}`);let a=await Kh({paths:e.paths,state:t});return a.length>0&&r.push(`capabilities are also declared by: ${a.join(", ")}`),{ready:r.length===0,blockers:r,capabilityPeers:a,archiveDir:Hc(e.paths,Oc(t)),stateVersion:t.state_version}}async function Yh(e){return U(e.paths,`archive portable change ${e.name}`,async()=>{let t=FS(e.serialFirstChange);if(t!==null&&t!==e.name)throw new Error("Native Archive --serial-first must name the change being archived");let r=await Dc(e.paths,e.name),i=Ne(e.paths,e.name),n=await Da(i),a=n?null:await Gh(e.paths,e.name),o;if(n)o=await _e(e.paths,e.name);else if(r)o=await X(te.join(Hc(e.paths,r.archive_ref),"comet-state.yaml"));else if(a)o=a.state;else throw new Error(`Native active change is missing: ${e.name}`);let s=await yt(e.paths,e.name);if(n&&!o.archived&&r===null){let u=await Tc({paths:e.paths,state:o});if(u.drifted){let f=u.reason??"Native confirmed requirements changed";throw await Fh({paths:e.paths,state:o,reason:f}),new Error(`${f}; Native change returned to Shape and requires confirmation`)}}if(n&&!o.archived&&s?.finalVerification.status==="pending"&&o.verification_result==="pass"){let u=await Lh({paths:e.paths,name:e.name});if(o=u.state,u.action==="rerun-final-verification")throw new Error("Native Supervisor final verification must be rerun for the current integration commit");u.action==="recorded-final-verification"&&(s=await yt(e.paths,e.name))}let c=Hc(e.paths,r?.archive_ref??Oc(o)),l=await Da(c);if(r&&WS(r,o),n&&l)throw new Error("Native active and archive directories both exist; doctor intervention is required");if(!n&&!r&&a){if(!o.archived||o.status!=="done"||o.loop.stage!=="done")throw new Error("Native archive exists without a completed portable state");return await Ha(e.paths,o.name),await Y.rm(ve(e.paths,o.name),{recursive:!0,force:!0}),{change:o.name,archiveDir:a.dir,transactionId:`recovered-${o.state_version}`,state:o}}if(!r){if(!o.archived)Bc(o);else if(o.status!=="done"||o.loop.stage!=="done")throw new Error("Native active archived state is inconsistent");let u=await Kh({paths:e.paths,state:o});if(!o.archived&&u.length>0&&t!==o.name)throw new Ri(u);r={schema:fa,id:qS(),change:o.name,start_state_version:o.archived?o.state_version-1:o.state_version,archive_ref:Oc(o),status:o.archived?"state-finalized":"prepared",next_spec_index:o.archived?o.spec_changes.length:0,spec_changes:await MS(e.paths,o),created_at:new Date().toISOString()},await Ft(e.paths,r)}if(!n&&l&&r.status==="report-aligned")r={...r,status:"moved"},await Ft(e.paths,r);else if(!n&&l&&r.status!=="moved")throw new Error(`Native Archive layout contradicts transaction state ${r.status}; doctor intervention is required`);let d=!1;if(r.status==="prepared"&&s&&!o.archived&&(s=(await Ni({paths:e.paths,state:s})).state,d=!0),r.status==="prepared"){for(let u=r.next_spec_index;u<r.spec_changes.length;u+=1)await VS({paths:e.paths,state:o,change:r.spec_changes[u]}),r={...r,next_spec_index:u+1},await Ft(e.paths,r),await e.hooks?.afterSpecApplied?.(u);r={...r,status:"specs-applied"},await Ft(e.paths,r)}if(r.status==="specs-applied"){if(s&&!o.archived&&!d&&(s=(await Ni({paths:e.paths,state:s})).state,d=!0),!o.archived){let u={...o,phase:"archive",status:"done",state_version:o.state_version+1,archived:!0,blockers:[],loop:{...o.loop,stage:"done",next_action:null}};o=await Ot({file:he(e.paths,o.name),expectedStateVersion:o.state_version,next:u,containedRoot:e.paths.nativeRoot})}r={...r,status:"state-finalized"},await Ft(e.paths,r),await e.hooks?.afterFinalState?.()}if(r.status==="state-finalized"){let u=await Da(i)?i:c;if(await xi({file:te.join(u,"verification.md"),state:o,...s?{supervisor:s}:{}}),await Pi({file:te.join(u,"verification.md"),stateVersion:o.state_version})!=="aligned")throw new Error("Native final verification report is not aligned");r={...r,status:"report-aligned"},await Ft(e.paths,r),s&&!d&&(await Ni({paths:e.paths,state:s}),d=!0),await e.hooks?.afterReportAligned?.()}if(r.status==="report-aligned"){if(s&&!d&&await Ni({paths:e.paths,state:s}),await Y.mkdir(e.paths.archiveDir,{recursive:!0}),await Da(c))throw new Error(`Native Archive target already exists: ${c}`);await Y.rename(i,c),r={...r,status:"moved"},await Ft(e.paths,r),await e.hooks?.afterMove?.()}return r.status==="moved"&&(await Ha(e.paths,o.name),await Y.rm(ve(e.paths,o.name),{recursive:!0,force:!0}),await e.hooks?.afterRuntimeCleanup?.(),await Y.rm(Ht(e.paths,{kind:"archive",change:o.name}),{force:!0})),{change:o.name,archiveDir:c,transactionId:r.id,state:o}},{allowedPortableTransaction:{kind:"archive",change:e.name}})}function Vt(e,t,r){return e.language==="zh-CN"?r:t}function zS(e,t){let r=i=>({required:!1,message:null,suggestedReply:null,agentInstruction:i});if(t&&e.phase==="shape"&&e.status==="active")return{required:!0,message:Vt(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:Vt(e,"Reply A or B","回复 A 或 B"),agentInstruction:Vt(e,"Relay the two coordination choices and wait for the user decision. Do not treat a generic confirmation as a mode selection or run --confirmed without --coordination-mode.","转述这两个推进方式并等待用户选择。不要把普通“确认”视为已选择推进方式,也不要在没有 --coordination-mode 时运行 --confirmed。")};if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready"&&e.loop.next_action!=="await-verifier-result")return r(Vt(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(Vt(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(Vt(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 Xh(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Ai(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function Qh(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function JS(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function GS(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function US(e){return["comet","native","next",e.change,"--summary","<summary>",...e.coordinationRequired?["--coordination-mode","<coordination-mode>"]:[],"--confirmed","--expected-state-version",String(e.stateVersion),"--expected-action","confirm-shape"]}function Mt(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:Xh({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Ai("summary","--summary"),Qh(e.name,e.flag)]}}function qc(e){return[Mt({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Mt({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function _i(e,t){let r=GS(t)&&e.coordination_mode===void 0,i={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],userCommunication:zS(e,r)},n=a=>({kind:a,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...i,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:n("none")};if(e.status==="await-user")return e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...i,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Ai("summary","--summary")],commandAlternatives:[Mt({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...qc({change:e.name,stateVersion:e.state_version})],runnerAction:n("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...i,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Ai("summary","--summary")],commandAlternatives:[Mt({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),Mt({name:"confirm-verifier-unavailable",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-verifier-unavailable",flag:"--confirmed",confirmationInput:"user-decision"})],runnerAction:n("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...i,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Ai("summary","--summary")],commandAlternatives:[Mt({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...qc({change:e.name,stateVersion:e.state_version})],runnerAction:n("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...i,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Ai("summary","--summary")],commandAlternatives:qc({change:e.name,stateVersion:e.state_version}),runnerAction:n("none")}:{...i,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:n("none")};if(e.status==="blocked"){let a=e.blockers.some(({resolution_action:o})=>o==="retry-verifier");return{...i,disposition:"blocked",action:a?"retry-verifier":"none",commandArgs:a?Xh({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:a?["summary"]:["repair-runtime"],inputOptions:a?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:n(a?"retry-verifier":"none")}}if(e.phase==="shape")return{...i,disposition:r?"await-user":"continue",action:"confirm-shape",commandArgs:US({change:e.name,stateVersion:e.state_version,coordinationRequired:r}),requiredInputs:["summary",...r?["coordination-choice"]:[],"shared-understanding-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},...r?[JS("coordination-mode","--coordination-mode",Of)]:[],Qh("confirmed","--confirmed")],runnerAction:n("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...i,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:n("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...i,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:n("none")};if(t.allDone)return{...i,disposition:"continue",action:"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:n("builder-handoff")};let a=t.children.some(({status:s})=>s==="blocked"||s==="needs-reverify"),o=t.children.some(({status:s})=>s==="ready"||s==="active");return{...i,disposition:a&&!o?"blocked":"continue",action:"advance-children",commandArgs:null,requiredInputs:a&&!o?["resolve-child-blocker"]:["ready-children"],inputOptions:[],runnerAction:n("none")}}return{...i,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:n("builder-handoff")}}if(e.phase==="verify"){let a=e.loop.next_action==="await-verifier-result",o=!!e.children_contract_hash,s={id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0};return{...i,userCommunication:!a&&o?{...i.userCommunication,agentInstruction:`${i.userCommunication.agentInstruction} ${Vt(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:i.userCommunication,disposition:"continue",action:a?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[a?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:a?[{kind:"verifier-response",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[s]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:[{id:"<acceptance-id>",result:"<passed|failed|blocked>",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:o?[s]:[]}}],runnerAction:n(a?"await-verifier":"dispatch-verifier")}}return e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived?{...i,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],commandAlternatives:[Mt({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:n("none")}:{...i,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:n("none")}}import{randomUUID as KS}from"node:crypto";import{promises as Ii}from"node:fs";import YS from"node:path";var Zh=["evidence.md","repair.md","archive.md","checkpoint.md"],XS="verification.md";async function QS(e,t){let r=await vt(e,{kind:"migration",change:t});return r?.kind==="migration"?r.journal:null}async function ep(e,t){await Ii.mkdir(e.transactionsDir,{recursive:!0}),await J(Ht(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function tp(e,t,r={}){let i=r.removeVerificationReport===!1?Zh:[...Zh,XS];await Promise.all([Ii.rm(ve(e,t),{recursive:!0,force:!0}),Ii.rm(Fs(e,t),{recursive:!0,force:!0}),...i.map(n=>Ii.rm(YS.join(fe(e,t),n),{force:!0}))])}async function rp(e,t){await Fe(bt(e,t.name),Ke({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function ip(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 np(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let r=I(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 ZS(e){let t=fe(e.paths,e.state.name),r=await H({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 H({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return aa({briefMarkdown:r.text,specs:i})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function ap(e,t){let r=await ka(e,t);if(!r.state)throw new Error(`Native legacy change ${t} is unreadable`);return r.state}async function op(e){return U(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await QS(e.paths,e.name),r=await Ci(e.paths,e.name)?await X(he(e.paths,e.name)):null;if(!t&&r)return await tp(e.paths,e.name,{removeVerificationReport:!1}),await rp(e.paths,r),r;let i=null,n=null;for(t||(i=await ap(e.paths,e.name),n=await ip(e.paths,e.name),np(e.paths,n),t={schema:da,id:KS(),change:i.name,fromSchema:i.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await ep(e.paths,t));;){let a=Bf(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?r||(i??=await ap(e.paths,e.name),n??=await ip(e.paths,e.name),np(e.paths,n),r=Df({state:i,acceptance:await ZS({paths:e.paths,state:i}),workspace:n,migratedAt:e.now}),await ua(he(e.paths,e.name),r,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await tp(e.paths,e.name):a.action==="commit-transaction"&&(r??=await X(he(e.paths,e.name)),await rp(e.paths,r)),t={...t,status:a.nextStatus},await ep(e.paths,t)}return await Ii.rm(Ht(e.paths,{kind:"migration",change:e.name}),{force:!0}),r??X(he(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as sp}from"node:fs";import cp from"node:path";function eE(e,t){let r=I(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 tE(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function rE(e,t,r){let i=new Date().toISOString(),n=e.verification===null?e:$t(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:Je(t),completed_at:i});return oe({...n,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:r?tE(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 iE(e){try{let t=await Ac(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 lp(e){return U(e.paths,`recover portable change ${e.name}`,async()=>{let t=await _e(e.paths,e.name);if(t.status==="done")return await $a({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=eE(e.paths,t);if(r)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:r};let i=bt(e.paths,e.name),n=await iE(i),a=n.reason==="available"&&(n.local?.change!==t.name||n.local?.basedOnStateVersion!==t.state_version)?"stale":n.reason;if(a==="available"&&!e.preserveRunningExecution&&n.local?.execution!==null&&n.local?.execution?.status!=="completed"&&n.local&&(a="interrupted",n.local.execution?.status==="running"&&(n.local={...n.local,execution:{...n.local.execution,status:"interrupted"},checks:n.local.checks.map(f=>f.status==="planned"||f.status==="running"?{...f,status:"interrupted"}:f)},await Fe(i,n.local,{containedRoot:e.paths.runtimeDir}))),a==="available")return await $a({paths:e.paths,state:t}),{state:t,local:n.local,action:"resume-stable-boundary",reason:a,message:"Native local execution overlay matches the portable state."};let s=a==="interrupted"?n.local?.checks.find(f=>f.status==="interrupted"&&!f.repeatable):void 0;if(s){let f=Pc({state:t,reason:`Check ${s.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await Ot({file:he(e.paths,t.name),expectedStateVersion:t.state_version,next:f,containedRoot:e.paths.nativeRoot}),await sp.rm(cp.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let m=Ke({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await Fe(i,m,{containedRoot:e.paths.runtimeDir}),{state:t,local:m,action:"resume-stable-boundary",reason:a,message:`Native check ${s.id} was not repeatable; the change returned to Build for a new candidate.`}}let c=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",l=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",d=c||l;if(d){let f=rE(t,l?"Local Runtime was unavailable at Archive ready; the synchronized implementation must be verified again.":"The previous Verifier execution was unavailable; dispatch a new attempt from the stable Verify boundary.",l);t=await Ot({file:he(e.paths,t.name),expectedStateVersion:t.state_version,next:f,containedRoot:e.paths.nativeRoot})}let u=Ke({portableState:t,projectRoot:e.paths.projectRoot,branch:I(e.paths.projectRoot).currentBranch});return await sp.mkdir(cp.dirname(bt(e.paths,t.name)),{recursive:!0}),await Fe(i,u,{containedRoot:e.paths.runtimeDir}),await $a({paths:e.paths,state:t}),{state:t,local:u,action:d?"reverify":"resume-stable-boundary",reason:a,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{accessSync as vE,constants as gE,promises as wE}from"node:fs";import Qe from"node:path";import{execFileSync as nE}from"node:child_process";import up from"node:path";var aE=6e4,oE=8*1024*1024,Fc=class extends Error{constructor(r,i,n,a){super(`${r} ${i.join(" ")} failed${n?`: ${n}`:""}`,a);this.command=r;this.args=i;this.stderr=n;this.name="ExternalCommandError"}command;args;stderr};function yr(e,t,r={}){let i=r.timeoutMs??aE,n=r.maxBufferBytes??oE;if(!Number.isSafeInteger(i)||i<1)throw new Error("External command timeout must be a positive integer");if(!Number.isSafeInteger(n)||n<1)throw new Error("External command max buffer must be a positive integer");let a=up.resolve(r.cwd??process.cwd()),o=r.env??process.env,s=process.platform==="win32"?jh(e,o,a):e,c=up.win32.extname(s).toLowerCase(),l=c===".bat"||c===".cmd";process.platform==="win32"&&l&&$h(t);try{return nE(s,[...t],{cwd:a,env:o,...r.input!==void 0?{input:r.input}:{},encoding:"utf8",stdio:[r.input===void 0?"ignore":"pipe","pipe","pipe"],timeout:i,maxBuffer:n,windowsHide:!0,shell:process.platform==="win32"&&l})}catch(d){let u=typeof d.stderr=="string"?d.stderr.trim():Buffer.isBuffer(d.stderr)?d.stderr.toString("utf8").trim():"";throw new Fc(e,t,u,{cause:d})}}import cE from"path";var lE=["outcome","scope","nonGoals","acceptanceExamples"],nO=[...lE,"constraints","decisions","openQuestions","verificationExpectations"];function Ba(e,t){return cE.join(e.specsDir,t,"spec.md")}var uE=6e4,z=class extends Error{constructor(r,i,n){super(r,n);this.pullRequest=i;this.name="NativePullRequestFinishError"}pullRequest};function Vc(e,t){try{return yr("gh",t,{cwd:e,timeoutMs:uE}).trim()}catch(r){throw new Error(`gh ${t.join(" ")} failed: ${r.message}`,{cause:r})}}function Mc(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a JSON object`);return e}function Wc(e,t){try{return JSON.parse(e)}catch(r){throw new Error(`${t} must be valid JSON`,{cause:r})}}function dp(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Wt(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be a non-empty string`);return e}function fp(e,t){let r=Wt(e,t),i;try{i=new URL(r)}catch(n){throw new Error(`${t} must be an absolute HTTP URL`,{cause:n})}if(i.protocol!=="https:"&&i.protocol!=="http:")throw new Error(`${t} must be an absolute HTTP URL`);return r}function qa(e,t){let r=Wt(e,t);if(!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/iu.test(r))throw new Error(`${t} must be a Git object ID`);return r.toLowerCase()}function hp(e,t){let r=Mc(e,t);if(Wt(r.state,`${t}.state`)!=="OPEN")throw new Error(`${t}.state must be OPEN`);return{number:dp(r.number,`${t}.number`),url:fp(r.url,`${t}.url`),baseBranch:Wt(r.baseRefName,`${t}.baseRefName`),headBranch:Wt(r.headRefName,`${t}.headRefName`),headSha:qa(r.headRefOid,`${t}.headRefOid`),state:"OPEN"}}function dE(e){let t=Mc(e,"pull request finish provider output.pullRequest");return{number:dp(t.number,"pull request finish provider output.pullRequest.number"),url:fp(t.url,"pull request finish provider output.pullRequest.url"),baseBranch:Wt(t.baseBranch,"pull request finish provider output.pullRequest.baseBranch"),headBranch:Wt(t.headBranch,"pull request finish provider output.pullRequest.headBranch"),headSha:qa(t.headSha,"pull request finish provider output.pullRequest.headSha")}}function fE(e){let t=Mc(Wc(e,"pull request finish provider output"),"pull request finish provider output");if(t.schema!=="comet.native.pull-request-finish-result.v1")throw new Error("pull request finish provider output.schema must be comet.native.pull-request-finish-result.v1");if(t.disposition!=="created"&&t.disposition!=="reused")throw new Error("pull request finish provider output.disposition must be created or reused");if(t.remoteVerified!==!0)throw new Error("pull request finish provider did not confirm repository-owned remote verification");let r=dE(t.pullRequest);return{schema:"comet.native.pull-request-finish-result.v1",disposition:t.disposition,remoteVerified:!0,pullRequest:r}}function zc(e){let t=Vc(e.projectRoot,["pr","list","--state","open","--base",e.baseBranch,"--head",e.headBranch,"--limit","2","--json","number,url,baseRefName,headRefName,headRefOid,state"]),r=Wc(t,"gh pr list output");if(!Array.isArray(r))throw new Error("gh pr list output must be a JSON array");if(r.length>1)throw new Error(`Multiple open pull requests match ${e.headBranch} -> ${e.baseBranch}`);return r.length===0?null:hp(r[0],"gh pr list output[0]")}function pp(e){let t=Vc(e.projectRoot,["pr","view",String(e.pullRequest.number),"--json","number,url,baseRefName,headRefName,headRefOid,state"]),r=hp(Wc(t,"gh pr view output"),"gh pr view output"),i=qa(e.headSha,"Native Archive head SHA");if(r.number!==e.pullRequest.number||r.url!==e.pullRequest.url)throw new z("Pull request provider result does not match the pull request observed from GitHub",r);if(r.baseBranch!==e.baseBranch)throw new z(`Pull request base branch mismatch: expected ${e.baseBranch}, got ${r.baseBranch}`,r);if(r.headBranch!==e.headBranch)throw new z(`Pull request head branch mismatch: expected ${e.headBranch}, got ${r.headBranch}`,r);if(r.headSha!==i)throw new z(`Pull request head SHA mismatch: expected ${i}, got ${r.headSha}`,r);return r}function La(e){try{return zc(e)}catch{return null}}function hE(e){return JSON.stringify({schema:"comet.native.pull-request-finish-input.v1",projectRoot:e.projectRoot,change:{name:e.changeName,branch:e.headBranch,headSha:e.headSha},target:{branch:e.baseBranch},remote:e.remote,transactionId:e.transactionId,existingPullRequest:e.existingPullRequest},null,2)}function pE(e){let t=e.existingPullRequest,r=t?"reused":"created";if(!t)try{let a=Vc(e.projectRoot,["pr","create","--base",e.baseBranch,"--head",e.headBranch,"--fill"]).split(/\r?\n/u).map(o=>o.trim()).find(o=>/^https?:\/\//u.test(o));if(!a)throw new Error("GitHub CLI did not return a pull request URL");if(t=zc(e),!t)throw new Error("GitHub CLI created a pull request that could not be observed uniquely");if(t.url!==a)throw new z("GitHub CLI returned a pull request URL that does not match the remotely observed pull request",t)}catch(n){if(n instanceof z)throw n;let a=La(e);if(!a)throw new z(n.message,null,{cause:n});t=a,r="reused"}let i;try{i=pp({...e,pullRequest:t})}catch(n){throw n instanceof z?n:new z(`Final GitHub pull request verification failed: ${n.message}`,t,{cause:n})}return{provider:"github-fill",disposition:r,pullRequest:i,remoteVerified:!0}}function mE(e){let[t,...r]=e.config.command,i;try{let o=yr(t,r,{cwd:e.projectRoot,timeoutMs:e.config.timeout_ms,input:`${hE(e)}
|
|
211
|
-
`}).trim();i=
|
|
209
|
+
${kt(e.verification.summary)}
|
|
210
|
+
`}function VS(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 Ii(e){let t;try{t=await DS.readFile(e.file,"utf8")}catch(i){if(i.code==="ENOENT")return"missing";throw i}let r=VS(t);return r===null?"invalid":r===e.stateVersion?"aligned":"stale"}async function Ti(e){await ne(e.file,FS(e.state,e.supervisor))}var zh=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,MS="comet-state.yaml",WS="state.json",k$=Mn("en");function be(e,t){if(!zh.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=et.join(e.changesDir,t);if(!F(e.changesDir,r))throw new Error("Native change path escaped");return r}function he(e,t){return et.join(be(e,t),MS)}function St(e,t){return et.join(ge(e,t),WS)}async function ji(e,t){try{let r=await Wt.readFile(he(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function Dc(e){return j(e).currentBranch}async function Ie(e,t){return Q(he(e,t))}async function Bc(e){let t=await Bt({file:he(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=et.join(be(e.paths,t.name),"verification.md");await D(e.paths.nativeRoot,r),await Wt.rm(r,{force:!0})}return t}async function zS(e){let t=be(e.paths,e.state.name),r=et.join(t,"specs"),i=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await Wt.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(!zh.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=et.join(t,...s.split("/")),l=await Wt.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let f=et.join(e.paths.specsDir,o.name,"spec.md"),u="create";try{let d=await Wt.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 JS(e){let t=be(e.paths,e.state.name),r=await H({root:t,ref:"brief.md",maxBytes:null,includeHash:!1});if(mh(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 H({root:t,ref:a.source,maxBytes:null,includeHash:!1});i.push({capability:a.capability,source:o.ref,markdown:o.text}),n.push({...a,contentHash:V("comet.native.shape-artifact-content.v1",o.text)})}return{acceptance:la({briefMarkdown:r.text,specs:i}),formalHash:V("comet.native.shape-formal-artifacts.v1",{brief:{source:r.ref,contentHash:V("comet.native.shape-artifact-content.v1",r.text)},specs:n})}}function GS(e){return V("comet.native.shape-confirmation.v1",{formalHash:e.formalHash,childrenHash:e.childrenHash,coordinationMode:e.coordinationMode??null})}async function Lc(e){let t=await zS(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 JS({...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(!Ff(o,a))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let s;try{s=await br({changeDir:be(e.paths,e.state.name),acceptanceIds:a.map(({id:l})=>l),validation:Ac({...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&&GS({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?_c({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 US(e){let t=await Ie(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 Ic({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}}}async function Jh(e){let t=await Lh({paths:e.childPaths,childName:e.childState.name,targetBranch:e.childState.workspace.target_branch});if(!t.candidate)return{parentState:null,parentAdvance:{trigger:"v1-archive",parent:null,advanced:!1,message:null,blocker:t.blockers.length>0?t.blockers.join("; "):null}};let r=await US({paths:t.candidate.paths,name:t.candidate.state.name,trigger:"v1-archive"});return{parentState:r.state,parentAdvance:r.parentAdvance}}async function Gh(e){let t=await Ie(e.paths,e.name),r=await Fe(e.paths,e.name),i=await Nt(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 Wt.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=Ph(r);if(n||a.stateVersion!==r.stateVersion){let o=await KS({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 Wt.rm(n.file,{force:!0}),{state:o,action:"rerun-final-verification"}}return await Mt(e.paths,xh(r,t)),{state:t,action:"recorded-final-verification"}}async function Uh(e){return K(e.paths,`set portable workspace finish ${e.name}`,async()=>{let t=await Ie(e.paths,e.name);if(t.workspace.isolation==="current")throw new Error("Native current-workspace isolation does not accept a finish action");let r={...t,state_version:t.state_version+1,workspace:{...t.workspace,finish:e.finish}},i=await Bc({paths:e.paths,previous:t,next:r});return await Me(St(e.paths,t.name),Qe({portableState:i,projectRoot:e.paths.projectRoot,branch:Dc(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),i.verification!==null&&await Ti({file:et.join(be(e.paths,t.name),"verification.md"),state:i}),i})}async function Kh(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let i={...Dt(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:Ke(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 Bc({paths:e.paths,previous:t,next:i});return await Me(St(e.paths,t.name),Qe({portableState:n,projectRoot:e.paths.projectRoot,branch:Dc(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function KS(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={...Dt(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:Ke(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 Bc({paths:e.paths,previous:t,next:i});return await Me(St(e.paths,t.name),Qe({portableState:n,projectRoot:e.paths.projectRoot,branch:Dc(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function qa(e){if(e.state.verification===null)return"not-applicable";let t=et.join(be(e.paths,e.state.name),"verification.md");return await Ii({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await Ti({file:t,state:e.state}),"rebuilt")}import{promises as YS}from"fs";import XS from"path";var qc="comet.selection.v2",QS=16*1024;function Fa(e){return XS.join(e,".comet","current-change.json")}function ZS(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Yh(e){return e===null||typeof e=="string"}function eE(e){let t;try{t=JSON.parse(e)}catch(r){throw new Error(`current change selection contains invalid JSON: ${r instanceof Error?r.message:String(r)}`,{cause:r})}if(!ZS(t))throw new Error("current change selection must be a JSON object");if(t.version===1){if(typeof t.change!="string")throw new Error("legacy current change selection change must be a string");if(t.branch!==void 0&&!Yh(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:qc,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==qc)throw new Error(`current change selection schema must be ${qc}`);if(t.workflow!=="native"&&t.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof t.change!="string")throw new Error("current change selection change must be a string");if(!Yh(t.branch))throw new Error("current change selection branch must be a string or null");if(t.workflow==="native"&&t.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:t,legacy:!1}}async function Xh(e){let t;try{let i=Fa(e),{bytes:n}=await $t(i,QS,{label:"current change selection"});t=n.toString("utf8")}catch(i){if(i.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${i instanceof Error?i.message:String(i)}`,{cause:i})}return{status:"selected",...eE(t)}}async function Qh(e){await YS.rm(Fa(e),{force:!0})}async function Zh(e,t,r){let i=await Xh(e);return i.status!=="selected"||i.selection.workflow!==t||i.selection.change!==r?!1:(await Qh(e),!0)}var $$=16*1024;function Fc(e){return Fa(e.projectRoot)}async function Va(e,t){return await pi(e.projectRoot),Zh(e.projectRoot,"native",t)}var $i=class extends Error{peers;constructor(t){super(t.length===0?"Native Archive serial capability decision is stale":`Native Archive requires a serial capability decision: ${t.join(", ")}`),this.name="NativePortableArchiveOrderRequiredError",this.peers=[...t]}};function Vc(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function Mc(e,t){if(!/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error("Native portable Archive ref is invalid");let r=ie.join(e.archiveDir,t);if(!F(e.archiveDir,r))throw new Error("Native Archive path escaped");return r}async function Ma(e){try{return await X.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function ep(e,t){let r=ie.normalize(ie.resolve(e)),i=ie.normalize(ie.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}async function tp(e,t){let r;try{r=await X.readdir(e.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return null;throw n}let i=[];for(let n of r){if(!n.isDirectory()||n.isSymbolicLink())continue;let a=ie.join(e.archiveDir,n.name);try{let o=await Q(ie.join(a,"comet-state.yaml"));o.name===t&&i.push({dir:a,state:o})}catch{}}if(i.length>1)throw new Error(`Multiple Native portable archives exist for ${t}`);return i[0]??null}async function Wc(e,t){let r=await Nt(e,{kind:"archive",change:t});return r?.kind==="archive"?r.journal:null}async function rp(e,t){return await Wc(e,t)!==null||await tp(e,t)!==null}async function zt(e,t){await X.mkdir(e.transactionsDir,{recursive:!0}),await G(Lt(e,{kind:"archive",change:t.change}),t,{containedRoot:e.runtimeDir})}async function ip(e){let t=new Set(e.state.spec_changes.map(({capability:a})=>a));if(t.size===0)return[];let r=le(e.paths.projectRoot);r.some(a=>ep(a,e.paths.projectRoot))||r.push(e.paths.projectRoot);let i=[];for(let a of r){let o=await de(a);if(!o)continue;let s=await Ue(a,o.native.artifact_root);i.some(c=>ep(c.changesDir,s.changesDir))||i.push(s)}i.length===0&&i.push(e.paths);let n=new Set;for(let a of i){let o;try{o=await X.readdir(a.changesDir,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of o)if(!(!s.isDirectory()||s.isSymbolicLink()||s.name===e.state.name))try{let c=await Q(ie.join(a.changesDir,s.name,"comet-state.yaml"));c.status!=="done"&&c.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.name)}catch{let c=await xa(a,s.name).catch(()=>null);c?.state&&c.state.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.state.name)}}return[...n].sort((a,o)=>a.localeCompare(o,"en"))}function rE(e){if(e===void 0)return null;if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error("Native Archive serial capability decision is invalid");return e}async function iE(e){let t=ie.join(e.paths.specsDir,e.change.capability),r=ie.join(t,"spec.md");if(!F(e.paths.specsDir,r))throw new Error("Native canonical spec path escaped");if(e.change.operation==="remove"){let n;try{n=await X.lstat(e.paths.specsDir)}catch(c){if(c.code==="ENOENT")return;throw c}if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native canonical specs root is unsafe");let a;try{a=await X.lstat(t)}catch(c){if(c.code==="ENOENT")return;throw c}if(!a.isDirectory()||a.isSymbolicLink())throw new Error(`Canonical Native capability directory is unsafe: ${e.change.capability}`);let[o,s]=await Promise.all([X.realpath(e.paths.specsDir),X.realpath(t)]);if(!F(o,s))throw new Error("Native canonical capability path escaped");try{let c=await X.lstat(r);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await X.unlink(r)}catch(c){if(c.code!=="ENOENT")throw c}await X.rmdir(t).catch(c=>{if(c.code!=="ENOENT"&&c.code!=="ENOTEMPTY")throw c});return}if(e.change.source===null||e.change.content===null)throw new Error(`Native ${e.change.operation} spec requires frozen source content`);let i=ie.join(be(e.paths,e.state.name),e.change.source);await ne(i,e.change.content,{containedRoot:e.paths.nativeRoot}),await X.mkdir(t,{recursive:!0}),await ne(r,e.change.content,{containedRoot:e.paths.nativeRoot})}function zc(e){if(e.phase!=="archive"||e.status!=="active"||e.loop.stage!=="archive-ready"||e.verification_result!=="pass"||e.verification?.verdict!=="pass"||e.verification_report!=="verification.md")throw new Error(`Native change ${e.name} is not archive-ready`)}async function nE(e,t){let r=be(e,t.name),i=[];for(let n of t.spec_changes){if(n.source===null){i.push({...n,content:null});continue}let a=await H({root:r,ref:n.source,maxBytes:null,includeHash:!1});i.push({...n,content:a.text})}return i}function aE(e,t){if(t.archived){if(t.status!=="done"||t.loop.stage!=="done"||t.state_version!==e.start_state_version+1)throw new Error("Native Archive transaction no longer matches the finalized portable state");return}if(t.state_version!==e.start_state_version)throw new Error("Native Archive transaction is stale for the current portable state");if(zc(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function Jc(e){let t=await Ie(e.paths,e.name),r=[];try{zc(t)}catch(o){r.push(o.message)}if(await Wc(e.paths,e.name)===null)try{let o=await Lc({paths:e.paths,state:t});o.drifted&&r.push(o.reason??"Native confirmed requirements changed")}catch(o){r.push(o.message)}let n=t.verification===null?"missing":await Ii({file:ie.join(be(e.paths,t.name),"verification.md"),stateVersion:t.state_version});n!=="aligned"&&r.push(`verification.md is ${n}`);let a=await ip({paths:e.paths,state:t});return a.length>0&&r.push(`capabilities are also declared by: ${a.join(", ")}`),{ready:r.length===0,blockers:r,capabilityPeers:a,archiveDir:Mc(e.paths,Vc(t)),stateVersion:t.state_version}}async function np(e){return K(e.paths,`archive portable change ${e.name}`,async()=>{let t=rE(e.serialFirstChange);if(t!==null&&t!==e.name)throw new Error("Native Archive --serial-first must name the change being archived");let r=await Wc(e.paths,e.name),i=be(e.paths,e.name),n=await Ma(i),a=n?null:await tp(e.paths,e.name),o;if(n)o=await Ie(e.paths,e.name);else if(r)o=await Q(ie.join(Mc(e.paths,r.archive_ref),"comet-state.yaml"));else if(a)o=a.state;else throw new Error(`Native active change is missing: ${e.name}`);let s=await Fe(e.paths,e.name);if(n&&!o.archived&&r===null){let u=await Lc({paths:e.paths,state:o});if(u.drifted){let d=u.reason??"Native confirmed requirements changed";throw await Kh({paths:e.paths,state:o,reason:d}),new Error(`${d}; Native change returned to Shape and requires confirmation`)}}if(n&&!o.archived&&s?.finalVerification.status==="pending"&&o.verification_result==="pass"){let u=await Gh({paths:e.paths,name:e.name});if(o=u.state,u.action==="rerun-final-verification")throw new Error("Native Supervisor final verification must be rerun for the current integration commit");u.action==="recorded-final-verification"&&(s=await Fe(e.paths,e.name))}let c=Mc(e.paths,r?.archive_ref??Vc(o)),l=await Ma(c);if(r&&aE(r,o),n&&l)throw new Error("Native active and archive directories both exist; doctor intervention is required");if(!n&&!r&&a){if(!o.archived||o.status!=="done"||o.loop.stage!=="done")throw new Error("Native archive exists without a completed portable state");return await Va(e.paths,o.name),await X.rm(ge(e.paths,o.name),{recursive:!0,force:!0}),{change:o.name,archiveDir:a.dir,transactionId:`recovered-${o.state_version}`,state:o}}if(!r){if(!o.archived)zc(o);else if(o.status!=="done"||o.loop.stage!=="done")throw new Error("Native active archived state is inconsistent");let u=await ip({paths:e.paths,state:o});if(!o.archived&&u.length>0&&t!==o.name)throw new $i(u);r={schema:va,id:tE(),change:o.name,start_state_version:o.archived?o.state_version-1:o.state_version,archive_ref:Vc(o),status:o.archived?"state-finalized":"prepared",next_spec_index:o.archived?o.spec_changes.length:0,spec_changes:await nE(e.paths,o),created_at:new Date().toISOString()},await zt(e.paths,r)}if(!n&&l&&r.status==="report-aligned")r={...r,status:"moved"},await zt(e.paths,r);else if(!n&&l&&r.status!=="moved")throw new Error(`Native Archive layout contradicts transaction state ${r.status}; doctor intervention is required`);let f=!1;if(r.status==="prepared"&&s&&!o.archived&&(s=(await xi({paths:e.paths,state:s})).state,f=!0),r.status==="prepared"){for(let u=r.next_spec_index;u<r.spec_changes.length;u+=1)await iE({paths:e.paths,state:o,change:r.spec_changes[u]}),r={...r,next_spec_index:u+1},await zt(e.paths,r),await e.hooks?.afterSpecApplied?.(u);r={...r,status:"specs-applied"},await zt(e.paths,r)}if(r.status==="specs-applied"){if(s&&!o.archived&&!f&&(s=(await xi({paths:e.paths,state:s})).state,f=!0),!o.archived){let u={...o,phase:"archive",status:"done",state_version:o.state_version+1,archived:!0,blockers:[],loop:{...o.loop,stage:"done",next_action:null}};o=await Bt({file:he(e.paths,o.name),expectedStateVersion:o.state_version,next:u,containedRoot:e.paths.nativeRoot})}r={...r,status:"state-finalized"},await zt(e.paths,r),await e.hooks?.afterFinalState?.()}if(r.status==="state-finalized"){let u=await Ma(i)?i:c;if(await Ti({file:ie.join(u,"verification.md"),state:o,...s?{supervisor:s}:{}}),await Ii({file:ie.join(u,"verification.md"),stateVersion:o.state_version})!=="aligned")throw new Error("Native final verification report is not aligned");r={...r,status:"report-aligned"},await zt(e.paths,r),s&&!f&&(await xi({paths:e.paths,state:s}),f=!0),await e.hooks?.afterReportAligned?.()}if(r.status==="report-aligned"){if(s&&!f&&await xi({paths:e.paths,state:s}),await X.mkdir(e.paths.archiveDir,{recursive:!0}),await Ma(c))throw new Error(`Native Archive target already exists: ${c}`);await X.rename(i,c),r={...r,status:"moved"},await zt(e.paths,r),await e.hooks?.afterMove?.()}return r.status==="moved"&&(await Va(e.paths,o.name),await X.rm(ge(e.paths,o.name),{recursive:!0,force:!0}),await e.hooks?.afterRuntimeCleanup?.(),await X.rm(Lt(e.paths,{kind:"archive",change:o.name}),{force:!0})),{change:o.name,archiveDir:c,transactionId:r.id,state:o}},{allowedPortableTransaction:{kind:"archive",change:e.name}})}function tt(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:tt(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:tt(e,"Reply A or B","回复 A 或 B"),agentInstruction:tt(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(tt(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(tt(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(tt(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 sE(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 cE(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:tt(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:tt(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function op(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Sr(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function lE(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function ap(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function uE(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function dE(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 Et(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:op({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Sr("summary","--summary"),lE(e.name,e.flag)]}}function Gc(e){return[Et({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Et({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function rt(e,t,r={}){let i=uE(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:[Sr("summary","--summary")],commandAlternatives:[Et({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:[Sr("summary","--summary")],commandAlternatives:[Et({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...Gc({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:[Sr("summary","--summary")],commandAlternatives:[Et({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),Et({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:[Sr("summary","--summary")],commandAlternatives:[Et({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...Gc({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:[Sr("summary","--summary")],commandAlternatives:Gc({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?op({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:dE({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?[ap("coordination-mode","--coordination-mode",Vf)]:[]],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} ${tt(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:[ap("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...cE(e)],userCommunication:sE(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[Et({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 fE}from"node:crypto";import{promises as Oi}from"node:fs";import hE from"node:path";var sp=["evidence.md","repair.md","archive.md","checkpoint.md"],pE="verification.md";async function mE(e,t){let r=await Nt(e,{kind:"migration",change:t});return r?.kind==="migration"?r.journal:null}async function cp(e,t){await Oi.mkdir(e.transactionsDir,{recursive:!0}),await G(Lt(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function lp(e,t,r={}){let i=r.removeVerificationReport===!1?sp:[...sp,pE];await Promise.all([Oi.rm(ge(e,t),{recursive:!0,force:!0}),Oi.rm(Ks(e,t),{recursive:!0,force:!0}),...i.map(n=>Oi.rm(hE.join(fe(e,t),n),{force:!0}))])}async function up(e,t){await Me(St(e,t.name),Qe({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function dp(e,t){try{let r=await bi(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 fp(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let r=j(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 vE(e){let t=fe(e.paths,e.state.name),r=await H({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 H({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return la({briefMarkdown:r.text,specs:i})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function hp(e,t){let r=await xa(e,t);if(!r.state)throw new Error(`Native legacy change ${t} is unreadable`);return r.state}async function pp(e){return K(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await mE(e.paths,e.name),r=await ji(e.paths,e.name)?await Q(he(e.paths,e.name)):null;if(!t&&r)return await lp(e.paths,e.name,{removeVerificationReport:!1}),await up(e.paths,r),r;let i=null,n=null;for(t||(i=await hp(e.paths,e.name),n=await dp(e.paths,e.name),fp(e.paths,n),t={schema:ma,id:fE(),change:i.name,fromSchema:i.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await cp(e.paths,t));;){let a=Jf(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?r||(i??=await hp(e.paths,e.name),n??=await dp(e.paths,e.name),fp(e.paths,n),r=zf({state:i,acceptance:await vE({paths:e.paths,state:i}),workspace:n,migratedAt:e.now}),await pa(he(e.paths,e.name),r,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await lp(e.paths,e.name):a.action==="commit-transaction"&&(r??=await Q(he(e.paths,e.name)),await up(e.paths,r)),t={...t,status:a.nextStatus},await cp(e.paths,t)}return await Oi.rm(Lt(e.paths,{kind:"migration",change:e.name}),{force:!0}),r??Q(he(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as vp}from"node:fs";import gp from"node:path";import{promises as Uc}from"node:fs";import gE from"node:path";var wE=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),yE=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),NE=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task"]),bE=new Set(["status","summary"]);function Wa(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function za(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 kE(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((r,i)=>r===t[i])}function Jt(e,t,r){return{status:"incompatible",file:e,snapshot:t,message:r}}function SE(e,t,r,i){let n=Wa(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=za(n,wE,"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=Wa(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=za(o,yE,"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=Wa(n.finalVerification,"Native Supervisor finalVerification");if(!c)return"Native Supervisor finalVerification must be an object";let l=za(c,bE,"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=Wa(u,`Native Supervisor child ${f}`);if(!d)return`Native Supervisor child ${f} must be an object`;let m=za(d,NE,`Native Supervisor child ${f}`);if(m)return m;let v=r.children[f];if(d.name!==v.name||d.summary!==v.summary||!kE(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 Kc(e){let t=Ta(e.paths,e.state.name),r;try{let c=await Uc.lstat(t);if(!c.isFile()||c.isSymbolicLink())return Jt(t,"","Native Supervisor overlay is not a regular file");r=await Uc.readFile(t,"utf8")}catch(c){return c.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:Jt(t,"",`Native Supervisor overlay cannot be read: ${c.message}`)}let i;try{i=JSON.parse(r)}catch(c){return Jt(t,r,`Native Supervisor overlay is invalid JSON: ${c.message}`)}let n=gE.join(e.paths.changesDir,e.state.name),a;try{a=await br({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:c})=>c),policy:"advisory"})}catch(c){return Jt(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 Fe(e.paths,e.state.name)}catch(c){return Jt(t,r,`Native Supervisor overlay is invalid: ${c.message}`)}if(!o)return Jt(t,r,"Native Supervisor overlay disappeared during inspection");let s=SE(i,e.state,a.contract,o);return s?Jt(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 mp(e){let t=await Kc({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 Uc.rm(t.file,{force:!1})}function EE(e,t){let r=j(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 PE(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function xE(e,t,r){let i=new Date().toISOString(),n=e.verification===null?e:Dt(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:Ke(t),completed_at:i});return se({...n,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:r?PE(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 RE(e){try{let t=await Hc(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 wp(e){return K(e.paths,`recover portable change ${e.name}`,async()=>{let t=await Ie(e.paths,e.name);if(t.status==="done")return await qa({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=EE(e.paths,t);if(r)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:r};let i=await Kc({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 mp({paths:e.paths,state:t,expected:i}),n=!0);let a=St(e.paths,e.name),o=await RE(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 Me(a,o.local,{containedRoot:e.paths.runtimeDir}))),s==="available")return await qa({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=Tc({state:t,reason:`Check ${l.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await Bt({file:he(e.paths,t.name),expectedStateVersion:t.state_version,next:v,containedRoot:e.paths.nativeRoot}),await vp.rm(gp.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let h=Qe({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await Me(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=xE(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 Bt({file:he(e.paths,t.name),expectedStateVersion:t.state_version,next:v,containedRoot:e.paths.nativeRoot})}let m=Qe({portableState:t,projectRoot:e.paths.projectRoot,branch:j(e.paths.projectRoot).currentBranch});return await vp.mkdir(gp.dirname(St(e.paths,t.name)),{recursive:!0}),await Me(a,m,{containedRoot:e.paths.runtimeDir}),await qa({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{accessSync as DE,constants as BE,promises as LE}from"node:fs";import We from"node:path";import{execFileSync as CE}from"node:child_process";import yp from"node:path";var AE=6e4,_E=8*1024*1024,Yc=class extends Error{constructor(r,i,n,a){super(`${r} ${i.join(" ")} failed${n?`: ${n}`:""}`,a);this.command=r;this.args=i;this.stderr=n;this.name="ExternalCommandError"}command;args;stderr};function Er(e,t,r={}){let i=r.timeoutMs??AE,n=r.maxBufferBytes??_E;if(!Number.isSafeInteger(i)||i<1)throw new Error("External command timeout must be a positive integer");if(!Number.isSafeInteger(n)||n<1)throw new Error("External command max buffer must be a positive integer");let a=yp.resolve(r.cwd??process.cwd()),o=r.env??process.env,s=process.platform==="win32"?Fh(e,o,a):e,c=yp.win32.extname(s).toLowerCase(),l=c===".bat"||c===".cmd";process.platform==="win32"&&l&&Vh(t);try{return CE(s,[...t],{cwd:a,env:o,...r.input!==void 0?{input:r.input}:{},encoding:"utf8",stdio:[r.input===void 0?"ignore":"pipe","pipe","pipe"],timeout:i,maxBuffer:n,windowsHide:!0,shell:process.platform==="win32"&&l})}catch(f){let u=typeof f.stderr=="string"?f.stderr.trim():Buffer.isBuffer(f.stderr)?f.stderr.toString("utf8").trim():"";throw new Yc(e,t,u,{cause:f})}}var IE=6e4,z=class extends Error{constructor(r,i,n){super(r,n);this.pullRequest=i;this.name="NativePullRequestFinishError"}pullRequest};function Xc(e,t){try{return Er("gh",t,{cwd:e,timeoutMs:IE}).trim()}catch(r){throw new Error(`gh ${t.join(" ")} failed: ${r.message}`,{cause:r})}}function Qc(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a JSON object`);return e}function Zc(e,t){try{return JSON.parse(e)}catch(r){throw new Error(`${t} must be valid JSON`,{cause:r})}}function Np(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Gt(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be a non-empty string`);return e}function bp(e,t){let r=Gt(e,t),i;try{i=new URL(r)}catch(n){throw new Error(`${t} must be an absolute HTTP URL`,{cause:n})}if(i.protocol!=="https:"&&i.protocol!=="http:")throw new Error(`${t} must be an absolute HTTP URL`);return r}function Ga(e,t){let r=Gt(e,t);if(!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/iu.test(r))throw new Error(`${t} must be a Git object ID`);return r.toLowerCase()}function kp(e,t){let r=Qc(e,t);if(Gt(r.state,`${t}.state`)!=="OPEN")throw new Error(`${t}.state must be OPEN`);return{number:Np(r.number,`${t}.number`),url:bp(r.url,`${t}.url`),baseBranch:Gt(r.baseRefName,`${t}.baseRefName`),headBranch:Gt(r.headRefName,`${t}.headRefName`),headSha:Ga(r.headRefOid,`${t}.headRefOid`),state:"OPEN"}}function TE(e){let t=Qc(e,"pull request finish provider output.pullRequest");return{number:Np(t.number,"pull request finish provider output.pullRequest.number"),url:bp(t.url,"pull request finish provider output.pullRequest.url"),baseBranch:Gt(t.baseBranch,"pull request finish provider output.pullRequest.baseBranch"),headBranch:Gt(t.headBranch,"pull request finish provider output.pullRequest.headBranch"),headSha:Ga(t.headSha,"pull request finish provider output.pullRequest.headSha")}}function jE(e){let t=Qc(Zc(e,"pull request finish provider output"),"pull request finish provider output");if(t.schema!=="comet.native.pull-request-finish-result.v1")throw new Error("pull request finish provider output.schema must be comet.native.pull-request-finish-result.v1");if(t.disposition!=="created"&&t.disposition!=="reused")throw new Error("pull request finish provider output.disposition must be created or reused");if(t.remoteVerified!==!0)throw new Error("pull request finish provider did not confirm repository-owned remote verification");let r=TE(t.pullRequest);return{schema:"comet.native.pull-request-finish-result.v1",disposition:t.disposition,remoteVerified:!0,pullRequest:r}}function el(e){let t=Xc(e.projectRoot,["pr","list","--state","open","--base",e.baseBranch,"--head",e.headBranch,"--limit","2","--json","number,url,baseRefName,headRefName,headRefOid,state"]),r=Zc(t,"gh pr list output");if(!Array.isArray(r))throw new Error("gh pr list output must be a JSON array");if(r.length>1)throw new Error(`Multiple open pull requests match ${e.headBranch} -> ${e.baseBranch}`);return r.length===0?null:kp(r[0],"gh pr list output[0]")}function Sp(e){let t=Xc(e.projectRoot,["pr","view",String(e.pullRequest.number),"--json","number,url,baseRefName,headRefName,headRefOid,state"]),r=kp(Zc(t,"gh pr view output"),"gh pr view output"),i=Ga(e.headSha,"Native Archive head SHA");if(r.number!==e.pullRequest.number||r.url!==e.pullRequest.url)throw new z("Pull request provider result does not match the pull request observed from GitHub",r);if(r.baseBranch!==e.baseBranch)throw new z(`Pull request base branch mismatch: expected ${e.baseBranch}, got ${r.baseBranch}`,r);if(r.headBranch!==e.headBranch)throw new z(`Pull request head branch mismatch: expected ${e.headBranch}, got ${r.headBranch}`,r);if(r.headSha!==i)throw new z(`Pull request head SHA mismatch: expected ${i}, got ${r.headSha}`,r);return r}function Ja(e){try{return el(e)}catch{return null}}function $E(e){return JSON.stringify({schema:"comet.native.pull-request-finish-input.v1",projectRoot:e.projectRoot,change:{name:e.changeName,branch:e.headBranch,headSha:e.headSha},target:{branch:e.baseBranch},remote:e.remote,transactionId:e.transactionId,existingPullRequest:e.existingPullRequest},null,2)}function OE(e){let t=e.existingPullRequest,r=t?"reused":"created";if(!t)try{let a=Xc(e.projectRoot,["pr","create","--base",e.baseBranch,"--head",e.headBranch,"--fill"]).split(/\r?\n/u).map(o=>o.trim()).find(o=>/^https?:\/\//u.test(o));if(!a)throw new Error("GitHub CLI did not return a pull request URL");if(t=el(e),!t)throw new Error("GitHub CLI created a pull request that could not be observed uniquely");if(t.url!==a)throw new z("GitHub CLI returned a pull request URL that does not match the remotely observed pull request",t)}catch(n){if(n instanceof z)throw n;let a=Ja(e);if(!a)throw new z(n.message,null,{cause:n});t=a,r="reused"}let i;try{i=Sp({...e,pullRequest:t})}catch(n){throw n instanceof z?n:new z(`Final GitHub pull request verification failed: ${n.message}`,t,{cause:n})}return{provider:"github-fill",disposition:r,pullRequest:i,remoteVerified:!0}}function HE(e){let[t,...r]=e.config.command,i;try{let o=Er(t,r,{cwd:e.projectRoot,timeoutMs:e.config.timeout_ms,input:`${$E(e)}
|
|
211
|
+
`}).trim();i=jE(o)}catch(o){if(o instanceof z)throw o;let s=Ja(e)??e.existingPullRequest;throw new z(`Repository pull request finish provider failed: ${o.message}`,s,{cause:o})}let n={...i.pullRequest,state:"OPEN"};if(n.baseBranch!==e.baseBranch||n.headBranch!==e.headBranch||n.headSha!==Ga(e.headSha,"Native Archive head SHA")){let o=Ja(e)??e.existingPullRequest;throw new z("Repository pull request finish provider returned a pull request outside the authorized base, head, or head SHA",o)}let a;try{a=Sp({...e,pullRequest:n})}catch(o){if(o instanceof z)throw o;let s=Ja(e)??e.existingPullRequest??n;throw new z(`Final repository pull request verification failed: ${o.message}`,s,{cause:o})}return{provider:"repository-command",disposition:i.disposition,pullRequest:a,remoteVerified:!0}}function Ep(e){let t=el(e);return e.config?HE({...e,existingPullRequest:t,config:e.config}):OE({...e,existingPullRequest:t})}var Hi=class extends Error{constructor(r){super(r.message??"Native workspace finish is blocked");this.result=r;this.name="NativeWorkspaceFinishError"}result},it=class extends Error{constructor(r,i,n="Native workspace finish is blocked"){super(`${n}; remaining paths: ${r.join(", ")}`);this.paths=r;this.workspaceRoot=i;this.name="NativeWorkspaceFinishPreparationError"}paths;workspaceRoot};function tl(e,t){let r=We.relative(e,t);return r===""||!We.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${We.sep}`)}function Ut(e,t){let r=We.relative(e,t).replaceAll("\\","/");if(!r||r===".."||r.startsWith("../")||We.isAbsolute(r))throw new Error(`Native workspace finish path escaped the project: ${t}`);return r}function Cp(e,t){return t.some(r=>e===r||e.startsWith(`${r}/`))}function Pp(e,t,r){let i=[Ut(e.projectRoot,fe(e,t.name)),Ut(e.projectRoot,Fc(e))];return r&&i.push(Ut(e.projectRoot,r)),i}function xp(e,t){let r=Ca(e).filter(i=>!Cp(i,t));if(r.length>0)throw new it(r,e)}function qE(e,t){return t.map(r=>We.resolve(e,...r.split("/")))}function FE(e){let t=Ca(e);if(t.length>0)throw new it(qE(e,t),e,`Native merge target worktree is not clean: ${e}`)}function Ap(e){return e.split("\0").filter(Boolean)}function VE(e,t){return Ap(x(e,["ls-files","-z","--",t]))}function ME(e,t){return Ap(x(e,["ls-files","--others","--exclude-standard","-z","--",t]))}function Rp(e){try{if(x(e,["config","--get","user.name"])&&x(e,["config","--get","user.email"]))return}catch{}throw new Error("Native workspace finish requires configured Git user.name and user.email")}function WE(e,t){for(let r of le(e))if(j(r).currentBranch===t)return r;return null}function zE(e,t){try{Er(e,t,{timeoutMs:1e4})}catch(r){throw new Error(`${e} is required for the selected Native workspace finish`,{cause:r})}}function JE(e,t){if(!t)return;let r=t.command[0];try{if(We.posix.isAbsolute(r)||We.win32.isAbsolute(r))throw new Error("configured executable must not be an absolute path");if(/[\\/]/u.test(r)){let n=We.resolve(e,r);if(!tl(e,n))throw new Error("configured executable escapes the project root");DE(n,BE.X_OK);return}Er(process.platform==="win32"?"where":"which",[r],{timeoutMs:1e4})}catch(i){throw new Error(`Configured Native pull request finish executable is not available: ${r}`,{cause:i})}}async function Ua(e){let{paths:t,state:r}=e,i=r.workspace,n=j(t.projectRoot);if(i.isolation==="current"){if(!n.isGitWorktree)return null;if(!n.primaryWorktreeRoot||!n.currentBranch)throw new Error("Native current workspace finish requires a registered Git branch");Rp(t.projectRoot);let c=Pp(t,r,e.archiveDir);return xp(t.projectRoot,c),{finish:"keep",changeRoot:t.projectRoot,primaryRoot:n.primaryWorktreeRoot,changeBranch:n.currentBranch,targetBranch:n.currentBranch,targetRoot:t.projectRoot,remote:null,isolation:"current",pullRequestFinish:null}}if(!i.finish||!i.change_branch||!i.target_branch)throw new Error("Native isolated workspace finish is not persisted");if(i.change_branch===i.target_branch)throw new Error("Native change and target branches must be different for workspace finish");if(!n.primaryWorktreeRoot||n.currentBranch!==i.change_branch)throw new Error(`Native workspace finish requires branch ${i.change_branch} in the current registered worktree`);Rp(t.projectRoot);let a=Pp(t,r,e.archiveDir);xp(t.projectRoot,a);let o=i.isolation==="branch"?t.projectRoot:WE(n.primaryWorktreeRoot,i.target_branch);if(i.finish==="merge"&&i.isolation==="worktree"){if(!o)throw new Error(`Native merge finish requires a registered worktree on target branch ${i.target_branch}`);FE(o)}let s=i.finish==="push"||i.finish==="pull-request"?gh(t.projectRoot,i.change_branch):null;return i.finish==="pull-request"&&(zE("gh",["--version"]),JE(t.projectRoot,e.pullRequestFinish)),{finish:i.finish,changeRoot:t.projectRoot,primaryRoot:n.primaryWorktreeRoot,changeBranch:i.change_branch,targetBranch:i.target_branch,targetRoot:o,remote:s,isolation:i.isolation,pullRequestFinish:e.pullRequestFinish??null}}async function GE(e){try{return await LE.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function UE(e){return{action:e.finish,status:e.finish==="keep"?"kept":"completed",commit:null,remote:e.remote,pushed:!1,pullRequestUrl:null,pullRequest:null,merged:!1,targetRoot:e.targetRoot,cleanup:{performed:!1,reason:null},blockedPaths:[],message:null,recoveryArgs:null}}function KE(e){if(e.isolation!=="worktree")return{performed:!1,reason:null};if(tl(e.changeRoot,process.cwd()))return{performed:!1,reason:"invocation-working-directory-is-the-change-worktree"};try{return x(e.primaryRoot,["worktree","remove",e.changeRoot]),{performed:!0,reason:null}}catch(t){return{performed:!1,reason:`worktree-cleanup-failed: ${t.message}`}}}async function _p(e){let t=UE(e.plan),r=null;try{let i=[Ut(e.paths.projectRoot,fe(e.paths,e.name)),Ut(e.paths.projectRoot,e.archiveDir),...e.state.spec_changes.map(l=>Ut(e.paths.projectRoot,Ra(e.paths,l.capability))),Ut(e.paths.projectRoot,Fc(e.paths))],n=Ca(e.plan.changeRoot).filter(l=>!Cp(l,i));if(n.length>0)throw t.blockedPaths=n,new Error(`Native Archive produced or encountered paths outside the authorized finish scope: ${n.join(", ")}`);let a=[],o=new Set;for(let l of i){let f=We.resolve(e.paths.projectRoot,...l.split("/"));if(VE(e.plan.changeRoot,l).length>0&&a.push(l),await GE(f))for(let d of ME(e.plan.changeRoot,l))o.add(d)}if(a.length>0&&x(e.plan.changeRoot,["add","-u","--",...a]),o.size>0&&x(e.plan.changeRoot,["add","--",...o]),x(e.plan.changeRoot,["diff","--cached","--name-only","-z"])&&x(e.plan.changeRoot,["commit","-m",`chore(native): archive ${e.name}`]),t.commit=x(e.plan.changeRoot,["rev-parse","HEAD"]),!Vt(e.plan.changeRoot))throw new Error("Native archive commit left unexpected working-tree changes");if(e.plan.finish==="keep")return t;if(e.plan.finish==="push"||e.plan.finish==="pull-request"){x(e.plan.changeRoot,["push","--set-upstream",e.plan.remote,e.plan.changeBranch]),t.pushed=!0,e.plan.finish==="pull-request"&&(t.pullRequest=Ep({projectRoot:e.plan.changeRoot,changeName:e.name,transactionId:e.transactionId,remote:e.plan.remote,baseBranch:e.plan.targetBranch,headBranch:e.plan.changeBranch,headSha:t.commit,config:e.plan.pullRequestFinish}),t.pullRequestUrl=t.pullRequest.pullRequest.url);let l=tl(e.plan.changeRoot,process.cwd());return e.plan.isolation==="worktree"&&!l?(x(e.plan.primaryRoot,["worktree","remove",e.plan.changeRoot]),t.cleanup={performed:!0,reason:null}):e.plan.isolation==="worktree"&&(t.cleanup={performed:!1,reason:"invocation-working-directory-is-the-change-worktree"}),t}let c=e.plan.targetRoot??e.plan.changeRoot;return e.plan.isolation==="branch"&&(x(c,["switch",e.plan.targetBranch]),r=c),x(c,["merge","--no-ff","--no-edit",e.plan.changeBranch]),t.merged=!0,t.targetRoot=c,t.cleanup=KE(e.plan),t}catch(i){if(i instanceof z&&i.pullRequest&&(t.pullRequestUrl=i.pullRequest.url),r!==null){let n;try{x(r,["merge","--abort"])}catch{}try{j(r).currentBranch===e.plan.targetBranch&&x(r,["switch",e.plan.changeBranch]),n=j(r).currentBranch===e.plan.changeBranch}catch{n=!1}n||(t.targetRoot=r)}throw t.status="blocked",t.message=i.message,t.recoveryArgs=e.plan.finish==="pull-request"?["comet","native","archive",e.name,"--confirmed"]:e.plan.finish==="merge"&&t.targetRoot?["git","-C",t.targetRoot,"status","--short"]:["git","-C",e.plan.changeRoot,"status","--short"],new Hi(t)}}import Bi from"path";import{realpathSync as VP}from"fs";var nt={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function Ip(e){return e?e.command?`${nt.next} ${e.command}`:e.ask_user?`${nt.next} ${e.ask_user}`:null:null}function Tp(e,t){let r=[e.summary],i=Ip(e.next);return i&&r.push(i),e.user_message&&r.push("",nt.relay,e.user_message),t!==void 0&&r.push("",nt.details,JSON.stringify(t,null,2)),`${r.join(`
|
|
212
212
|
`)}
|
|
213
|
-
`}function
|
|
214
|
-
`)}var
|
|
215
|
-
`)}}let r=t.continuation;if(
|
|
216
|
-
comet native next <change-name> --
|
|
217
|
-
comet native
|
|
213
|
+
`}function jp(e,t,r){let i=[e.summary],n=Ip(e.next);return n&&i.push(n),e.user_message&&i.push("",nt.relay,e.user_message),i.push("",`${nt.detail} ${t}`),r!==void 0&&i.push("",nt.details,JSON.stringify(r,null,2)),i.join(`
|
|
214
|
+
`)}var YE=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 $p=1024*1024;var Hp="scoped-text-safety",XE=1,QE=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var ZE="comet.native.checker-policy.v1";var k0=V(ZE,{policy:Hp,version:XE,limits:QE,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var eP=["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"],S0=new Set(eP);var iP=$p,q0=3*iP;var Dp={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:[]},aP=Ne("comet-native-runtime:v3:scope-reopen"),hH=[{skillVersion:"3",skillHash:Ne("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:Ne("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:Ne("comet-native-runtime:v1")}];var Lp=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],GH=new Set(Lp),fP=new Set([...Lp,"minimum_runtime_version","revision"]),UH=new Set([...fP,"operation"]),KH=512*1024,hP=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),YH=new Set([...hP,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);var tD={maxAcceptanceCriteria:ca.maxCriteria};var oD={maxSpecs:64,maxFileBytes:Mi,maxTotalBytes:4*1024*1024};import{execFile as kP}from"node:child_process";import{promisify as SP}from"node:util";var vD={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};var DD=512*1024;var Di=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};var oB=64*1024;var sB=3600*1e3;var cB=SP(kP);var Ka=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 GB={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var iL=16*1024*1024,nL=256*1024,aL=16*1024;var dL=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var eq=16*1024*1024,Ya=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"},Xa=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 rl={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function Vp(e,t){return typeof e=="string"&&rl[e]?R(t,rl[e].en,rl[e].zh):typeof e=="string"?e:""}function il(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 CP(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 Mp(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 Wp(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 nl(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function AP(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 _P(e,t,r){let i=nl(e),n=[];r&&n.push(r);let a=R(i,`Change ${e.change}`,`需求 ${e.change}`),o=Vp(e.phase,i),s=AP(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(Mp(t,i));let c=e.userCommunication,l=zp(e,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function zp(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 IP(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function TP(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=Vp(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=il(e.acceptance)?`${R(t,", ",",")}${Mp(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function jP(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 $P(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 OP(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=HP(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 HP(e){return Wp(e)?zp(e,nl(e)):void 0}function Jp(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if($P(t))return OP(t);if(IP(t)){let i=jP(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=>TP(a,i))].join(`
|
|
215
|
+
`)}}let r=t.continuation;if(Wp(r))return _P(r,DP(t),BP(t,nl(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 DP(e){if(il(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(il(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return CP(r.acceptance)}return null}function BP(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 Gp(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 Up=["--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."],ol=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:Up,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>]
|
|
216
|
+
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>]
|
|
217
|
+
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]
|
|
218
|
+
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 al(e,t){return`${e}:
|
|
218
219
|
${t.map(r=>` ${r}`).join(`
|
|
219
|
-
`)}`}function
|
|
220
|
-
${r.output}`),r.examples&&i.push("",
|
|
220
|
+
`)}`}function LP(e){let t=e.filter(i=>i!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return ol[r]||t.length>1&&ol[t[0]]?.subcommands?r:t[0]}function qP(e=[]){let t=LP(e),r=ol[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.subcommands&&i.push("",al("Commands",r.subcommands));let n=t===""?r.options:[...r.options??[],...Up];return n&&n.length>0&&i.push("",al("Options",n)),i.push("",`Output:
|
|
221
|
+
${r.output}`),r.examples&&i.push("",al("Examples",r.examples)),t===""&&i.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${i.join(`
|
|
221
222
|
`)}
|
|
222
|
-
`}}var
|
|
223
|
-
`}function
|
|
224
|
-
`}:e.error?{exitCode:e.exitCode,stderr:i?
|
|
225
|
-
${
|
|
223
|
+
`}}var FP=qP().usage;var yq=10*1024*1024,J=class extends Error{};function Pr(e,t){let r=e.flatMap((i,n)=>i===t?[n]:[]);if(r.length>1)throw new J(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function xr(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new J(`${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 J(`${t} requires a value`);return e.splice(i,2),n}function cl(e){if(e.length>0)throw new J(`Unexpected argument: ${e[0]}`)}function Yp(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new J(`${t} is required`);return r}function sl(e,t){let r=Bi.normalize(Kp(e)),i=Bi.normalize(Kp(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function Kp(e){let t=Bi.resolve(e);try{return VP.native(t)}catch{return t}}function MP(e){let t=Bi.resolve(e),r=j(process.cwd());if(!r.isSecondaryWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null)return t;let i=j(t);return!i.isGitWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null||!sl(r.primaryWorktreeRoot,i.primaryWorktreeRoot)||sl(r.currentWorktreeRoot,i.currentWorktreeRoot)?t:sl(process.cwd(),r.currentWorktreeRoot)?Bi.resolve(process.cwd()):r.currentWorktreeRoot}async function Xp(e){return e?MP(e):ta(process.cwd())}async function Qp(e){let t=await Nf({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function Zp(e){return JSON.stringify(e,null,2)+`
|
|
224
|
+
`}function Rr(e,t,r){return{command:e,exitCode:0,data:t,text:r??Zp(t)}}function WP(e,t){if(t instanceof J)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Ya)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 Xa)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof Ea)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 ki)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 _a)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Pa)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 Ka)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof Di)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 em(e,t){let r=WP(e,t),i=r.error;if(!i)return r;let n=Gp({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function tm(e,t,r=!1){let i=e.envelope??Jp(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}})+`
|
|
225
|
+
`}:e.error?{exitCode:e.exitCode,stderr:i?jp(i,e.error.message,r?e.data:void 0):e.error.message}:i?{exitCode:e.exitCode,stdout:Tp(i,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==Zp(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
|
|
226
|
+
${nt.details}
|
|
226
227
|
${JSON.stringify(e.data,null,2)}
|
|
227
|
-
`}:{exitCode:e.exitCode,stdout:e.text}}async function
|
|
228
|
-
`);if(i){if(!h)return
|
|
229
|
-
`);
|
|
230
|
-
`)}if(l.config.native.archive_confirmation==="required"&&!a)throw new
|
|
231
|
-
`)}if(s)throw new
|
|
232
|
-
`)}async function
|
|
228
|
+
`}:{exitCode:e.exitCode,stdout:e.text}}async function rm(e,t){let r=Yp(e,"change name"),i=Pr(e,"--dry-run"),n=xr(e,"--expect-preflight"),a=Pr(e,"--confirmed"),o=xr(e,"--finish"),s=xr(e,"--serial-first");if(s!==void 0&&!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(s))throw new J("--serial-first must be one Native change name");let c=o;if(c!==void 0&&c!=="merge"&&c!=="push"&&c!=="pull-request"&&c!=="keep")throw new J("--finish must be merge, push, pull-request, or keep");let l=await Qp(t),f=await ji(l.paths,r),u=f?await Nt(l.paths,{kind:"archive",change:r}):null,d=f?!1:await rp(l.paths,r);if(f||d){if(n)throw new J("Portable Native Archive does not use preflight hashes");if(i&&a)throw new J("--confirmed is only valid when executing Archive");if(i&&s)throw new J("--serial-first is only valid when executing Archive");if(!i&&c)throw new J("--finish is only valid with --dry-run");cl(e);let v=f&&!i&&u?.kind!=="archive"?await wp({paths:l.paths,name:r}):null,h=v?.state??(f?await Ie(l.paths,r):null);if(v?.action==="reverify"||v?.action==="await-user")return Rr(i?"archive --dry-run":"archive",{archived:!1,state:v.state,recovery:v,continuation:rt(v.state)},`${v.message}
|
|
229
|
+
`);if(i){if(!h)return Rr("archive --dry-run",{change:r,ready:!0,archiveRecovery:!0,continuation:{disposition:"continue",reason:"Resume the interrupted Native Archive transaction.",commandArgs:["comet","native","archive",r,"--confirmed"],inputOptions:[],runnerAction:null}},`Native Archive recovery is ready for ${r}
|
|
230
|
+
`);c&&(h=await Uh({paths:l.paths,name:r,finish:c}));let w=await Jc({paths:l.paths,name:r}),S="capabilities are also declared by:",E=w.blockers.filter(A=>!A.startsWith(S)),P=[],k=h.workspace.isolation!=="current"&&h.workspace.finish===null;if(k&&E.push("Native branch and worktree isolation require a workspace finish choice"),!k)try{await Ua({paths:l.paths,state:h,pullRequestFinish:l.config.native.finish?.pull_request})}catch(A){let Cr=A.message;E.push(Cr),P.push({message:Cr,paths:A instanceof it?A.paths:[],workspaceRoot:A instanceof it?A.workspaceRoot:l.paths.projectRoot})}let T=w.capabilityPeers.length>0&&E.length===0?rt(h,null,{archiveMode:"preview"}):null,Z=T?{...T,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["choose-first-archive"],runnerAction:{...T.runnerAction,kind:"none"}}:k?rt(h):rt(h,null,{archiveMode:"preview",archiveBlockers:E}),pe=[...E,...w.capabilityPeers.length>0?[`${S} ${w.capabilityPeers.join(", ")}`]:[]];return Rr("archive --dry-run",{...w,ready:pe.length===0,blockers:pe,...P.length>0?{workspaceFinishBlockers:P}:{},workspaceFinish:h.workspace.finish,continuation:Z},`Native Archive preview: ${pe.length===0?"ready":"blocked"}
|
|
231
|
+
`)}if(l.config.native.archive_confirmation==="required"&&!a)throw new J("archive requires --confirmed when native.archive_confirmation is required");if(h&&h.workspace.isolation!=="current"&&h.workspace.finish===null){let w=rt(h);return{command:"archive",exitCode:65,data:{change:r,archived:!1,workspaceFinish:null,continuation:w},error:{code:"usage",message:"Native branch and worktree isolation require a workspace finish choice; follow continuation.commandAlternatives and run its dry-run command"}}}let p=null;if(h)try{p=await Ua({paths:l.paths,state:h,pullRequestFinish:l.config.native.finish?.pull_request})}catch(w){let S=w.message,E=w instanceof it?w.paths:[],P=w instanceof it?w.workspaceRoot:l.paths.projectRoot,k={action:h.workspace.finish??"keep",status:"blocked",commit:null,remote:null,pushed:!1,pullRequestUrl:null,pullRequest:null,merged:!1,targetRoot:P,cleanup:{performed:!1,reason:null},blockedPaths:E,message:S,recoveryArgs:["git","-C",P,"status","--short"]};return{command:"archive",exitCode:73,data:{change:r,archived:!1,state:h,workspaceFinish:h.workspace.finish,workspaceFinishResult:k,continuation:rt(h,null,{archiveMode:"blocked",archiveBlockers:[S]})},error:{code:"conflict",message:S}}}let y;try{y=await np({paths:l.paths,name:r,...s?{serialFirstChange:s}:{}})}catch(w){if(!(w instanceof $i)||!h)throw w;let S=await Jc({paths:l.paths,name:r}),E=w.peers.length>0?["comet","native","archive",r,"--confirmed","--serial-first",r]:["comet","native","archive",r,"--confirmed"];return{command:"archive",exitCode:73,data:{...S,workspaceFinish:h.workspace.finish,workspaceFinishResult:null,continuation:{disposition:"await-user",reason:w.message,commandArgs:E,inputOptions:w.peers.length>0?["serial-first-change"]:[],runnerAction:null}},error:{code:"conflict",message:w.message}}}h=y.state,!p&&h&&(p=await Ua({paths:l.paths,state:h,archiveDir:y.archiveDir,pullRequestFinish:l.config.native.finish?.pull_request}));let N=null;if(p)try{N=await _p({paths:l.paths,state:y.state,name:r,archiveDir:y.archiveDir,transactionId:y.transactionId,plan:p})}catch(w){if(!(w instanceof Hi))throw w;return{command:"archive",exitCode:73,data:{...y,workspaceFinish:y.state.workspace.finish,workspaceFinishResult:w.result,continuation:{disposition:"blocked",reason:w.message,commandArgs:w.result.recoveryArgs,inputOptions:[],runnerAction:null}},error:{code:"conflict",message:w.message}}}let g=N?.merged===!0?await Jh({childPaths:l.paths,childState:y.state}):null;return Rr("archive",{...y,workspaceFinish:y.state.workspace.finish,workspaceFinishResult:N,...g?{parentAdvance:g.parentAdvance}:{},...g?.parentState?{parentState:g.parentState}:{},continuation:rt(g?.parentState??y.state)},`Archived Native change ${r} to ${y.archiveDir}
|
|
232
|
+
`)}if(s)throw new J("--serial-first is only valid for portable Native changes");if(!i&&c)throw new J("--finish is only valid with --dry-run");if(cl(e),i)return{command:"archive --dry-run",exitCode:65,data:{change:r,migrationRequired:!0,repairCommand:`comet native doctor ${r} --repair`},error:{code:"invalid-data",message:`Native active change ${r} must migrate before Archive preview`}};let m=await pp({paths:l.paths,name:r});return Rr("archive",{migration:{from:"legacy",to:m.schema,completed:!0},state:m,continuation:rt(m)},`Migrated Native change ${r}; follow the returned portable continuation before Archive
|
|
233
|
+
`)}async function im(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{Pr(n,"--json"),Pr(n,"--verbose"),c=xr(n,"--project-root");let u=[...n,...a],d=await Xp(c);l=await t(u,d)}catch(u){l=em(e,u)}let f=tm(l,o,s);return f.stdout&&process.stdout.write(f.stdout),f.stderr&&process.stderr.write(f.stderr+(f.stderr.endsWith(`
|
|
233
234
|
`)?"":`
|
|
234
|
-
`)),
|
|
235
|
+
`)),f.exitCode}process.exitCode=await im("archive",rm);
|