@rpamis/comet 0.4.0-rc.2 → 0.4.0-rc.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +1 -1
- package/assets/manifest.json +1 -1
- package/assets/skills/comet/scripts/comet-archive.mjs +55 -55
- package/assets/skills/comet/scripts/comet-entry-runtime.mjs +1 -1
- package/assets/skills/comet/scripts/comet-guard.mjs +79 -79
- package/assets/skills/comet/scripts/comet-handoff.mjs +64 -64
- package/assets/skills/comet/scripts/comet-hook-guard.mjs +51 -51
- package/assets/skills/comet/scripts/comet-hook-router.mjs +123 -123
- package/assets/skills/comet/scripts/comet-resume-probe.mjs +48 -48
- package/assets/skills/comet/scripts/comet-runtime.mjs +128 -128
- package/assets/skills/comet/scripts/comet-state.mjs +60 -60
- package/assets/skills/comet/scripts/comet-yaml-validate.mjs +15 -15
- package/assets/skills/comet-native/SKILL.md +2 -2
- package/assets/skills/comet-native/reference/commands.md +3 -2
- package/assets/skills/comet-native/scripts/comet-native-archive.mjs +120 -120
- package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +126 -126
- package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +62 -62
- package/assets/skills/comet-native/scripts/comet-native-init.mjs +57 -57
- package/assets/skills/comet-native/scripts/comet-native-new.mjs +87 -87
- package/assets/skills/comet-native/scripts/comet-native-next.mjs +129 -129
- package/assets/skills/comet-native/scripts/comet-native-root.mjs +67 -67
- package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +157 -157
- package/assets/skills/comet-native/scripts/comet-native-select.mjs +98 -98
- package/assets/skills/comet-native/scripts/comet-native-show.mjs +88 -88
- package/assets/skills/comet-native/scripts/comet-native-spec.mjs +94 -94
- package/assets/skills/comet-native/scripts/comet-native-status.mjs +91 -91
- package/assets/skills-zh/comet-native/SKILL.md +2 -2
- package/assets/skills-zh/comet-native/reference/commands.md +3 -2
- package/dist/app/commands/bundle.d.ts.map +1 -1
- package/dist/app/commands/bundle.js.map +1 -1
- package/dist/app/commands/dashboard.d.ts +1 -1
- package/dist/app/commands/dashboard.js +1 -1
- package/dist/app/commands/doctor.d.ts.map +1 -1
- package/dist/app/commands/doctor.js +1 -1
- package/dist/app/commands/doctor.js.map +1 -1
- package/dist/app/commands/init.js +2 -2
- package/dist/app/commands/init.js.map +1 -1
- package/dist/app/commands/platform-select-prompt.d.ts.map +1 -1
- package/dist/app/commands/platform-select-prompt.js +1 -0
- package/dist/app/commands/platform-select-prompt.js.map +1 -1
- package/dist/app/commands/update.d.ts.map +1 -1
- package/dist/app/commands/update.js +12 -5
- package/dist/app/commands/update.js.map +1 -1
- package/dist/domains/agent-learning/policy-compiler.d.ts.map +1 -1
- package/dist/domains/agent-learning/policy-compiler.js.map +1 -1
- package/dist/domains/agent-learning/types.d.ts.map +1 -1
- package/dist/domains/agent-learning/types.js.map +1 -1
- package/dist/domains/bundle/authoring.d.ts.map +1 -1
- package/dist/domains/bundle/authoring.js.map +1 -1
- package/dist/domains/bundle/next-action.d.ts.map +1 -1
- package/dist/domains/bundle/next-action.js.map +1 -1
- package/dist/domains/bundle/readiness-user-summary.d.ts.map +1 -1
- package/dist/domains/bundle/readiness-user-summary.js.map +1 -1
- package/dist/domains/bundle/types.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-layout-initialization.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-layout-initialization.js.map +1 -1
- package/dist/domains/comet-entry/current-selection.d.ts.map +1 -1
- package/dist/domains/comet-entry/current-selection.js.map +1 -1
- package/dist/domains/comet-entry/init-workflow.d.ts.map +1 -1
- package/dist/domains/comet-entry/init-workflow.js.map +1 -1
- package/dist/domains/comet-entry/types.d.ts.map +1 -1
- package/dist/domains/comet-memory/personal-memory.d.ts.map +1 -1
- package/dist/domains/comet-memory/personal-memory.js.map +1 -1
- package/dist/domains/comet-memory/types.d.ts.map +1 -1
- package/dist/domains/comet-memory/types.js.map +1 -1
- package/dist/domains/comet-native/native-atomic-file.d.ts +1 -0
- package/dist/domains/comet-native/native-atomic-file.d.ts.map +1 -1
- package/dist/domains/comet-native/native-atomic-file.js +19 -0
- package/dist/domains/comet-native/native-atomic-file.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 +15 -4
- package/dist/domains/comet-native/native-children.js.map +1 -1
- package/dist/domains/comet-native/native-cli-help.js +1 -1
- package/dist/domains/comet-native/native-cli-help.js.map +1 -1
- package/dist/domains/comet-native/native-cli-shared.js.map +1 -1
- package/dist/domains/comet-native/native-evidence-storage.d.ts.map +1 -1
- package/dist/domains/comet-native/native-evidence-storage.js.map +1 -1
- package/dist/domains/comet-native/native-lock.d.ts.map +1 -1
- package/dist/domains/comet-native/native-lock.js +10 -1
- package/dist/domains/comet-native/native-lock.js.map +1 -1
- package/dist/domains/comet-native/native-loop-runtime.d.ts.map +1 -1
- package/dist/domains/comet-native/native-loop-runtime.js +21 -3
- 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 +35 -2
- package/dist/domains/comet-native/native-next-command.js.map +1 -1
- package/dist/domains/comet-native/native-output-language.d.ts.map +1 -1
- package/dist/domains/comet-native/native-output-language.js.map +1 -1
- package/dist/domains/comet-native/native-portable-archive.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-archive.js +17 -1
- package/dist/domains/comet-native/native-portable-archive.js.map +1 -1
- package/dist/domains/comet-native/native-portable-continuation.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-continuation.js +28 -29
- package/dist/domains/comet-native/native-portable-continuation.js.map +1 -1
- package/dist/domains/comet-native/native-portable-migration.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-migration.js.map +1 -1
- package/dist/domains/comet-native/native-portable-recovery.d.ts +1 -0
- package/dist/domains/comet-native/native-portable-recovery.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-recovery.js +2 -2
- package/dist/domains/comet-native/native-portable-recovery.js.map +1 -1
- package/dist/domains/comet-native/native-portable-runtime.d.ts +21 -0
- package/dist/domains/comet-native/native-portable-runtime.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-runtime.js +113 -3
- package/dist/domains/comet-native/native-portable-runtime.js.map +1 -1
- 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 +14 -27
- package/dist/domains/comet-native/native-runner-input.js.map +1 -1
- package/dist/domains/comet-native/native-schema-migration.d.ts.map +1 -1
- package/dist/domains/comet-native/native-schema-migration.js.map +1 -1
- package/dist/domains/comet-native/native-supervisor.d.ts +11 -1
- package/dist/domains/comet-native/native-supervisor.d.ts.map +1 -1
- package/dist/domains/comet-native/native-supervisor.js +61 -0
- package/dist/domains/comet-native/native-supervisor.js.map +1 -1
- package/dist/domains/comet-native/native-types.d.ts.map +1 -1
- package/dist/domains/comet-native/native-verification-receipt.d.ts.map +1 -1
- package/dist/domains/comet-native/native-verification-receipt.js.map +1 -1
- package/dist/domains/comet-native/native-workspace.d.ts.map +1 -1
- package/dist/domains/comet-native/native-workspace.js.map +1 -1
- package/dist/domains/comet-plugin/integration.d.ts +2 -0
- package/dist/domains/comet-plugin/integration.d.ts.map +1 -1
- package/dist/domains/comet-plugin/integration.js +10 -6
- package/dist/domains/comet-plugin/integration.js.map +1 -1
- package/dist/domains/dashboard/collector.js +1 -1
- package/dist/domains/dashboard/default-plugin-host.d.ts +3 -0
- package/dist/domains/dashboard/default-plugin-host.d.ts.map +1 -1
- package/dist/domains/dashboard/default-plugin-host.js +38 -4
- package/dist/domains/dashboard/default-plugin-host.js.map +1 -1
- package/dist/domains/dashboard/native-adapter.d.ts.map +1 -1
- package/dist/domains/dashboard/native-adapter.js.map +1 -1
- package/dist/domains/dashboard/web/assets/abnfDiagram-VCTEODGH-UcCx24DV.js +1 -0
- package/dist/domains/dashboard/web/assets/arc-n8qsRq7W.js +1 -0
- package/dist/domains/dashboard/web/assets/architecture-7GRP2DOG-B5p4GzJf.js +1 -0
- package/dist/domains/dashboard/web/assets/architectureDiagram-5GKGNRK7-D4pJ8CU0.js +36 -0
- package/dist/domains/dashboard/web/assets/array-BifhSqXX.js +1 -0
- package/dist/domains/dashboard/web/assets/blockDiagram-I7D4REHJ-C7n-qrSQ.js +129 -0
- package/dist/domains/dashboard/web/assets/browser-CgwPGwaV.js +107 -0
- package/dist/domains/dashboard/web/assets/c4Diagram-7LVT6UL2-cMVrWYOm.js +38 -0
- package/dist/domains/dashboard/web/assets/channel-BZeSeXVb.js +1 -0
- package/dist/domains/dashboard/web/assets/chunk-2Q5K7J3B-C1jixKkw.js +1 -0
- package/dist/domains/dashboard/web/assets/chunk-4HAMMTFA-CE5QrCQd.js +62 -0
- package/dist/domains/dashboard/web/assets/{chunk-5VM5RSS4-CopXcnFA.js → chunk-5VM5RSS4-ZNzvKenW.js} +2 -2
- package/dist/domains/dashboard/web/assets/chunk-75Z2AOVW-BtZqN-pM.js +2 -0
- package/dist/domains/dashboard/web/assets/chunk-DU6HZSFF-CChv0huc.js +125 -0
- package/dist/domains/dashboard/web/assets/chunk-F27PBJKO-CDT1ttJ8.js +1 -0
- package/dist/domains/dashboard/web/assets/chunk-FOHPRMQF-DHwB1DNv.js +161 -0
- package/dist/domains/dashboard/web/assets/chunk-GMAD6QVW-y5m6LMR7.js +72 -0
- package/dist/domains/dashboard/web/assets/chunk-GVQU2GXP-DkhKkaHd.js +1 -0
- package/dist/domains/dashboard/web/assets/chunk-IMKFNOWR-BaDSh7Jp.js +231 -0
- package/dist/domains/dashboard/web/assets/chunk-JWPE2WC7-DVXcaiue.js +1 -0
- package/dist/domains/dashboard/web/assets/chunk-L3NEJ4N5-B4ztH2fV.js +1 -0
- package/dist/domains/dashboard/web/assets/chunk-OSK3NFVY-BhX6NVzA.js +10 -0
- package/dist/domains/dashboard/web/assets/chunk-P2QGCYS3-BCNdGJkX.js +1 -0
- package/dist/domains/dashboard/web/assets/chunk-POPQ4Y6H-DwYVuiXw.js +1 -0
- package/dist/domains/dashboard/web/assets/chunk-PWAF6VOD-Cyg0IO0R.js +1 -0
- package/dist/domains/dashboard/web/assets/chunk-SHT3W25Y-BZ6skx8I.js +168 -0
- package/dist/domains/dashboard/web/assets/chunk-SVP7TREG-CLIGmSO0.js +88 -0
- package/dist/domains/dashboard/web/assets/chunk-TICWLB2K-BAQBbsn9.js +206 -0
- package/dist/domains/dashboard/web/assets/chunk-XXDRQBXY-D07UbEpV.js +1 -0
- package/dist/domains/dashboard/web/assets/chunk-Y2CYZVJY-DsF7k-Jl.js +1 -0
- package/dist/domains/dashboard/web/assets/classDiagram-ZZMXUADV-2fcinal6.js +1 -0
- package/dist/domains/dashboard/web/assets/classDiagram-v2-VYDZK3BY-2fcinal6.js +1 -0
- package/dist/domains/dashboard/web/assets/cose-bilkent-JH36ORCC-wIi0mUih.js +1 -0
- package/dist/domains/dashboard/web/assets/cynefin-OW5HDTMX-DBdxyuTN.js +1 -0
- package/dist/domains/dashboard/web/assets/cynefinDiagram-5FMLGOSQ-DzO3jXxV.js +62 -0
- package/dist/domains/dashboard/web/assets/cytoscape.esm-CGd-uY3x.js +321 -0
- package/dist/domains/dashboard/web/assets/dagre-GXQ25YYZ-CE7H_hZS.js +4 -0
- package/dist/domains/dashboard/web/assets/dagre-PrKaheQc.js +1 -0
- package/dist/domains/dashboard/web/assets/defaultLocale-BFoDCU3G.js +1 -0
- package/dist/domains/dashboard/web/assets/demo-DrJ2uuUL.js +456 -0
- package/dist/domains/dashboard/web/assets/diagram-S7CK7UJ4-jUGQk5n-.js +30 -0
- package/dist/domains/dashboard/web/assets/diagram-UQ7AKVKN-DaH_zW8T.js +41 -0
- package/dist/domains/dashboard/web/assets/diagram-VSXAHHWV-DmG80db0.js +3 -0
- package/dist/domains/dashboard/web/assets/diagram-VX7I27RA-ltQ6niKn.js +24 -0
- package/dist/domains/dashboard/web/assets/diagram-Z3DM3KII-x92ex4lK.js +24 -0
- package/dist/domains/dashboard/web/assets/dist-Cf0h0n6i.js +1 -0
- package/dist/domains/dashboard/web/assets/ebnfDiagram-PWID7BFC-CI2u976k.js +1 -0
- package/dist/domains/dashboard/web/assets/erDiagram-RLTQ6QDP-DKs90SRd.js +99 -0
- package/dist/domains/dashboard/web/assets/es-D7xGlyQk.js +10 -0
- package/dist/domains/dashboard/web/assets/eventmodeling-NTZA5JFV-uARcGZPD.js +1 -0
- package/dist/domains/dashboard/web/assets/flowDiagram-HODETNUW-DXL1E4Bl.js +1 -0
- package/dist/domains/dashboard/web/assets/ganttDiagram-EL5Y4UJY-D3z6G60S.js +292 -0
- package/dist/domains/dashboard/web/assets/gitGraph-4MIJSDKK-vT1UnORT.js +1 -0
- package/dist/domains/dashboard/web/assets/gitGraphDiagram-WWUBYQGX-BJmJ96jv.js +106 -0
- package/dist/domains/dashboard/web/assets/graphlib-DS17s2tU.js +1 -0
- package/dist/domains/dashboard/web/assets/index-BG3MF8re.js +261 -0
- package/dist/domains/dashboard/web/assets/index-C2Hlo7VZ.css +1 -0
- package/dist/domains/dashboard/web/assets/info-A6RAGUB7-DFeLqqen.js +1 -0
- package/dist/domains/dashboard/web/assets/infoDiagram-27XIBGKW-DxuY43XD.js +2 -0
- package/dist/domains/dashboard/web/assets/init-C-OQMol4.js +1 -0
- package/dist/domains/dashboard/web/assets/ishikawaDiagram-5VMMS53U-DxillfWQ.js +70 -0
- package/dist/domains/dashboard/web/assets/journeyDiagram-3NMN7TZE-BPngQ3ag.js +139 -0
- package/dist/domains/dashboard/web/assets/kanban-definition-UXKFOSKX-DHMLEGD4.js +89 -0
- package/dist/domains/dashboard/web/assets/katex-CXMH3UgJ.js +257 -0
- package/dist/domains/dashboard/web/assets/line-D31peBjo.js +1 -0
- package/dist/domains/dashboard/web/assets/linear-B7X50T2m.js +1 -0
- package/dist/domains/dashboard/web/assets/marked.esm-BtJme7Pf.js +65 -0
- package/dist/domains/dashboard/web/assets/mermaid-parser.core-CX3Pzygh.js +7 -0
- package/dist/domains/dashboard/web/assets/mermaid.core-DlMjBFb6.js +44 -0
- package/dist/domains/dashboard/web/assets/mindmap-definition-YA3MSWOX-BKuSGF75.js +96 -0
- package/dist/domains/dashboard/web/assets/ordinal-BDEzSJ7C.js +1 -0
- package/dist/domains/dashboard/web/assets/packet-AYTQ26CC-B1T8Bds9.js +1 -0
- package/dist/domains/dashboard/web/assets/path-fybaL0A-.js +1 -0
- package/dist/domains/dashboard/web/assets/pegDiagram-XKGWAZYB-BYgTNxLw.js +1 -0
- package/dist/domains/dashboard/web/assets/pie-WAS4IAKB-fqAjmoQw.js +1 -0
- package/dist/domains/dashboard/web/assets/pieDiagram-E7YTZNPT-BAO0Ufky.js +39 -0
- package/dist/domains/dashboard/web/assets/purify.es-ChwZkWde.js +3 -0
- package/dist/domains/dashboard/web/assets/quadrantDiagram-AXDQQJYC-SA_1-7DT.js +7 -0
- package/dist/domains/dashboard/web/assets/radar-RG4KPBEZ-Bl_UfUle.js +1 -0
- package/dist/domains/dashboard/web/assets/railroad-74A4TZTK-yj6dkiSy.js +1 -0
- package/dist/domains/dashboard/web/assets/railroad-abnf-HS5TGJTU-CvouMciM.js +1 -0
- package/dist/domains/dashboard/web/assets/railroad-ebnf-LZEXJU2U-CkYQEX72.js +1 -0
- package/dist/domains/dashboard/web/assets/railroad-peg-WCYAUIDC-B0uYr48F.js +1 -0
- package/dist/domains/dashboard/web/assets/railroadDiagram-O6MQD6OU-DqV18Y46.js +1 -0
- package/dist/domains/dashboard/web/assets/requirementDiagram-BXWQKSXE-Ca2K5LuT.js +84 -0
- package/dist/domains/dashboard/web/assets/rough.esm-Dy-Kn_BL.js +1 -0
- package/dist/domains/dashboard/web/assets/sankeyDiagram-P5KCCOFB-D9MKl-Nr.js +40 -0
- package/dist/domains/dashboard/web/assets/sequenceDiagram-WJ2MYXX4-CXfvIzRx.js +162 -0
- package/dist/domains/dashboard/web/assets/sizeCapture-INFHLROL-B0uUizjq.js +1 -0
- package/dist/domains/dashboard/web/assets/src-CquUPIQx.js +1 -0
- package/dist/domains/dashboard/web/assets/stateDiagram-D77RDMKH-B7iaZHW7.js +1 -0
- package/dist/domains/dashboard/web/assets/stateDiagram-v2-MP3YSRHH-B6KoHQVe.js +1 -0
- package/dist/domains/dashboard/web/assets/swimlanes-42K2YHIH-OK-62yZl.js +1 -0
- package/dist/domains/dashboard/web/assets/swimlanesDiagram-VR7AAH4N-CjdOls9K.js +8 -0
- package/dist/domains/dashboard/web/assets/timeline-definition-24CTP7MA-D0l01B1h.js +120 -0
- package/dist/domains/dashboard/web/assets/treeView-Q6P3EWNA-Bg5u_o3A.js +1 -0
- package/dist/domains/dashboard/web/assets/treemap-WGGIJYW6-x89ccozk.js +1 -0
- package/dist/domains/dashboard/web/assets/vennDiagram-4TSXK5OY-DV19Cqhv.js +34 -0
- package/dist/domains/dashboard/web/assets/wardley-WFR3VGLG-BWoeoVk5.js +1 -0
- package/dist/domains/dashboard/web/assets/wardleyDiagram-VM6X3IG4-D4fCpoIP.js +78 -0
- package/dist/domains/dashboard/web/assets/xychartDiagram-S5SC5T6Z-DALnOMLb.js +7 -0
- package/dist/domains/dashboard/web/index.html +16 -16
- package/dist/domains/factory/artifacts.d.ts.map +1 -1
- package/dist/domains/factory/artifacts.js.map +1 -1
- package/dist/domains/factory/types.d.ts.map +1 -1
- package/dist/domains/integrations/codegraph.d.ts.map +1 -1
- package/dist/domains/integrations/codegraph.js.map +1 -1
- package/dist/domains/project-knowledge/local-store.d.ts +21 -0
- package/dist/domains/project-knowledge/local-store.d.ts.map +1 -1
- package/dist/domains/project-knowledge/local-store.js +97 -0
- package/dist/domains/project-knowledge/local-store.js.map +1 -1
- package/dist/domains/project-knowledge/types.d.ts.map +1 -1
- package/dist/domains/skill/platform-inspect.d.ts +1 -1
- package/dist/domains/skill/platform-inspect.d.ts.map +1 -1
- package/dist/domains/skill/platform-inspect.js +50 -10
- package/dist/domains/skill/platform-inspect.js.map +1 -1
- package/dist/domains/skill/platform-install.d.ts +10 -5
- package/dist/domains/skill/platform-install.d.ts.map +1 -1
- package/dist/domains/skill/platform-install.js +107 -17
- package/dist/domains/skill/platform-install.js.map +1 -1
- package/dist/domains/skill/uninstall.d.ts.map +1 -1
- package/dist/domains/skill/uninstall.js +38 -61
- package/dist/domains/skill/uninstall.js.map +1 -1
- package/dist/domains/workflow-contract/contained-atomic-write.d.ts +1 -0
- package/dist/domains/workflow-contract/contained-atomic-write.d.ts.map +1 -1
- package/dist/domains/workflow-contract/contained-atomic-write.js +19 -0
- package/dist/domains/workflow-contract/contained-atomic-write.js.map +1 -1
- package/dist/domains/workflow-contract/global-config.d.ts +8 -0
- package/dist/domains/workflow-contract/global-config.d.ts.map +1 -1
- package/dist/domains/workflow-contract/global-config.js +25 -0
- package/dist/domains/workflow-contract/global-config.js.map +1 -1
- package/dist/domains/workflow-contract/index.d.ts +1 -1
- package/dist/domains/workflow-contract/index.d.ts.map +1 -1
- package/dist/domains/workflow-contract/index.js +1 -1
- package/dist/domains/workflow-contract/index.js.map +1 -1
- package/dist/domains/workflow-contract/project-config.d.ts +1 -1
- package/dist/domains/workflow-contract/project-config.d.ts.map +1 -1
- package/dist/domains/workflow-contract/project-config.js +1 -0
- package/dist/domains/workflow-contract/project-config.js.map +1 -1
- package/dist/domains/workflow-contract/types.d.ts.map +1 -1
- package/dist/platform/install/platforms.d.ts +4 -0
- package/dist/platform/install/platforms.d.ts.map +1 -1
- package/dist/platform/install/platforms.js +15 -3
- package/dist/platform/install/platforms.js.map +1 -1
- package/dist/platform/paths/project-knowledge-storage.d.ts +1 -1
- package/dist/platform/paths/project-knowledge-storage.d.ts.map +1 -1
- package/dist/platform/paths/project-knowledge-storage.js +9 -4
- package/dist/platform/paths/project-knowledge-storage.js.map +1 -1
- package/eval/local/tasks/comet-classic-layout-lifecycle/environment/current-comet-package.json +13 -13
- package/eval/local/tasks/comet-native-wave-f-dashboard-readonly/environment/current-comet-package.json +13 -13
- package/package.json +24 -24
- package/dist/domains/dashboard/web/assets/abnfDiagram-N423BO3Z-BkUJc7LK.js +0 -1
- package/dist/domains/dashboard/web/assets/arc-DY4Y9tSO.js +0 -1
- package/dist/domains/dashboard/web/assets/architectureDiagram-T3A2C74G-7wC9YZS-.js +0 -36
- package/dist/domains/dashboard/web/assets/blockDiagram-VBNYF7ZC-Biqe-SaL.js +0 -132
- package/dist/domains/dashboard/web/assets/c4Diagram-5PPSVZJV-CccUFD1S.js +0 -10
- package/dist/domains/dashboard/web/assets/channel-DnRvSkOm.js +0 -1
- package/dist/domains/dashboard/web/assets/chunk-2GRJ4B5K-BUL4dDxo.js +0 -1
- package/dist/domains/dashboard/web/assets/chunk-2Q5K7J3B-BnKtDH9O.js +0 -1
- package/dist/domains/dashboard/web/assets/chunk-5RXB4S5H-C9pHQ1n3.js +0 -231
- package/dist/domains/dashboard/web/assets/chunk-6Q2QTUOP-CxrbngCi.js +0 -88
- package/dist/domains/dashboard/web/assets/chunk-GF5L2VYU-01mzgCUh.js +0 -206
- package/dist/domains/dashboard/web/assets/chunk-JWPE2WC7-wTiZVDvw.js +0 -1
- package/dist/domains/dashboard/web/assets/chunk-KBJHAD2P-Bxdv5bl-.js +0 -1
- package/dist/domains/dashboard/web/assets/chunk-RYQCIY6F-B5vF9l9A.js +0 -1
- package/dist/domains/dashboard/web/assets/chunk-XXDRQBXY-Dra3NnDp.js +0 -1
- package/dist/domains/dashboard/web/assets/classDiagram-JCYQIIEL-D3E-rgaQ.js +0 -1
- package/dist/domains/dashboard/web/assets/classDiagram-v2-OCEON4UE-D3E-rgaQ.js +0 -1
- package/dist/domains/dashboard/web/assets/cose-bilkent-JH36ORCC-DC96ge-n.js +0 -1
- package/dist/domains/dashboard/web/assets/cynefin-VYW2F7L2-Tt_NiopT.js +0 -166
- package/dist/domains/dashboard/web/assets/cynefinDiagram-MW4NZA55-BQ5__1hv.js +0 -62
- package/dist/domains/dashboard/web/assets/cytoscape.esm-D3_iZ_3b.js +0 -321
- package/dist/domains/dashboard/web/assets/dagre-VZM6K2ZE-Cr2zq3ro.js +0 -4
- package/dist/domains/dashboard/web/assets/defaultLocale-DX6XiGOO.js +0 -1
- package/dist/domains/dashboard/web/assets/demo-lxXhgJ9-.js +0 -456
- package/dist/domains/dashboard/web/assets/diagram-7IWD3JNH-BRpYDwPl.js +0 -30
- package/dist/domains/dashboard/web/assets/diagram-B4RE2ZJO-D7u-VBxW.js +0 -3
- package/dist/domains/dashboard/web/assets/diagram-LBJQPF4R-CHYuv2JD.js +0 -24
- package/dist/domains/dashboard/web/assets/diagram-Q27KOJAE-CV3ZE8Q3.js +0 -24
- package/dist/domains/dashboard/web/assets/diagram-UB23O5K3-co_OsTiQ.js +0 -41
- package/dist/domains/dashboard/web/assets/ebnfDiagram-BXEA7PRR-CETcWswS.js +0 -1
- package/dist/domains/dashboard/web/assets/erDiagram-JOGREHBK-edkItb7Z.js +0 -85
- package/dist/domains/dashboard/web/assets/flowDiagram-UKHOOZJN-D_oFJtSf.js +0 -156
- package/dist/domains/dashboard/web/assets/ganttDiagram-PKOTCBZU-CFjLVoA1.js +0 -292
- package/dist/domains/dashboard/web/assets/gitGraphDiagram-DS77QQ5N-BfD0tiKH.js +0 -106
- package/dist/domains/dashboard/web/assets/graph-DOmOIIwC.js +0 -1
- package/dist/domains/dashboard/web/assets/index-BzyqCfMb.css +0 -1
- package/dist/domains/dashboard/web/assets/index-CCKHH_A9.js +0 -10
- package/dist/domains/dashboard/web/assets/index-D8dxsTJY.js +0 -271
- package/dist/domains/dashboard/web/assets/index-DlSYK56b.js +0 -139
- package/dist/domains/dashboard/web/assets/infoDiagram-6WML65LV-Cx6xa9DS.js +0 -2
- package/dist/domains/dashboard/web/assets/init-Gi6I4Gst.js +0 -1
- package/dist/domains/dashboard/web/assets/ishikawaDiagram-WSZJBQD7-BjNLyyv_.js +0 -70
- package/dist/domains/dashboard/web/assets/journeyDiagram-NVQOT4AX-D2n9vrhx.js +0 -139
- package/dist/domains/dashboard/web/assets/kanban-definition-27J2QSJJ-kJL7v018.js +0 -89
- package/dist/domains/dashboard/web/assets/katex-HP8lGamR.js +0 -257
- package/dist/domains/dashboard/web/assets/layout-D-LzfAck.js +0 -1
- package/dist/domains/dashboard/web/assets/linear-CeHtd5-l.js +0 -1
- package/dist/domains/dashboard/web/assets/map-DxJ2ADlA.js +0 -1
- package/dist/domains/dashboard/web/assets/marked.esm-DECB3bxB.js +0 -64
- package/dist/domains/dashboard/web/assets/mermaid.core-B0EPSHs2.js +0 -306
- package/dist/domains/dashboard/web/assets/mindmap-definition-FAOFIHXS-bQQWINF4.js +0 -96
- package/dist/domains/dashboard/web/assets/ordinal-Cboi1Yqb.js +0 -1
- package/dist/domains/dashboard/web/assets/pegDiagram-VL7TDLO6-LxLY1W7W.js +0 -1
- package/dist/domains/dashboard/web/assets/pieDiagram-7S7Q4E2Y-BMDQqvuT.js +0 -39
- package/dist/domains/dashboard/web/assets/purify.es-Cz4mVeUR.js +0 -3
- package/dist/domains/dashboard/web/assets/quadrantDiagram-CIZ2JOQS-XWYjcuZN.js +0 -7
- package/dist/domains/dashboard/web/assets/railroadDiagram-AXF67PYL-p-OlQTa7.js +0 -1
- package/dist/domains/dashboard/web/assets/requirementDiagram-LRYGKXZP-BL4N8Vsl.js +0 -84
- package/dist/domains/dashboard/web/assets/sankeyDiagram-W5VNT64P-Btu-o6LN.js +0 -40
- package/dist/domains/dashboard/web/assets/sequenceDiagram-SI44F4Z6-9HpdQQ47.js +0 -162
- package/dist/domains/dashboard/web/assets/sizeCapture-X5ZJPWSS-5AnBiBHD.js +0 -1
- package/dist/domains/dashboard/web/assets/stateDiagram-OKZ733FA-Dv8IDsai.js +0 -1
- package/dist/domains/dashboard/web/assets/stateDiagram-v2-UEYNNEHI-DxOMyFOm.js +0 -1
- package/dist/domains/dashboard/web/assets/swimlanes-SLNWSIFB-BfJcN7dK.js +0 -2
- package/dist/domains/dashboard/web/assets/swimlanesDiagram-ULZ7WXOC-BnHRSbDk.js +0 -8
- package/dist/domains/dashboard/web/assets/timeline-definition-Z64GVDOM-DEOuEHi5.js +0 -120
- package/dist/domains/dashboard/web/assets/vennDiagram-T6HMQDX7-BqsGpwgo.js +0 -34
- package/dist/domains/dashboard/web/assets/wardleyDiagram-T6FBY63Y-CXlOp9so.js +0 -78
- package/dist/domains/dashboard/web/assets/xychartDiagram-ELKLHX3M-DyqqtC9X.js +0 -7
|
@@ -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 Jp=Object.create;var rl=Object.defineProperty;var Gp=Object.getOwnPropertyDescriptor;var Up=Object.getOwnPropertyNames;var Kp=Object.getPrototypeOf,Yp=Object.prototype.hasOwnProperty;var Oi=(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 Xp=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Up(t))!Yp.call(e,n)&&n!==r&&rl(e,n,{get:()=>t[n],enumerable:!(i=Gp(t,n))||i.enumerable});return e};var Sr=(e,t,r)=>(r=e!=null?Jp(Kp(e)):{},Xp(t||!e||!e.__esModule?rl(r,"default",{value:e,enumerable:!0}):r,e));var C=b(G=>{"use strict";var za=Symbol.for("yaml.alias"),sl=Symbol.for("yaml.document"),qi=Symbol.for("yaml.map"),cl=Symbol.for("yaml.pair"),Ja=Symbol.for("yaml.scalar"),Fi=Symbol.for("yaml.seq"),Ve=Symbol.for("yaml.node.type"),vm=e=>!!e&&typeof e=="object"&&e[Ve]===za,gm=e=>!!e&&typeof e=="object"&&e[Ve]===sl,wm=e=>!!e&&typeof e=="object"&&e[Ve]===qi,ym=e=>!!e&&typeof e=="object"&&e[Ve]===cl,ll=e=>!!e&&typeof e=="object"&&e[Ve]===Ja,Nm=e=>!!e&&typeof e=="object"&&e[Ve]===Fi;function ul(e){if(e&&typeof e=="object")switch(e[Ve]){case qi:case Fi:return!0}return!1}function bm(e){if(e&&typeof e=="object")switch(e[Ve]){case za:case qi:case Ja:case Fi:return!0}return!1}var km=e=>(ll(e)||ul(e))&&!!e.anchor;G.ALIAS=za;G.DOC=sl;G.MAP=qi;G.NODE_TYPE=Ve;G.PAIR=cl;G.SCALAR=Ja;G.SEQ=Fi;G.hasAnchor=km;G.isAlias=vm;G.isCollection=ul;G.isDocument=gm;G.isMap=wm;G.isNode=bm;G.isPair=ym;G.isScalar=ll;G.isSeq=Nm});var Cr=b(Ga=>{"use strict";var F=C(),ie=Symbol("break visit"),dl=Symbol("skip children"),Te=Symbol("remove node");function Vi(e,t){let r=fl(t);F.isDocument(e)?Gt(null,e.contents,r,Object.freeze([e]))===Te&&(e.contents=null):Gt(null,e,r,Object.freeze([]))}Vi.BREAK=ie;Vi.SKIP=dl;Vi.REMOVE=Te;function Gt(e,t,r,i){let n=hl(e,t,r,i);if(F.isNode(n)||F.isPair(n))return pl(e,i,n),Gt(e,n,r,i);if(typeof n!="symbol"){if(F.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=Gt(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===ie)return ie;o===Te&&(t.items.splice(a,1),a-=1)}}}else if(F.isPair(t)){i=Object.freeze(i.concat(t));let a=Gt("key",t.key,r,i);if(a===ie)return ie;a===Te&&(t.key=null);let o=Gt("value",t.value,r,i);if(o===ie)return ie;o===Te&&(t.value=null)}}return n}async function Mi(e,t){let r=fl(t);F.isDocument(e)?await Ut(null,e.contents,r,Object.freeze([e]))===Te&&(e.contents=null):await Ut(null,e,r,Object.freeze([]))}Mi.BREAK=ie;Mi.SKIP=dl;Mi.REMOVE=Te;async function Ut(e,t,r,i){let n=await hl(e,t,r,i);if(F.isNode(n)||F.isPair(n))return pl(e,i,n),Ut(e,n,r,i);if(typeof n!="symbol"){if(F.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await Ut(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===ie)return ie;o===Te&&(t.items.splice(a,1),a-=1)}}}else if(F.isPair(t)){i=Object.freeze(i.concat(t));let a=await Ut("key",t.key,r,i);if(a===ie)return ie;a===Te&&(t.key=null);let o=await Ut("value",t.value,r,i);if(o===ie)return ie;o===Te&&(t.value=null)}}return n}function fl(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 hl(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(F.isMap(t))return r.Map?.(e,t,i);if(F.isSeq(t))return r.Seq?.(e,t,i);if(F.isPair(t))return r.Pair?.(e,t,i);if(F.isScalar(t))return r.Scalar?.(e,t,i);if(F.isAlias(t))return r.Alias?.(e,t,i)}function pl(e,t,r){let i=t[t.length-1];if(F.isCollection(i))i.items[e]=r;else if(F.isPair(i))e==="key"?i.key=r:i.value=r;else if(F.isDocument(i))i.contents=r;else{let n=F.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}Ga.visit=Vi;Ga.visitAsync=Mi});var Ua=b(vl=>{"use strict";var ml=C(),Sm=Cr(),Em={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Pm=e=>e.replace(/[!,[\]{}]/g,t=>Em[t]),Rr=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+Pm(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&&ml.isNode(t.contents)){let a={};Sm.visit(t.contents,(o,s)=>{ml.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
|
+
`)}};Rr.defaultYaml={explicit:!1,version:"1.2"};Rr.defaultTags={"!!":"tag:yaml.org,2002:"};vl.Directives=Rr});var Wi=b(Ar=>{"use strict";var gl=C(),xm=Cr();function Cm(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 wl(e){let t=new Set;return xm.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function yl(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function Rm(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=wl(e));let o=yl(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(gl.isScalar(o.node)||gl.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}}Ar.anchorIsValid=Cm;Ar.anchorNames=wl;Ar.createNodeAnchors=Rm;Ar.findNewAnchor=yl});var Ka=b(Nl=>{"use strict";function _r(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=_r(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=_r(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=_r(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=_r(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}Nl.applyReviver=_r});var it=b(kl=>{"use strict";var Am=C();function bl(e,t,r){if(Array.isArray(e))return e.map((i,n)=>bl(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!Am.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}kl.toJS=bl});var zi=b(El=>{"use strict";var _m=Ka(),Sl=C(),Im=it(),Ya=class{constructor(t){Object.defineProperty(this,Sl.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(!Sl.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=Im.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?_m.applyReviver(a,{"":s},"",s):s}};El.NodeBase=Ya});var Ir=b(Pl=>{"use strict";var Tm=Wi(),jm=Cr(),Kt=C(),$m=zi(),Om=it(),Xa=class extends $m.NodeBase{constructor(t){super(Kt.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=[],jm.visit(t,{Node:(a,o)=>{(Kt.isAlias(o)||Kt.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||(Om.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=Ji(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(Tm.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 Ji(e,t,r){if(Kt.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(Kt.isCollection(t)){let i=0;for(let n of t.items){let a=Ji(e,n,r);a>i&&(i=a)}return i}else if(Kt.isPair(t)){let i=Ji(e,t.key,r),n=Ji(e,t.value,r);return Math.max(i,n)}return 1}Pl.Alias=Xa});var B=b(Qa=>{"use strict";var Hm=C(),Dm=zi(),Bm=it(),Lm=e=>!e||typeof e!="function"&&typeof e!="object",nt=class extends Dm.NodeBase{constructor(t){super(Hm.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:Bm.toJS(this.value,t,r)}toString(){return String(this.value)}};nt.BLOCK_FOLDED="BLOCK_FOLDED";nt.BLOCK_LITERAL="BLOCK_LITERAL";nt.PLAIN="PLAIN";nt.QUOTE_DOUBLE="QUOTE_DOUBLE";nt.QUOTE_SINGLE="QUOTE_SINGLE";Qa.Scalar=nt;Qa.isScalarValue=Lm});var Tr=b(Cl=>{"use strict";var qm=Ir(),St=C(),xl=B(),Fm="tag:yaml.org,2002:";function Vm(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 Mm(e,t,r){if(St.isDocument(e)&&(e=e.contents),St.isNode(e))return e;if(St.isPair(e)){let u=r.schema[St.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=Fm+t.slice(2));let l=Vm(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let u=new xl.Scalar(e);return c&&(c.node=u),u}l=e instanceof Map?o[St.MAP]:Symbol.iterator in Object(e)?o[St.SEQ]:o[St.MAP]}a&&(a(l),delete r.onTagObj);let d=l?.createNode?l.createNode(r.schema,e,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,e,r):new xl.Scalar(e);return t?d.tag=t:l.default||(d.tag=l.tag),c&&(c.node=d),d}Cl.createNode=Mm});var Ui=b(Gi=>{"use strict";var Wm=Tr(),je=C(),zm=zi();function Za(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 Wm.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 Rl=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,eo=class extends zm.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=>je.isNode(i)||je.isPair(i)?i.clone(t):i),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(Rl(t))this.add(r);else{let[i,...n]=t,a=this.get(i,!0);if(je.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,Za(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(je.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&&je.isScalar(a)?a.value:a:je.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!je.isPair(r))return!1;let i=r.value;return i==null||t&&je.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 je.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(je.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,Za(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};Gi.Collection=eo;Gi.collectionFromPath=Za;Gi.isEmptyPath=Rl});var jr=b(Ki=>{"use strict";var Jm=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function to(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Gm=(e,t,r)=>e.endsWith(`
|
|
6
|
+
`)?to(r,t):r.includes(`
|
|
7
7
|
`)?`
|
|
8
|
-
`+
|
|
9
|
-
`)r===
|
|
8
|
+
`+to(r,t):(e.endsWith(" ")?"":" ")+r;Ki.indentComment=to;Ki.lineComment=Gm;Ki.stringifyComment=Jm});var _l=b($r=>{"use strict";var Um="flow",ro="block",Yi="quoted";function Km(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=[],d={},u=n-t.length;typeof i=="number"&&(i>n-Math.max(2,a)?l.push(0):u=n-i);let f,m,v=!1,h=-1,p=-1,w=-1;r===ro&&(h=Al(e,h,t.length),h!==-1&&(u=h+c));for(let g;g=e[h+=1];){if(r===Yi&&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}w=h}if(g===`
|
|
9
|
+
`)r===ro&&(h=Al(e,h,t.length)),u=h+t.length+c,f=void 0;else{if(g===" "&&m&&m!==" "&&m!==`
|
|
10
10
|
`&&m!==" "){let N=e[h+1];N&&N!==" "&&N!==`
|
|
11
|
-
`&&N!==" "&&(
|
|
12
|
-
${t}${e.slice(0,k)}`:(r===
|
|
13
|
-
${t}${e.slice(N+1,k)}`)}return y}function
|
|
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
|
|
11
|
+
`&&N!==" "&&(f=h)}if(h>=u)if(f)l.push(f),u=f+c,f=void 0;else if(r===Yi){for(;m===" "||m===" ";)m=g,g=e[h+=1],v=!0;let N=h>w+1?h-2:p-1;if(d[N])return e;l.push(N),d[N]=!0,u=N+c,f=void 0}else v=!0}m=g}if(v&&s&&s(),l.length===0)return e;o&&o();let y=e.slice(0,l[0]);for(let g=0;g<l.length;++g){let N=l[g],k=l[g+1]||e.length;N===0?y=`
|
|
12
|
+
${t}${e.slice(0,k)}`:(r===Yi&&d[N]&&(y+=`${e[N]}\\`),y+=`
|
|
13
|
+
${t}${e.slice(N+1,k)}`)}return y}function Al(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}$r.FOLD_BLOCK=ro;$r.FOLD_FLOW=Um;$r.FOLD_QUOTED=Yi;$r.foldFlowLines=Km});var Hr=b(Il=>{"use strict";var Se=B(),at=_l(),Qi=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Zi=e=>/^(%|---|\.\.\.)/m.test(e);function Ym(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 Or(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:i}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(Zi(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 d=r.substr(c+2,4);switch(d){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:d.substr(0,2)==="00"?o+="\\x"+d.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:at.foldFlowLines(o,a,at.FOLD_QUOTED,Qi(t,!1))}function io(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
19
|
+
`)||/[ \t]\n|\n[ \t]/.test(e))return Or(e,t);let r=t.indent||(Zi(e)?" ":""),i="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
20
|
+
${r}`)+"'";return t.implicitKey?i:at.foldFlowLines(i,r,at.FOLD_FLOW,Qi(t,!1))}function Yt(e,t){let{singleQuote:r}=t.options,i;if(r===!1)i=Or;else{let n=e.includes('"'),a=e.includes("'");n&&!a?i=io:a&&!n?i=Or:i=r?io:Or}return i(e,t)}var no;try{no=new RegExp(`(^|(?<!
|
|
21
21
|
))
|
|
22
22
|
+(?!
|
|
23
|
-
|$)`,"g")}catch{
|
|
23
|
+
|$)`,"g")}catch{no=/\n+(?!\n|$)/g}function Xi({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 Yt(r,i);let l=i.indent||(i.forceBlockIndent||Zi(r)?" ":""),d=o==="literal"?!0:o==="folded"||t===Se.Scalar.BLOCK_FOLDED?!1:t===Se.Scalar.BLOCK_LITERAL?!0:!Ym(r,c,l.length);if(!r)return d?`|
|
|
24
24
|
`:`>
|
|
25
|
-
`;let u,
|
|
26
|
-
`&&k!==" "&&k!==" ")break}let m=r.substring(
|
|
25
|
+
`;let u,f;for(f=r.length;f>0;--f){let k=r[f-1];if(k!==`
|
|
26
|
+
`&&k!==" "&&k!==" ")break}let m=r.substring(f),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
|
-
`)w=p;else break}let y=r.substring(0,w<p?w+1:p);y&&(r=r.substring(y.length),y=y.replace(/\n+/g,`$&${l}`));let N=(h?l?"2":"1":"")+u;if(e&&(N+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!
|
|
30
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),E=!1,R=
|
|
28
|
+
`&&(m=m.slice(0,-1)),m=m.replace(no,`$&${l}`));let h=!1,p,w=-1;for(p=0;p<r.length;++p){let k=r[p];if(k===" ")h=!0;else if(k===`
|
|
29
|
+
`)w=p;else break}let y=r.substring(0,w<p?w+1:p);y&&(r=r.substring(y.length),y=y.replace(/\n+/g,`$&${l}`));let N=(h?l?"2":"1":"")+u;if(e&&(N+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!d){let k=r.replace(/\n+/g,`
|
|
30
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),E=!1,R=Qi(i,!0);o!=="folded"&&t!==Se.Scalar.BLOCK_FOLDED&&(R.onOverflow=()=>{E=!0});let S=at.foldFlowLines(`${y}${k}${m}`,l,at.FOLD_BLOCK,R);if(!E)return`>${N}
|
|
31
31
|
${l}${S}`}return r=r.replace(/\n+/g,`$&${l}`),`|${N}
|
|
32
|
-
${l}${y}${r}${m}`}function
|
|
33
|
-
`)||
|
|
34
|
-
`)?
|
|
35
|
-
`))return
|
|
36
|
-
${c}`);if(o){let
|
|
37
|
-
${t.indent}${s}`:s}
|
|
38
|
-
${s}:`):(p=`${p}:`,
|
|
32
|
+
${l}${y}${r}${m}`}function Xm(e,t,r,i){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:d}=t;if(s&&a.includes(`
|
|
33
|
+
`)||d&&/[[\]{},]/.test(a))return Yt(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||d||!a.includes(`
|
|
34
|
+
`)?Yt(a,t):Xi(e,t,r,i);if(!s&&!d&&n!==Se.Scalar.PLAIN&&a.includes(`
|
|
35
|
+
`))return Xi(e,t,r,i);if(Zi(a)){if(c==="")return t.forceBlockIndent=!0,Xi(e,t,r,i);if(s&&c===l)return Yt(a,t)}let u=a.replace(/\n+/g,`$&
|
|
36
|
+
${c}`);if(o){let f=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(u),{compat:m,tags:v}=t.doc.schema;if(v.some(f)||m?.some(f))return Yt(a,t)}return s?u:at.foldFlowLines(u,c,at.FOLD_FLOW,Qi(t,!1))}function Qm(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!==Se.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=Se.Scalar.QUOTE_DOUBLE);let c=d=>{switch(d){case Se.Scalar.BLOCK_FOLDED:case Se.Scalar.BLOCK_LITERAL:return n||a?Yt(o.value,t):Xi(o,t,r,i);case Se.Scalar.QUOTE_DOUBLE:return Or(o.value,t);case Se.Scalar.QUOTE_SINGLE:return io(o.value,t);case Se.Scalar.PLAIN:return Xm(o,t,r,i);default:return null}},l=c(s);if(l===null){let{defaultKeyType:d,defaultStringType:u}=t.options,f=n&&d||u;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}Il.stringifyString=Qm});var Dr=b(ao=>{"use strict";var Zm=Wi(),ot=C(),ev=jr(),tv=Hr();function rv(e,t){let r=Object.assign({blockQuote:!0,commentString:ev.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 iv(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(ot.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 nv(e,t,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=(ot.isScalar(e)||ot.isCollection(e))&&e.anchor;a&&Zm.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 av(e,t,r,i){if(ot.isPair(e))return e.toString(t,r,i);if(ot.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=ot.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=iv(t.doc.schema.tags,a));let o=nv(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):ot.isScalar(a)?tv.stringifyString(a,t,r,i):a.toString(t,r,i);return o?ot.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
|
|
37
|
+
${t.indent}${s}`:s}ao.createStringifyContext=rv;ao.stringify=av});var Ol=b($l=>{"use strict";var Me=C(),Tl=B(),jl=Dr(),Br=jr();function ov({key:e,value:t},r,i,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:d,simpleKeys:u}}=r,f=Me.isNode(e)&&e.comment||null;if(u){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(Me.isCollection(e)||!Me.isNode(e)&&typeof e=="object"){let R="With simple keys, collection cannot be used as a key value";throw new Error(R)}}let m=!u&&(!e||f&&t==null&&!r.inFlow||Me.isCollection(e)||(Me.isScalar(e)?e.type===Tl.Scalar.BLOCK_FOLDED||e.type===Tl.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=jl.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}`,f&&!v?p+=Br.lineComment(p,r.indent,l(f)):h&&n&&n(),p;v&&(f=null),m?(f&&(p+=Br.lineComment(p,r.indent,l(f))),p=`? ${p}
|
|
38
|
+
${s}:`):(p=`${p}:`,f&&(p+=Br.lineComment(p,r.indent,l(f))));let w,y,g;Me.isNode(t)?(w=!!t.spaceBefore,y=t.commentBefore,g=t.comment):(w=!1,y=null,g=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!m&&!f&&Me.isScalar(t)&&(r.indentAtStart=p.length+1),h=!1,!d&&c.length>=2&&!r.inFlow&&!m&&Me.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let N=!1,k=jl.stringify(t,r,()=>N=!0,()=>h=!0),E=" ";if(f||w||y){if(E=w?`
|
|
39
39
|
`:"",y){let R=l(y);E+=`
|
|
40
|
-
${
|
|
40
|
+
${Br.indentComment(R,r.indent)}`}k===""&&!r.inFlow?E===`
|
|
41
41
|
`&&g&&(E=`
|
|
42
42
|
|
|
43
43
|
`):E+=`
|
|
44
|
-
${r.indent}`}else if(!m&&
|
|
45
|
-
`),$=S!==-1,ce=r.inFlow??t.flow??t.items.length===0;if($||!ce){let
|
|
44
|
+
${r.indent}`}else if(!m&&Me.isCollection(t)){let R=k[0],S=k.indexOf(`
|
|
45
|
+
`),$=S!==-1,ce=r.inFlow??t.flow??t.items.length===0;if($||!ce){let et=!1;if($&&(R==="&"||R==="!")){let O=k.indexOf(" ");R==="&"&&O!==-1&&O<S&&k[O+1]==="!"&&(O=k.indexOf(" ",O+1)),(O===-1||S<O)&&(et=!0)}et||(E=`
|
|
46
46
|
${r.indent}`)}}else(k===""||k[0]===`
|
|
47
|
-
`)&&(E="");return p+=E+k,r.inFlow?N&&i&&i():g&&!N?p+=
|
|
47
|
+
`)&&(E="");return p+=E+k,r.inFlow?N&&i&&i():g&&!N?p+=Br.lineComment(p,r.indent,l(g)):h&&n&&n(),p}$l.stringifyPair=ov});var so=b(oo=>{"use strict";var Hl=Oi("process");function sv(e,...t){e==="debug"&&console.log(...t)}function cv(e,t){(e==="debug"||e==="warn")&&(typeof Hl.emitWarning=="function"?Hl.emitWarning(t):console.warn(t))}oo.debug=sv;oo.warn=cv});var an=b(nn=>{"use strict";var rn=C(),Dl=B(),en="<<",tn={identify:e=>e===en||typeof e=="symbol"&&e.description===en,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Dl.Scalar(Symbol(en)),{addToJSMap:Bl}),stringify:()=>en},lv=(e,t)=>(tn.identify(t)||rn.isScalar(t)&&(!t.type||t.type===Dl.Scalar.PLAIN)&&tn.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===tn.tag&&r.default);function Bl(e,t,r){let i=Ll(e,r);if(rn.isSeq(i))for(let n of i.items)co(e,t,n);else if(Array.isArray(i))for(let n of i)co(e,t,n);else co(e,t,i)}function co(e,t,r){let i=Ll(e,r);if(!rn.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 Ll(e,t){return e&&rn.isAlias(t)?t.resolve(e.doc,e):t}nn.addMergeToJSMap=Bl;nn.isMergeKey=lv;nn.merge=tn});var uo=b(Vl=>{"use strict";var uv=so(),ql=an(),dv=Dr(),Fl=C(),lo=it();function fv(e,t,{key:r,value:i}){if(Fl.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,i);else if(ql.isMergeKey(e,r))ql.addMergeToJSMap(e,t,i);else{let n=lo.toJS(r,"",e);if(t instanceof Map)t.set(n,lo.toJS(i,n,e));else if(t instanceof Set)t.add(n);else{let a=hv(r,n,e),o=lo.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 hv(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(Fl.isNode(e)&&r?.doc){let i=dv.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)+'..."'),uv.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)}Vl.addPairToJSMap=fv});var st=b(fo=>{"use strict";var Ml=Tr(),pv=Ol(),mv=uo(),on=C();function vv(e,t,r){let i=Ml.createNode(e,void 0,r),n=Ml.createNode(t,void 0,r);return new sn(i,n)}var sn=class e{constructor(t,r=null){Object.defineProperty(this,on.NODE_TYPE,{value:on.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:i}=this;return on.isNode(r)&&(r=r.clone(t)),on.isNode(i)&&(i=i.clone(t)),new e(r,i)}toJSON(t,r){let i=r?.mapAsMap?new Map:{};return mv.addPairToJSMap(r,i,this)}toString(t,r,i){return t?.doc?pv.stringifyPair(this,t,r,i):JSON.stringify(this)}};fo.Pair=sn;fo.createPair=vv});var ho=b(zl=>{"use strict";var Et=C(),Wl=Dr(),cn=jr();function gv(e,t,r){return(t.inFlow??e.flow?yv:wv)(e,t,r)}function wv({comment:e,items:t},r,{blockItemPrefix:i,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=r,d=Object.assign({},r,{indent:a,type:null}),u=!1,f=[];for(let v=0;v<t.length;++v){let h=t[v],p=null;if(Et.isNode(h))!u&&h.spaceBefore&&f.push(""),ln(r,f,h.commentBefore,u),h.comment&&(p=h.comment);else if(Et.isPair(h)){let y=Et.isNode(h.key)?h.key:null;y&&(!u&&y.spaceBefore&&f.push(""),ln(r,f,y.commentBefore,u))}u=!1;let w=Wl.stringify(h,d,()=>p=null,()=>u=!0);p&&(w+=cn.lineComment(w,a,l(p))),u&&p&&(u=!1),f.push(i+w)}let m;if(f.length===0)m=n.start+n.end;else{m=f[0];for(let v=1;v<f.length;++v){let h=f[v];m+=h?`
|
|
48
48
|
${c}${h}`:`
|
|
49
49
|
`}}return e?(m+=`
|
|
50
|
-
`+
|
|
51
|
-
`)),v<e.length-1?w+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=u.reduce((y,g)=>y+g.length+2,2)+(w.length+2)>t.options.lineWidth)),l&&(w+=",")),p&&(w+=
|
|
50
|
+
`+cn.indentComment(l(e),c),s&&s()):u&&o&&o(),m}function yv({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,d=0,u=[];for(let v=0;v<e.length;++v){let h=e[v],p=null;if(Et.isNode(h))h.spaceBefore&&u.push(""),ln(t,u,h.commentBefore,!1),h.comment&&(p=h.comment);else if(Et.isPair(h)){let y=Et.isNode(h.key)?h.key:null;y&&(y.spaceBefore&&u.push(""),ln(t,u,y.commentBefore,!1),y.comment&&(l=!0));let g=Et.isNode(h.value)?h.value:null;g?(g.comment&&(p=g.comment),g.commentBefore&&(l=!0)):h.value==null&&y?.comment&&(p=y.comment)}p&&(l=!0);let w=Wl.stringify(h,c,()=>p=null);l||(l=u.length>d||w.includes(`
|
|
51
|
+
`)),v<e.length-1?w+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=u.reduce((y,g)=>y+g.length+2,2)+(w.length+2)>t.options.lineWidth)),l&&(w+=",")),p&&(w+=cn.lineComment(w,i,s(p))),u.push(w),d=u.length}let{start:f,end:m}=r;if(u.length===0)return f+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=f;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`${f}${o}${u.join(" ")}${o}${m}`}function ln({indent:e,options:{commentString:t}},r,i,n){if(i&&n&&(i=i.replace(/^\n+/,"")),i){let a=cn.indentComment(t(i),e);r.push(a.trimStart())}}zl.stringifyCollection=gv});var lt=b(mo=>{"use strict";var Nv=ho(),bv=uo(),kv=Ui(),ct=C(),un=st(),Sv=B();function Lr(e,t){let r=ct.isScalar(t)?t.value:t;for(let i of e)if(ct.isPair(i)&&(i.key===t||i.key===r||ct.isScalar(i.key)&&i.key.value===r))return i}var po=class extends kv.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(ct.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(un.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;ct.isPair(t)?i=t:!t||typeof t!="object"||!("key"in t)?i=new un.Pair(t,t?.value):i=new un.Pair(t.key,t.value);let n=Lr(this.items,i.key),a=this.schema?.sortMapEntries;if(n){if(!r)throw new Error(`Key ${i.key} already set`);ct.isScalar(n.value)&&Sv.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=Lr(this.items,t);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(t,r){let n=Lr(this.items,t)?.value;return(!r&&ct.isScalar(n)?n.value:n)??void 0}has(t){return!!Lr(this.items,t)}set(t,r){this.add(new un.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)bv.addPairToJSMap(r,n,a);return n}toString(t,r,i){if(!t)return JSON.stringify(this);for(let n of this.items)if(!ct.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})),Nv.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:i,onComment:r})}};mo.YAMLMap=po;mo.findPair=Lr});var Xt=b(Gl=>{"use strict";var Ev=C(),Jl=lt(),Pv={collection:"map",default:!0,nodeClass:Jl.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return Ev.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>Jl.YAMLMap.from(e,t,r)};Gl.map=Pv});var ut=b(Ul=>{"use strict";var xv=Tr(),Cv=ho(),Rv=Ui(),fn=C(),Av=B(),_v=it(),vo=class extends Rv.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(fn.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let r=dn(t);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(t,r){let i=dn(t);if(typeof i!="number")return;let n=this.items[i];return!r&&fn.isScalar(n)?n.value:n}has(t){let r=dn(t);return typeof r=="number"&&r<this.items.length}set(t,r){let i=dn(t);if(typeof i!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[i];fn.isScalar(n)&&Av.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(_v.toJS(a,String(n++),r));return i}toString(t,r,i){return t?Cv.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(xv.createNode(s,void 0,i))}}return a}};function dn(e){let t=fn.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Ul.YAMLSeq=vo});var Qt=b(Yl=>{"use strict";var Iv=C(),Kl=ut(),Tv={collection:"seq",default:!0,nodeClass:Kl.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return Iv.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>Kl.YAMLSeq.from(e,t,r)};Yl.seq=Tv});var qr=b(Xl=>{"use strict";var jv=Hr(),$v={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),jv.stringifyString(e,t,r,i)}};Xl.string=$v});var hn=b(eu=>{"use strict";var Ql=B(),Zl={identify:e=>e==null,createNode:()=>new Ql.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Ql.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Zl.test.test(e)?e:t.options.nullStr};eu.nullTag=Zl});var go=b(ru=>{"use strict";var Ov=B(),tu={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new Ov.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&tu.test.test(e)){let i=e[0]==="t"||e[0]==="T";if(t===i)return e}return t?r.options.trueStr:r.options.falseStr}};ru.boolTag=tu});var Zt=b(iu=>{"use strict";function Hv({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}iu.stringifyNumber=Hv});var yo=b(pn=>{"use strict";var Dv=B(),wo=Zt(),Bv={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:wo.stringifyNumber},Lv={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():wo.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 Dv.Scalar(parseFloat(e)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:wo.stringifyNumber};pn.float=qv;pn.floatExp=Lv;pn.floatNaN=Bv});var bo=b(vn=>{"use strict";var nu=Zt(),mn=e=>typeof e=="bigint"||Number.isInteger(e),No=(e,t,r,{intAsBigInt:i})=>i?BigInt(e):parseInt(e.substring(t),r);function au(e,t,r){let{value:i}=e;return mn(i)&&i>=0?r+i.toString(t):nu.stringifyNumber(e)}var Fv={identify:e=>mn(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>No(e,2,8,r),stringify:e=>au(e,8,"0o")},Vv={identify:mn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>No(e,0,10,r),stringify:nu.stringifyNumber},Mv={identify:e=>mn(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>No(e,2,16,r),stringify:e=>au(e,16,"0x")};vn.int=Vv;vn.intHex=Mv;vn.intOct=Fv});var su=b(ou=>{"use strict";var Wv=Xt(),zv=hn(),Jv=Qt(),Gv=qr(),Uv=go(),ko=yo(),So=bo(),Kv=[Wv.map,Jv.seq,Gv.string,zv.nullTag,Uv.boolTag,So.intOct,So.int,So.intHex,ko.floatNaN,ko.floatExp,ko.float];ou.schema=Kv});var uu=b(lu=>{"use strict";var Yv=B(),Xv=Xt(),Qv=Qt();function cu(e){return typeof e=="bigint"||Number.isInteger(e)}var gn=({value:e})=>JSON.stringify(e),Zv=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:gn},{identify:e=>e==null,createNode:()=>new Yv.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:gn},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:gn},{identify:cu,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})=>cu(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:gn}],eg={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},tg=[Xv.map,Qv.seq].concat(Zv,eg);lu.schema=tg});var Po=b(du=>{"use strict";var Fr=Oi("buffer"),Eo=B(),rg=Hr(),ig={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Fr.Buffer=="function")return Fr.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 Fr.Buffer=="function")s=o instanceof Fr.Buffer?o.toString("base64"):Fr.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=Eo.Scalar.BLOCK_LITERAL),t!==Eo.Scalar.QUOTE_DOUBLE){let c=Math.max(i.options.lineWidth-i.indent.length,i.options.minContentWidth),l=Math.ceil(s.length/c),d=new Array(l);for(let u=0,f=0;u<l;++u,f+=c)d[u]=s.substr(f,c);s=d.join(t===Eo.Scalar.BLOCK_LITERAL?`
|
|
55
|
+
`:" ")}return rg.stringifyString({comment:e,type:t,value:s},i,n,a)}};du.binary=ig});var Nn=b(yn=>{"use strict";var wn=C(),xo=st(),ng=B(),ag=ut();function fu(e,t){if(wn.isSeq(e))for(let r=0;r<e.items.length;++r){let i=e.items[r];if(!wn.isPair(i)){if(wn.isMap(i)){i.items.length>1&&t("Each pair must have its own sequence indicator");let n=i.items[0]||new xo.Pair(new ng.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]=pn.isPair(i)?i:new So.Pair(i)}}else t("Expected a sequence for this tag");return e}function uu(e,t,r){let{replacer:i}=r,n=new tg.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(So.createPair(s,c,r))}return n}var rg={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:lu,createNode:uu};mn.createPairs=uu;mn.pairs=rg;mn.resolvePairs=lu});var xo=b(Po=>{"use strict";var du=C(),Eo=tt(),Lr=st(),ig=ct(),fu=vn(),kt=class e extends ig.YAMLSeq{constructor(){super(),this.add=Lr.YAMLMap.prototype.add.bind(this),this.delete=Lr.YAMLMap.prototype.delete.bind(this),this.get=Lr.YAMLMap.prototype.get.bind(this),this.has=Lr.YAMLMap.prototype.has.bind(this),this.set=Lr.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(du.isPair(n)?(a=Eo.toJS(n.key,"",r),o=Eo.toJS(n.value,a,r)):a=Eo.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=fu.createPairs(t,r,i),a=new this;return a.items=n.items,a}};kt.tag="tag:yaml.org,2002:omap";var ng={collection:"seq",identify:e=>e instanceof Map,nodeClass:kt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=fu.resolvePairs(e,t),i=[];for(let{key:n}of r.items)du.isScalar(n)&&(i.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new kt,r)},createNode:(e,t,r)=>kt.from(e,t,r)};Po.YAMLOMap=kt;Po.omap=ng});var gu=b(Co=>{"use strict";var hu=B();function pu({value:e,source:t},r){return t&&(e?mu:vu).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var mu={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 hu.Scalar(!0),stringify:pu},vu={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 hu.Scalar(!1),stringify:pu};Co.falseTag=vu;Co.trueTag=mu});var wu=b(gn=>{"use strict";var ag=B(),Ro=Jt(),og={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:Ro.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():Ro.stringifyNumber(e)}},cg={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 ag.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:Ro.stringifyNumber};gn.float=cg;gn.floatExp=sg;gn.floatNaN=og});var Nu=b(Fr=>{"use strict";var yu=Jt(),qr=e=>typeof e=="bigint"||Number.isInteger(e);function wn(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 Ao(e,t,r){let{value:i}=e;if(qr(i)){let n=i.toString(t);return i<0?"-"+r+n.substr(1):r+n}return yu.stringifyNumber(e)}var lg={identify:qr,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>wn(e,2,2,r),stringify:e=>Ao(e,2,"0b")},ug={identify:qr,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>wn(e,1,8,r),stringify:e=>Ao(e,8,"0")},dg={identify:qr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>wn(e,0,10,r),stringify:yu.stringifyNumber},fg={identify:qr,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>wn(e,2,16,r),stringify:e=>Ao(e,16,"0x")};Fr.int=dg;Fr.intBin=lg;Fr.intHex=fg;Fr.intOct=ug});var Io=b(_o=>{"use strict";var bn=C(),yn=at(),Nn=st(),St=class e extends Nn.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;bn.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new yn.Pair(t.key,null):r=new yn.Pair(t,null),Nn.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let i=Nn.findPair(this.items,t);return!r&&bn.isPair(i)?bn.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=Nn.findPair(this.items,t);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new yn.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(yn.createPair(o,null,i));return a}};St.tag="tag:yaml.org,2002:set";var hg={collection:"map",identify:e=>e instanceof Set,nodeClass:St,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>St.from(e,t,r),resolve(e,t){if(bn.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new St,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};_o.YAMLSet=St;_o.set=hg});var jo=b(kn=>{"use strict";var pg=Jt();function To(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 bu(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return pg.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 mg={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})=>To(e,r),stringify:bu},vg={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=>To(e,!1),stringify:bu},ku={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(ku.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=To(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$/,"")??""};kn.floatTime=vg;kn.intTime=mg;kn.timestamp=ku});var Pu=b(Eu=>{"use strict";var gg=Wt(),wg=ln(),yg=zt(),Ng=Dr(),bg=ko(),Su=gu(),$o=wu(),Sn=Nu(),kg=en(),Sg=xo(),Eg=vn(),Pg=Io(),Oo=jo(),xg=[gg.map,yg.seq,Ng.string,wg.nullTag,Su.trueTag,Su.falseTag,Sn.intBin,Sn.intOct,Sn.int,Sn.intHex,$o.floatNaN,$o.floatExp,$o.float,bg.binary,kg.merge,Sg.omap,Eg.pairs,Pg.set,Oo.intTime,Oo.floatTime,Oo.timestamp];Eu.schema=xg});var Ou=b(Bo=>{"use strict";var Au=Wt(),Cg=ln(),_u=zt(),Rg=Dr(),Ag=po(),Ho=vo(),Do=wo(),_g=nu(),Ig=su(),Iu=ko(),Mr=en(),Tu=xo(),ju=vn(),xu=Pu(),$u=Io(),En=jo(),Cu=new Map([["core",_g.schema],["failsafe",[Au.map,_u.seq,Rg.string]],["json",Ig.schema],["yaml11",xu.schema],["yaml-1.1",xu.schema]]),Ru={binary:Iu.binary,bool:Ag.boolTag,float:Ho.float,floatExp:Ho.floatExp,floatNaN:Ho.floatNaN,floatTime:En.floatTime,int:Do.int,intHex:Do.intHex,intOct:Do.intOct,intTime:En.intTime,map:Au.map,merge:Mr.merge,null:Cg.nullTag,omap:Tu.omap,pairs:ju.pairs,seq:_u.seq,set:$u.set,timestamp:En.timestamp},Tg={"tag:yaml.org,2002:binary":Iu.binary,"tag:yaml.org,2002:merge":Mr.merge,"tag:yaml.org,2002:omap":Tu.omap,"tag:yaml.org,2002:pairs":ju.pairs,"tag:yaml.org,2002:set":$u.set,"tag:yaml.org,2002:timestamp":En.timestamp};function jg(e,t,r){let i=Cu.get(t);if(i&&!e)return r&&!i.includes(Mr.merge)?i.concat(Mr.merge):i.slice();let n=i;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(Cu.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(Mr.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Ru[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Ru).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},[])}Bo.coreKnownTags=Tg;Bo.getTags=jg});var Fo=b(Hu=>{"use strict";var Lo=C(),$g=Wt(),Og=zt(),Hg=Dr(),Pn=Ou(),Dg=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,qo=class e{constructor({compat:t,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Pn.getTags(t,"compat"):t?Pn.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Pn.coreKnownTags:{},this.tags=Pn.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,Lo.MAP,{value:$g.map}),Object.defineProperty(this,Lo.SCALAR,{value:Hg.string}),Object.defineProperty(this,Lo.SEQ,{value:Og.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Dg:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Hu.Schema=qo});var Bu=b(Du=>{"use strict";var Bg=C(),Mo=$r(),Vr=_r();function Lg(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=Mo.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=a(e.commentBefore);r.unshift(Vr.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(Bg.isNode(e.contents)){if(e.contents.spaceBefore&&i&&r.push(""),e.contents.commentBefore){let f=a(e.contents.commentBefore);r.push(Vr.indentComment(f,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Mo.stringify(e.contents,n,()=>s=null,c);s&&(l+=Vr.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(Mo.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]=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(Jr.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(Jr.indentComment(a(c),"")))}return r.join(`
|
|
59
59
|
`)+`
|
|
60
|
-
`}
|
|
60
|
+
`}qu.stringifyDocument=Mg});var Gr=b(Vu=>{"use strict";var Wg=Ir(),er=Ui(),me=C(),zg=st(),Jg=it(),Gg=Wo(),Ug=Fu(),Jo=Wi(),Kg=Ka(),Yg=Tr(),Go=Ua(),Uo=class e{constructor(t,r,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,me.NODE_TYPE,{value:me.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 Go.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,{[me.NODE_TYPE]:{value:me.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=me.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){tr(this.contents)&&this.contents.add(t)}addIn(t,r){tr(this.contents)&&this.contents.addIn(t,r)}createAlias(t,r){if(!t.anchor){let i=Jo.anchorNames(this);t.anchor=!r||i.has(r)?Jo.findNewAnchor(r||"a",i):r}return new Wg.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=y=>typeof y=="number"||y instanceof String||y instanceof Number,w=r.filter(p).map(String);w.length>0&&(r=r.concat(w)),n=r}else i===void 0&&r&&(i=r,r=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:d}=i??{},{onAnchor:u,setAnchors:f,sourceObjects:m}=Jo.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:m},h=Yg.createNode(t,d,v);return s&&me.isCollection(h)&&(h.flow=!0),f(),h}createPair(t,r,i={}){let n=this.createNode(t,null,i),a=this.createNode(r,null,i);return new zg.Pair(n,a)}delete(t){return tr(this.contents)?this.contents.delete(t):!1}deleteIn(t){return er.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):tr(this.contents)?this.contents.deleteIn(t):!1}get(t,r){return me.isCollection(this.contents)?this.contents.get(t,r):void 0}getIn(t,r){return er.isEmptyPath(t)?!r&&me.isScalar(this.contents)?this.contents.value:this.contents:me.isCollection(this.contents)?this.contents.getIn(t,r):void 0}has(t){return me.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return er.isEmptyPath(t)?this.contents!==void 0:me.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,r){this.contents==null?this.contents=er.collectionFromPath(this.schema,[t],r):tr(this.contents)&&this.contents.set(t,r)}setIn(t,r){er.isEmptyPath(t)?this.contents=r:this.contents==null?this.contents=er.collectionFromPath(this.schema,Array.from(t),r):tr(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 Go.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 Go.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 Gg.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=Jg.toJS(this.contents,r??"",s);if(typeof a=="function")for(let{count:l,res:d}of s.anchors.values())a(d,l);return typeof o=="function"?Kg.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 Ug.stringifyDocument(this,t)}};function tr(e){if(me.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Vu.Document=Uo});var Yr=b(Kr=>{"use strict";var Ur=class extends Error{constructor(t,r,i,n){super(),this.name=t,this.code=i,this.message=n,this.pos=r}},Ko=class extends Ur{constructor(t,r,i){super("YAMLParseError",t,r,i)}},Yo=class extends Ur{constructor(t,r,i){super("YAMLWarning",t,r,i)}},Xg=(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:y.comment=g.comment);let N=new
|
|
69
|
-
`+E.comment:l.comment=E.comment),u=E.end;continue}!o&&r.options.strict&&
|
|
70
|
-
`+R:S.comment=R,E.comment=E.comment.substring(R.length+1)}}if(!o&&!N&&!E.found){let R=k?e(r,k,E,n):t(r,E.end,N,null,E,n);l.items.push(R),u=R.range[2],
|
|
71
|
-
`+$.comment:S.comment=$.comment);let
|
|
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||w[0]===" "?(
|
|
76
|
-
`:!m&&
|
|
77
|
-
`&&(
|
|
78
|
-
|
|
79
|
-
`),u+=
|
|
80
|
-
`,m=!0):w===""?
|
|
65
|
+
`}};Kr.YAMLError=Ur;Kr.YAMLParseError=Ko;Kr.YAMLWarning=Yo;Kr.prettifyError=Xg});var Xr=b(Mu=>{"use strict";function Qg(e,{flow:t,indicator:r,next:i,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,d=s,u="",f="",m=!1,v=!1,h=null,p=null,w=null,y=null,g=null,N=null,k=null;for(let S of e)switch(v&&(S.type!=="space"&&S.type!=="newline"&&S.type!=="comma"&&a(S.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),h&&(l&&S.type!=="comment"&&S.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),S.type){case"space":!t&&(r!=="doc-start"||i?.type!=="flow-collection")&&S.source.includes(" ")&&(h=S),d=!0;break;case"comment":{d||a(S,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let $=S.source.substring(1)||" ";u?u+=f+$:u=$,f="",l=!1;break}case"newline":l?u?u+=S.source:(!N||r!=="seq-item-ind")&&(c=!0):f+=S.source,l=!0,m=!0,(p||w)&&(y=S),d=!0;break;case"anchor":p&&a(S,"MULTIPLE_ANCHORS","A node can have at most one anchor"),S.source.endsWith(":")&&a(S.offset+S.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),p=S,k??(k=S.offset),l=!1,d=!1,v=!0;break;case"tag":{w&&a(S,"MULTIPLE_TAGS","A node can have at most one tag"),w=S,k??(k=S.offset),l=!1,d=!1,v=!0;break}case r:(p||w)&&a(S,"BAD_PROP_ORDER",`Anchors and tags must be after the ${S.source} indicator`),N&&a(S,"UNEXPECTED_TOKEN",`Unexpected ${S.source} in ${t??"collection"}`),N=S,l=r==="seq-item-ind"||r==="explicit-key-ind",d=!1;break;case"comma":if(t){g&&a(S,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),g=S,l=!1,d=!1;break}default:a(S,"UNEXPECTED_TOKEN",`Unexpected ${S.type} token`),l=!1,d=!1}let E=e[e.length-1],R=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:N,spaceBefore:c,comment:u,hasNewline:m,anchor:p,tag:w,newlineAfterProp:y,end:R,start:k??R}}Mu.resolveProps=Qg});var _n=b(Wu=>{"use strict";function Xo(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(Xo(t.key)||Xo(t.value))return!0}return!1;default:return!0}}Wu.containsNewline=Xo});var Qo=b(zu=>{"use strict";var Zg=_n();function ew(e,t,r){if(t?.type==="flow-collection"){let i=t.end[0];i.indent===e&&(i.source==="]"||i.source==="}")&&Zg.containsNewline(t)&&r(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}zu.flowIndentCheck=ew});var Zo=b(Gu=>{"use strict";var Ju=C();function tw(e,t,r){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let n=typeof i=="function"?i:(a,o)=>a===o||Ju.isScalar(a)&&Ju.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,r))}Gu.mapIncludes=tw});var Zu=b(Qu=>{"use strict";var Uu=st(),rw=lt(),Ku=Xr(),iw=_n(),Yu=Qo(),nw=Zo(),Xu="All mapping items must start at the same column";function aw({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??rw.YAMLMap,s=new o(r.schema);r.atRoot&&(r.atRoot=!1);let c=i.offset,l=null;for(let d of i.items){let{start:u,key:f,sep:m,value:v}=d,h=Ku.resolveProps(u,{indicator:"explicit-key-ind",next:f??m?.[0],offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0}),p=!h.found;if(p){if(f&&(f.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==i.indent&&n(c,"BAD_INDENT",Xu)),!h.anchor&&!h.tag&&!m){l=h.end,h.comment&&(s.comment?s.comment+=`
|
|
67
|
+
`+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||iw.containsNewline(f))&&n(f??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",Xu);r.atKey=!0;let w=h.end,y=f?e(r,f,h,n):t(r,w,u,null,h,n);r.schema.compat&&Yu.flowIndentCheck(i.indent,f,n),r.atKey=!1,nw.mapIncludes(r,s.items,y)&&n(w,"DUPLICATE_KEY","Map keys must be unique");let g=Ku.resolveProps(m??[],{indicator:"map-value-ind",next:v,offset:y.range[2],onError:n,parentIndent:i.indent,startOnNewline:!f||f.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(y.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let N=v?e(r,v,g,n):t(r,c,m,null,g,n);r.schema.compat&&Yu.flowIndentCheck(i.indent,v,n),c=N.range[2];let k=new Uu.Pair(y,N);r.options.keepSourceTokens&&(k.srcToken=d),s.items.push(k)}else{p&&n(y.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),g.comment&&(y.comment?y.comment+=`
|
|
68
|
+
`+g.comment:y.comment=g.comment);let N=new Uu.Pair(y);r.options.keepSourceTokens&&(N.srcToken=d),s.items.push(N)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[i.offset,c,l??c],s}Qu.resolveBlockMap=aw});var td=b(ed=>{"use strict";var ow=ut(),sw=Xr(),cw=Qo();function lw({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??ow.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:d,value:u}of i.items){let f=sw.resolveProps(d,{indicator:"seq-item-ind",next:u,offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||u)u?.type==="block-seq"?n(f.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(s.comment=f.comment);continue}let m=u?e(r,u,f,n):t(r,f.end,d,null,f,n);r.schema.compat&&cw.flowIndentCheck(i.indent,u,n),c=m.range[2],s.items.push(m)}return s.range=[i.offset,c,l??c],s}ed.resolveBlockSeq=lw});var rr=b(rd=>{"use strict";function uw(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 d=c.substring(1)||" ";n?n+=o+d:n=d,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}}rd.resolveEnd=uw});var od=b(ad=>{"use strict";var dw=C(),fw=st(),id=lt(),hw=ut(),pw=rr(),nd=Xr(),mw=_n(),vw=Zo(),es="Block collections are not allowed within flow collections",ts=e=>e&&(e.type==="block-map"||e.type==="block-seq");function gw({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=i.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?id.YAMLMap:hw.YAMLSeq),l=new c(r.schema);l.flow=!0;let d=r.atRoot;d&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let u=i.offset+i.start.source.length;for(let p=0;p<i.items.length;++p){let w=i.items[p],{start:y,key:g,sep:N,value:k}=w,E=nd.resolveProps(y,{flow:s,indicator:"explicit-key-ind",next:g??N?.[0],offset:u,onError:n,parentIndent:i.indent,startOnNewline:!1});if(!E.found){if(!E.anchor&&!E.tag&&!N&&!k){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&&mw.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 R="";e:for(let S of y)switch(S.type){case"comma":case"space":break;case"comment":R=S.source.substring(1);break e;default:break e}if(R){let S=l.items[l.items.length-1];dw.isPair(S)&&(S=S.value??S.key),S.comment?S.comment+=`
|
|
70
|
+
`+R:S.comment=R,E.comment=E.comment.substring(R.length+1)}}if(!o&&!N&&!E.found){let R=k?e(r,k,E,n):t(r,E.end,N,null,E,n);l.items.push(R),u=R.range[2],ts(k)&&n(R.range,"BLOCK_IN_FLOW",es)}else{r.atKey=!0;let R=E.end,S=g?e(r,g,E,n):t(r,R,y,null,E,n);ts(g)&&n(S.range,"BLOCK_IN_FLOW",es),r.atKey=!1;let $=nd.resolveProps(N??[],{flow:s,indicator:"map-value-ind",next:k,offset:S.range[2],onError:n,parentIndent:i.indent,startOnNewline:!1});if($.found){if(!o&&!E.found&&r.options.strict){if(N)for(let O of N){if(O===$.found)break;if(O.type==="newline"){n(O,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}E.start<$.found.offset-1024&&n($.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else k&&("source"in k&&k.source?.[0]===":"?n(k,"MISSING_CHAR",`Missing space after : in ${s}`):n($.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let ce=k?e(r,k,$,n):$.found?t(r,$.end,N,null,$,n):null;ce?ts(k)&&n(ce.range,"BLOCK_IN_FLOW",es):$.comment&&(S.comment?S.comment+=`
|
|
71
|
+
`+$.comment:S.comment=$.comment);let et=new fw.Pair(S,ce);if(r.options.keepSourceTokens&&(et.srcToken=w),o){let O=l;vw.mapIncludes(r,O.items,S)&&n(R,"DUPLICATE_KEY","Map keys must be unique"),O.items.push(et)}else{let O=new id.YAMLMap(r.schema);O.flow=!0,O.items.push(et);let tl=(ce??S).range;O.range=[S.range[0],tl[1],tl[2]],l.items.push(O)}u=ce?ce.range[2]:$.end}}let f=o?"}":"]",[m,...v]=i.end,h=u;if(m?.source===f)h=m.offset+m.source.length;else{let p=s[0].toUpperCase()+s.substring(1),w=d?`${p} must end with a ${f}`:`${p} in block collection must be sufficiently indented and end with a ${f}`;n(u,d?"MISSING_CHAR":"BAD_INDENT",w),m&&m.source.length!==1&&v.unshift(m)}if(v.length>0){let p=pw.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}ad.resolveFlowCollection=gw});var cd=b(sd=>{"use strict";var ww=C(),yw=B(),Nw=lt(),bw=ut(),kw=Zu(),Sw=td(),Ew=od();function rs(e,t,r,i,n,a){let o=r.type==="block-map"?kw.resolveBlockMap(e,t,r,i,a):r.type==="block-seq"?Sw.resolveBlockSeq(e,t,r,i,a):Ew.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 Pw(e,t,r,i,n){let a=i.tag,o=a?t.directives.tagName(a.source,f=>n(a,"TAG_RESOLVE_FAILED",f)):null;if(r.type==="block-seq"){let{anchor:f,newlineAfterProp:m}=i,v=f&&a?f.offset>a.offset?f:a:f??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===Nw.YAMLMap.tagName&&s==="map"||o===bw.YAMLSeq.tagName&&s==="seq")return rs(e,t,r,n,o);let c=t.schema.tags.find(f=>f.tag===o&&f.collection===s);if(!c){let f=t.schema.knownTags[o];if(f?.collection===s)t.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?n(a,"BAD_COLLECTION_TYPE",`${f.tag} used for ${s} collection, but expects ${f.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),rs(e,t,r,n,o)}let l=rs(e,t,r,n,o,c),d=c.resolve?.(l,f=>n(a,"TAG_RESOLVE_FAILED",f),t.options)??l,u=ww.isNode(d)?d:new yw.Scalar(d);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}sd.composeCollection=Pw});var ns=b(ld=>{"use strict";var is=B();function xw(e,t,r){let i=t.offset,n=Cw(t,e.options.strict,r);if(!n)return{value:"",type:null,comment:"",range:[i,i,i]};let a=n.mode===">"?is.Scalar.BLOCK_FOLDED:is.Scalar.BLOCK_LITERAL,o=t.source?Rw(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,d=0;for(let h=0;h<s;++h){let[p,w]=o[h];if(w===""||w==="\r")n.indent===0&&p.length>c&&(c=p.length);else{p.length<c&&r(l+p.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(c=p.length),d=h,c===0&&!e.atRoot&&r(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=p.length+w.length+1}for(let h=o.length-1;h>=s;--h)o[h][0].length>c&&(s=h+1);let u="",f="",m=!1;for(let h=0;h<d;++h)u+=o[h][0].slice(c)+`
|
|
74
|
+
`;for(let h=d;h<s;++h){let[p,w]=o[h];l+=p.length+w.length+1;let y=w[w.length-1]==="\r";if(y&&(w=w.slice(0,-1)),w&&p.length<c){let N=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;r(l-w.length-(y?2:1),"BAD_INDENT",N),p=""}a===is.Scalar.BLOCK_LITERAL?(u+=f+p.slice(c)+w,f=`
|
|
75
|
+
`):p.length>c||w[0]===" "?(f===" "?f=`
|
|
76
|
+
`:!m&&f===`
|
|
77
|
+
`&&(f=`
|
|
78
|
+
|
|
79
|
+
`),u+=f+p.slice(c)+w,f=`
|
|
80
|
+
`,m=!0):w===""?f===`
|
|
81
81
|
`?u+=`
|
|
82
|
-
`:
|
|
83
|
-
`:(u+=
|
|
82
|
+
`:f=`
|
|
83
|
+
`:(u+=f+w,f=" ",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 Cw({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 f=1;f<n.length;++f){let m=n[f];if(!s&&(m==="-"||m==="+"))s=m;else{let v=Number(m);!o&&v?o=v:c===-1&&(c=e+f)}}c!==-1&&i(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,d="",u=n.length;for(let f=1;f<t.length;++f){let m=t[f];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,d=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:d,length:u}}function Rw(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}ld.resolveBlockScalar=xw});var os=b(dd=>{"use strict";var as=B(),Aw=rr();function _w(e,t,r){let{offset:i,type:n,source:a,end:o}=e,s,c,l=(f,m,v)=>r(i+f,m,v);switch(n){case"scalar":s=as.Scalar.PLAIN,c=Iw(a,l);break;case"single-quoted-scalar":s=as.Scalar.QUOTE_SINGLE,c=Tw(a,l);break;case"double-quoted-scalar":s=as.Scalar.QUOTE_DOUBLE,c=jw(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 d=i+a.length,u=Aw.resolveEnd(o,d,t,r);return{value:c,type:s,comment:u.comment,range:[i,d,u.offset]}}function Iw(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}`),ud(e)}function Tw(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),ud(e.slice(1,-1)).replace(/''/g,"'")}function ud(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 jw(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}=$w(e,i);r+=a,i=o}else if(n==="\\"){let a=e[++i],o=Ow[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+=Hw(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 $w(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 Ow={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
102
|
+
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Hw(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}}dd.resolveFlowScalar=_w});var pd=b(hd=>{"use strict";var Ct=C(),fd=B(),Dw=ns(),Bw=os();function Lw(e,t,r,i){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?Dw.resolveBlockScalar(e,t,i):Bw.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[Ct.SCALAR]:c?l=qw(e.schema,n,c,r,i):t.type==="scalar"?l=Fw(e,n,t,i):l=e.schema[Ct.SCALAR];let d;try{let u=l.resolve(n,f=>i(r??t,"TAG_RESOLVE_FAILED",f),e.options);d=Ct.isScalar(u)?u:new fd.Scalar(u)}catch(u){let f=u instanceof Error?u.message:String(u);i(r??t,"TAG_RESOLVE_FAILED",f),d=new fd.Scalar(n)}return d.range=s,d.source=n,a&&(d.type=a),c&&(d.tag=c),l.format&&(d.format=l.format),o&&(d.comment=o),d}function qw(e,t,r,i,n){if(r==="!")return e[Ct.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[Ct.SCALAR])}function Fw({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[Ct.SCALAR];if(r.compat){let s=r.compat.find(c=>c.default&&c.test?.test(i))??r[Ct.SCALAR];if(o.tag!==s.tag){let c=t.tagString(o.tag),l=t.tagString(s.tag),d=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",d,!0)}}return o}hd.composeScalar=Lw});var vd=b(md=>{"use strict";function Vw(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}md.emptyScalarPosition=Vw});var yd=b(cs=>{"use strict";var Mw=Ir(),Ww=C(),zw=cd(),gd=pd(),Jw=rr(),Gw=vd(),Uw={composeNode:wd,composeEmptyNode:ss};function wd(e,t,r,i){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=r,l,d=!0;switch(t.type){case"alias":l=Kw(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=gd.composeScalar(e,t,c,i),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=zw.composeCollection(Uw,e,t,r,i),s&&(l.anchor=s.source.substring(1))}catch(u){let f=u instanceof Error?u.message:String(u);i(t,"RESOURCE_EXHAUSTION",f)}break;default:{let u=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;i(t,"UNEXPECTED_TOKEN",u),d=!1}}return l??(l=ss(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&&(!Ww.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&&d&&(l.srcToken=t),l}function ss(e,t,r,i,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let d={type:"scalar",offset:Gw.emptyScalarPosition(t,r,i),indent:-1,source:""},u=gd.composeScalar(e,d,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 Kw({options:e},{offset:t,source:r,end:i},n){let a=new Mw.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=Jw.resolveEnd(i,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}cs.composeEmptyNode=ss;cs.composeNode=wd});var kd=b(bd=>{"use strict";var Yw=Gr(),Nd=yd(),Xw=rr(),Qw=Xr();function Zw(e,t,{offset:r,start:i,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new Yw.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},d=Qw.resolveProps(i,{indicator:"doc-start",next:n??a?.[0],offset:r,onError:o,parentIndent:0,startOnNewline:!0});d.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!d.hasNewline&&o(d.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?Nd.composeNode(l,n,d,o):Nd.composeEmptyNode(l,d.end,i,null,d,o);let u=c.contents.range[2],f=Xw.resolveEnd(a,u,!1,o);return f.comment&&(c.comment=f.comment),c.range=[r,u,f.offset],c}bd.composeDoc=Zw});var us=b(Pd=>{"use strict";var ey=Oi("process"),ty=Ua(),ry=Gr(),Qr=Yr(),Sd=C(),iy=kd(),ny=rr();function Zr(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 Ed(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 ls=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,i,n,a)=>{let o=Zr(r);a?this.warnings.push(new Qr.YAMLWarning(o,i,n)):this.errors.push(new Qr.YAMLParseError(o,i,n))},this.directives=new ty.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,r){let{comment:i,afterEmptyLine:n}=Ed(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(Sd.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];Sd.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:Ed(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(ey.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(r,i,n)=>{let a=Zr(t);a[0]+=r,this.onError(a,"BAD_DIRECTIVE",i,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let r=iy.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 Qr.YAMLParseError(Zr(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 Qr.YAMLParseError(Zr(t),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let r=ny.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 Qr.YAMLParseError(Zr(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 ry.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}}};Pd.Composer=ls});var Rd=b(In=>{"use strict";var ay=ns(),oy=os(),sy=Yr(),xd=Hr();function cy(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 sy.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return oy.resolveFlowScalar(e,t,i);case"block-scalar":return ay.resolveBlockScalar({options:{strict:t}},e,i)}}return null}function ly(e,t){let{implicitKey:r=!1,indent:i,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=xd.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
|
+
`),d=s.substring(0,l),u=s.substring(l+1)+`
|
|
112
|
+
`,f=[{type:"block-scalar-header",offset:a,indent:i,source:d}];return Cd(f,c)||f.push({type:"newline",offset:-1,indent:i,source:`
|
|
113
|
+
`}),{type:"block-scalar",offset:a,indent:i,props:f,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 uy(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=xd.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">":dy(e,c);break;case'"':ds(e,c,"double-quoted-scalar");break;case"'":ds(e,c,"single-quoted-scalar");break;default:ds(e,c,"scalar")}}function dy(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}];Cd(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 Cd(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 ds(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})}}}In.createScalarToken=ly;In.resolveAsScalar=cy;In.setScalarValue=uy});var _d=b(Ad=>{"use strict";var fy=e=>"type"in e?jn(e):Tn(e);function jn(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=jn(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=Tn(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=Tn(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=Tn(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 Tn({start:e,key:t,sep:r,value:i}){let n="";for(let a of e)n+=a.source;if(t&&(n+=jn(t)),r)for(let a of r)n+=a.source;return i&&(n+=jn(i)),n}Ad.stringify=fy});var $d=b(jd=>{"use strict";var fs=Symbol("break visit"),hy=Symbol("skip children"),Id=Symbol("remove item");function Rt(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Td(Object.freeze([]),e,t)}Rt.BREAK=fs;Rt.SKIP=hy;Rt.REMOVE=Id;Rt.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};Rt.parentCollection=(e,t)=>{let r=Rt.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 Td(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=Td(Object.freeze(e.concat([[n,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===fs)return fs;s===Id&&(a.items.splice(o,1),o-=1)}}typeof i=="function"&&n==="key"&&(i=i(t,e))}}return typeof i=="function"?i(t,e):i}jd.visit=Rt});var $n=b(ne=>{"use strict";var hs=Rd(),py=_d(),my=$d(),ps="\uFEFF",ms="",vs="",gs="",vy=e=>!!e&&"items"in e,gy=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function wy(e){switch(e){case ps:return"<BOM>";case ms:return"<DOC>";case vs:return"<FLOW_END>";case gs:return"<SCALAR>";default:return JSON.stringify(e)}}function yy(e){switch(e){case ps:return"byte-order-mark";case ms:return"doc-mode";case vs:return"flow-error-end";case gs: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}ne.createScalarToken=
|
|
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}ne.createScalarToken=hs.createScalarToken;ne.resolveAsScalar=hs.resolveAsScalar;ne.setScalarValue=hs.setScalarValue;ne.stringify=py.stringify;ne.visit=my.visit;ne.BOM=ps;ne.DOCUMENT=ms;ne.FLOW_END=vs;ne.SCALAR=gs;ne.isCollection=vy;ne.isScalar=gy;ne.prettyToken=wy;ne.tokenType=yy});var Ns=b(Hd=>{"use strict";var ei=$n();function Ee(e){switch(e){case void 0:case" ":case`
|
|
120
|
+
`:case"\r":case" ":return!0;default:return!1}}var Od=new Set("0123456789ABCDEFabcdef"),Ny=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),On=new Set(",[]{}"),by=new Set(` ,[]{}
|
|
121
|
+
\r `),ws=e=>!e||by.has(e),ys=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
125
|
`||i>=this.indentNext||!r&&!this.atEnd?t+i:-1}if(r==="-"||r==="."){let i=this.buffer.substr(t,3);if((i==="---"||i==="...")&&Ee(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]===
|
|
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]===ei.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 ei.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==="...")&&Ee(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&&!Ee(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===":")&&Ee(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(ws),"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("..."))&&Ee(n[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield ei.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(ws),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Ee(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
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=>Ee(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 ei.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(Ee(a)||t&&On.has(a))break;r=i}else if(Ee(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&&On.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&&On.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield ei.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(ws),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(Ee(i)||r&&On.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(;!Ee(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(Ny.has(r))r=this.buffer[++t];else if(r==="%"&&Od.has(this.buffer[t+1])&&Od.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)}};Hd.Lexer=ys});var ks=b(Dd=>{"use strict";var bs=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}}}};Dd.LineCounter=bs});var Es=b(Vd=>{"use strict";var ky=Oi("process"),Bd=$n(),Sy=Ns();function dt(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function Ld(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 Fd(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 Hn(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 ir(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 Dn(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 qd(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!dt(t.start,"explicit-key-ind")&&!dt(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Fd(t.value)?t.value.end?Dn(t.value.end,t.sep):t.value.end=t.sep:Dn(t.start,t.sep),delete t.sep)}var Ss=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 Sy.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,ky.env.LOG_TOKENS&&console.log("|",Bd.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=Bd.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"&&qd(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&&Ld(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":{Ld(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=Hn(this.peek(2)),i=ir(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)){Dn(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(dt(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(Fd(r.key)&&!dt(r.sep,"newline")){let o=ir(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(dt(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=ir(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]}):dt(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&&!dt(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)){Dn(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||dt(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=Hn(i),a=ir(n);qd(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=Hn(t),i=ir(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=Hn(t),i=ir(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())}}};Vd.Parser=Ss});var Gd=b(ri=>{"use strict";var Md=us(),Ey=Gr(),ti=Yr(),Py=so(),xy=C(),Cy=ks(),Wd=Es();function zd(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new Cy.LineCounter||null,prettyErrors:t}}function Ry(e,t={}){let{lineCounter:r,prettyErrors:i}=zd(t),n=new Wd.Parser(r?.addNewLine),a=new Md.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach(ti.prettifyError(e,r)),s.warnings.forEach(ti.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Jd(e,t={}){let{lineCounter:r,prettyErrors:i}=zd(t),n=new Wd.Parser(r?.addNewLine),a=new Md.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 ti.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(ti.prettifyError(e,r)),o.warnings.forEach(ti.prettifyError(e,r))),o}function Ay(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=Jd(e,r);if(!n)return null;if(n.warnings.forEach(a=>Py.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 _y(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 xy.isDocument(e)&&!i?e.toString(r):new Ey.Document(e,i,r).toString(r)}ri.parse=Ay;ri.parseAllDocuments=Ry;ri.parseDocument=Jd;ri.stringify=_y});var nr=b(A=>{"use strict";var Iy=us(),Ty=Gr(),jy=Wo(),Ps=Yr(),$y=Ir(),ft=C(),Oy=st(),Hy=B(),Dy=lt(),By=ut(),Ly=$n(),qy=Ns(),Fy=ks(),Vy=Es(),Bn=Gd(),Ud=Cr();A.Composer=Iy.Composer;A.Document=Ty.Document;A.Schema=jy.Schema;A.YAMLError=Ps.YAMLError;A.YAMLParseError=Ps.YAMLParseError;A.YAMLWarning=Ps.YAMLWarning;A.Alias=$y.Alias;A.isAlias=ft.isAlias;A.isCollection=ft.isCollection;A.isDocument=ft.isDocument;A.isMap=ft.isMap;A.isNode=ft.isNode;A.isPair=ft.isPair;A.isScalar=ft.isScalar;A.isSeq=ft.isSeq;A.Pair=Oy.Pair;A.Scalar=Hy.Scalar;A.YAMLMap=Dy.YAMLMap;A.YAMLSeq=By.YAMLSeq;A.CST=Ly;A.Lexer=qy.Lexer;A.LineCounter=Fy.LineCounter;A.Parser=Vy.Parser;A.parse=Bn.parse;A.parseAllDocuments=Bn.parseAllDocuments;A.parseDocument=Bn.parseDocument;A.stringify=Bn.stringify;A.visit=Ud.visit;A.visitAsync=Ud.visitAsync});import{randomUUID as qS}from"node:crypto";import{promises as Y}from"node:fs";import te from"node:path";import{execFileSync as Qp}from"child_process";import Er from"path";function tt(e,t){return Qp("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function Zp(e,t){let r=Er.normalize(e),i=Er.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function I(e){try{let t=Er.resolve(tt(e,["rev-parse","--show-toplevel"])),i=tt(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?Er.resolve(i.slice(9)):t,a=null;try{a=tt(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!Zp(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function il(e){try{tt(e,["rev-parse","--is-inside-work-tree"]);let t=tt(e,["worktree","list","--porcelain"]).split(/\r?\n/u),r=[],i=null;for(let n of t)n.startsWith("worktree ")?(i&&r.push(i),i={root:Er.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 il(e).map(t=>t.root)}function Pr(e,t){try{return tt(e,["check-ref-format","--branch",t]),tt(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function kt(e,t){try{let r=tt(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}import{randomUUID as em}from"crypto";import{promises as M}from"fs";import be from"path";function rt(e){return e!==0&&e!==0n&&e!=="0"}function Ie(e,t){return rt(e.dev)&&rt(t.dev)&&rt(e.ino)&&rt(t.ino)}function T(e,t){let r=rt(e.dev)&&rt(t.dev);if(r&&e.dev!==t.dev)return!1;let i=rt(e.ino)&&rt(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}function Hi(e,t){let r=be.relative(e,t);return r===""||!be.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${be.sep}`)}function tm(e,t){return T({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Di(e,t){return T({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function rm(e,t){return Di(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function nl(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 Jt(e){for(let t of e){let r=await M.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!tm(t,r)||await M.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function im(e,t,r){let[i,n]=await Promise.all([M.lstat(e),M.realpath(e),r?Jt(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!Di(i,t)||r&&!Hi(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function nm(e,t){let r=be.resolve(e),i=be.resolve(t);if(!Hi(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await nl(r)],a=be.relative(r,i).split(be.sep).filter(Boolean),o=r;for(let s of a){await Jt(n),o=be.join(o,s);try{await M.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await nl(o);if(!Hi(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Jt(n),n}async function am(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 om(e,t,r={}){let i=be.dirname(e),n=r.containedRoot?await nm(r.containedRoot,i):null;n||await M.mkdir(i,{recursive:!0});let a=be.join(i,`.${be.basename(e)}.${em()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await M.open(a,"wx"),s=await o.stat(),n){let[l,d]=await Promise.all([M.lstat(a),M.realpath(a)]);if(await Jt(n),!l.isFile()||l.isSymbolicLink()||!Di(s,l)||!Hi(n[0].realPath,d))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(),!Di(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 im(a,c,n),await r.beforeCommit?.(),n){await Jt(n);let l=await M.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!rm(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 am(i)}catch(l){if(await o?.close(),!n)await M.rm(a,{force:!0});else try{await Jt(n),await M.rm(a,{force:!0})}catch{}throw l}}async function re(e,t,r={}){await om(e,t,r)}async function J(e,t,r={}){await re(e,JSON.stringify(t,null,2)+`
|
|
143
|
+
`,r)}import{createHash as um}from"node:crypto";import{promises as ke}from"node:fs";import pe from"node:path";import{TextDecoder as dm}from"node:util";var sm=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),cm=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function lm(e){return e.toLowerCase().startsWith(".env")}function xr(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>lm(i))?"environment-file":r.some(i=>cm.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>sm.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}var Li=1024*1024;function Wa(e,t){let r=pe.relative(e,t);return r===""||!pe.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${pe.sep}`)}function fm(e){let t=pe.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||pe.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let r=e.toLowerCase(),i=xr(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 hm(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function pm(e,t){return T({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Bi(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Ie(r,i)?T(r,i):T(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function al(e){let t=await ke.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await ke.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function mm(e,t){let r=pe.resolve(e),i=pe.resolve(t);if(!Wa(r,i))throw new Error("Native artifact path is outside its root");let n=[await al(r)],a=r;for(let o of pe.relative(r,i).split(pe.sep).filter(Boolean)){a=pe.join(a,o);let s=await al(a);if(!Wa(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function ol(e){for(let t of e){let r=await ke.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!pm(t,r)||await ke.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function H(e){let t=fm(e.ref),r=e.maxBytes===null?null:hm(e.maxBytes??Li),i=pe.resolve(e.root,...t.split("/")),n=await mm(e.root,pe.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await ke.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 ke.realpath(i);if(!Wa(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await ke.open(i,"r");try{let[c,l,d]=await Promise.all([s.stat(),ke.lstat(i),ke.realpath(i)]);if(await ol(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||d!==o||!Bi(a,c)||!Bi(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let u=[],f=0,m=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let g=r===null?m.length:r+1-f,N=await s.read(m,0,Math.min(m.length,g),null);if(N.bytesRead===0)break;if(f+=N.bytesRead,r!==null&&f>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);u.push(Buffer.from(m.subarray(0,N.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,h,p]=await Promise.all([s.stat(),ke.lstat(i),ke.realpath(i)]);if(await ol(n),!h.isFile()||h.isSymbolicLink()||p!==o||!Bi(c,v)||!Bi(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let w=Buffer.concat(u,f),y;try{y=new dm("utf-8",{fatal:!0}).decode(w)}catch(g){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:g})}return{ref:t,size:f,hash:e.includeHash===!1?null:um("sha256").update(w).digest("hex"),text:y}}finally{await s.close()}}var uc=Sr(nr(),1);import hr from"path";var xs={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:"验证预期"}},Yd={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:"结论"}},Xd={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:"结论"}},Qd=new Map,Kd=new Map;for(let e of Object.keys(xs)){for(let[t,r]of Object.entries(xs[e]))Qd.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(Yd[e]))Kd.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(Xd[e]))Kd.set(r.toLocaleLowerCase("en-US"),t)}function My(e,t){return xs[e][t]}function Cs(e,t){return Yd[e][t]??Xd[e][t]}function Rs(e){return Qd.get(e.trim().toLocaleLowerCase("en-US"))??null}function Ln(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(r=>`# ${My(e,r)}
|
|
144
144
|
`).join(`
|
|
145
|
-
`)}function Pe(e,t,r){return e==="zh-CN"?r:t}var Cs=yr(Xt(),1);import dt from"path";var ei=64*1024,Dn=1024,Bn=64,Yd=1024,Xd=64,Rs=5,Hn={learning:!0,retrieval:!0},ef={provider:"local"},qy=12e4,Qd=6e5,Fy=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".workbuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".dsh/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".grok/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".omp/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],My=["**/.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"],Vy=[...Fy,...My].sort((e,t)=>e.localeCompare(t,"en"));var ue={include:["**/*"],exclude:[...Vy],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function Wy(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||dt.posix.isAbsolute(r)||dt.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 xt(e){let t=Wy(e,"native.artifact_root");return t.length===0?".":t.join("/")}function tf(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 Ln(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||dt.posix.isAbsolute(i)||dt.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 Me(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function rf(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 As(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>Dn)throw new Error(`${t} exceeds ${Dn} 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>Bn)throw new Error(`${t} contains more than ${Bn} wildcard tokens`);return e}function Zd(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=>As(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function xs(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 zy(e){if(e===void 0)return{...ue,include:[...ue.include],exclude:[...ue.exclude]};let t=Me(e,"native.snapshot");return{include:Zd(t.include,"native.snapshot.include",ue.include),exclude:Zd(t.exclude,"native.snapshot.exclude",ue.exclude),max_files:xs(t.max_files,ue.max_files,"native.snapshot.max_files"),max_total_bytes:xs(t.max_total_bytes,ue.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:xs(t.max_duration_ms,ue.max_duration_ms,"native.snapshot.max_duration_ms")}}function Jy(e){if(e===void 0)return;let t=Me(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=Me(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:xt(i),toArtifactRoot:xt(n),stage:a,...o?{cleanup:o}:{}}}function Gy(e){if(e===void 0)return;let t=Me(e,"native.finish");if(t.pull_request===void 0)return{};let r=Me(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(dt.posix.isAbsolute(i[0])||dt.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??qy;if(!Number.isSafeInteger(n)||n<1||n>Qd)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Qd}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function Uy(e,t={}){let r=Me(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??Rs;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=Jy(r.pending_root_move),c=Gy(r.finish);return{artifact_root:xt(i),language:rf(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:zy(r.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function Ky(e){let t=Me(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:tf(t.artifact_layout),language:rf(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n}}function Yy(e){let r=Me(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)=>Ln(i,`hook.allow_paths[${n}]`)))]}}function Xy(e){if(e===void 0)return{...Hn};let t=Me(e,"memory"),r=t.learning??Hn.learning,i=t.retrieval??Hn.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 _s(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Qy(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")||dt.posix.isAbsolute(r)||dt.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>Yd)throw new Error(`${t} exceeds ${Yd} 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>Xd)throw new Error(`${t} contains more than ${Xd} wildcard tokens`);return r}function Zy(e){let r=_s(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)=>Qy(i,`knowledge.local.include[${n}]`)))]}}function eN(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 tN(e){let t=_s(e,"knowledge.remote"),r=eN(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 rN(e){if(e===void 0)return{...ef};let t=_s(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:Zy(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:tN(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 iN(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 ti(e,t={}){let r=(0,Cs.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=iN(n.ambient_resume),o=n.hook===void 0?void 0:Yy(n.hook),s=Xy(n.memory),c=rN(n.knowledge),l=n.native===void 0?void 0:Uy(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),f=n.classic===void 0?void 0:Ky(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 qn(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...Hn},knowledge:{...ef},native:{artifact_root:xt(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:Rs,snapshot:{...ue,include:[...ue.include],exclude:[...ue.exclude]}}}}import{createHash as oN}from"crypto";import{promises as Vn}from"fs";import ft from"path";import{constants as Fn,promises as Ct}from"fs";var xe=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}};function Is(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function nf(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function ri(e){return{dev:e.dev,ino:e.ino,birthtime:Is(e)}}function Mn(e,t){let r=ri(e),i=ri(t);return _e(r,i)?T(r,i):T(r,i)&&Is(e)===Is(t)&&nf(e)===nf(t)&&e.size===t.size}async function Rt(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 Ct.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 Ct.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:ri(a)});let s=process.platform==="win32"?Fn.O_RDONLY:Fn.O_RDONLY|Fn.O_NOFOLLOW|Fn.O_NONBLOCK,c;try{c=await Ct.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,f,u]=await Promise.all([c.stat({bigint:n}),Ct.lstat(e,{bigint:n}),Ct.realpath(e)]);if(!l.isFile()||!f.isFile()||f.isSymbolicLink()||u!==o||!Mn(a,l)||!Mn(a,f))throw new xe("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:u,identity:ri(l)}),await r.hooks?.afterOpen?.();let d=[],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`);d.push(Buffer.from(v.subarray(0,g)))}await r.hooks?.beforeFinalCheck?.();let[h,p,w]=await Promise.all([c.stat({bigint:n}),Ct.lstat(e,{bigint:n}),Ct.realpath(e)]);if(!p.isFile()||p.isSymbolicLink()||w!==o||!Mn(a,h)||!Mn(a,p))throw new xe("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:w,identity:ri(h)}),{bytes:Buffer.concat(d,m),stat:h,realPath:w}}finally{await c.close()}}function aN(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Ts(e,t){let r=ft.relative(e,t);return r===""||!ft.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ft.sep}`)}async function af(e,t){let r=ft.resolve(e),i=await Vn.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return Vn.realpath(r)}async function of(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=ft.join(n,r[a]);let o;try{o=await Vn.lstat(n)}catch(f){if(aN(f))return{exists:!1,kind:"missing"};throw f}let s=ft.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 Vn.realpath(n);if(!Ts(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 Qt(e,t,r){let i=Ln(t,r.label),n=ft.resolve(e),a=await af(n,r.label),o=i.split("/"),s=ft.resolve(n,...o);if(!Ts(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await of(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function ht(e,t,r,i){let n=await Qt(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 af(n.projectRoot,i.label);return Rt(n.target,r,{...i,verify:async(o,s)=>{if(!Ts(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await of(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var ii=".comet/config.yaml";function sN(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Wn(e,t={}){return(await zn(e,t)).document}async function cN(e){try{return(await ht(e,ii,ei,{label:ii})).bytes}catch(t){if(sN(t))return null;throw t}}function lN(e){return e?{exists:!0,sha256:oN("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function zn(e,t={}){let r=await cN(e);return{document:r?ti(r.toString("utf8"),t):null,identity:lN(r)}}async function js(e){return(await Wn(e))?.config??null}var bC=16*1024;import{existsSync as cf,promises as At}from"fs";import _ from"path";import pN from"os";var Jn=".comet/config.yaml",mN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function Hs(e){try{return await At.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function vN(e){try{let t=await At.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function er(e,t){let r=_.relative(e,t);return r===""||!_.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${_.sep}`)}async function Zt(e){let t=[],r=e;for(;!await Hs(r);){let n=_.dirname(r);if(n===r)break;t.push(_.basename(r)),r=n}let i=await At.realpath(r);return _.resolve(i,...t.reverse())}async function Ds(e){try{return(await At.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Gn(e){let t=_.resolve(e);try{(await At.stat(t)).isDirectory()||(t=_.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=_.resolve(pN.homedir());for(;;){if(!(t===i&&r!==i)){let o=_.join(t,...Jn.split("/")),s=t===r||await vN(o);if(await Hs(o)&&s)return t}if(await Hs(_.join(t,".git")))return t;let a=_.dirname(t);if(a===t)return r;t=a}}function Un(e){return xt(e)}async function gN(e,t){let r=Un(t),i=_.resolve(e,...r.split("/")),n=await At.realpath(e),a=await Zt(i);if(!er(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function Ve(e,t){let r=Un(t),i=await gN(e,r),n=_.join(i,"comet");if(await Ds(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Zt(i),Zt(n)]);if(!er(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 Ds(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,f]=await Promise.all([At.realpath(s),Zt(c)]);if(!er(l,f))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:_.join(e,...Jn.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 lf(e){if(!mN.test(e))throw new Error(`Invalid Native change name: ${e}`)}function ve(e,t){lf(t);let r=_.join(e.changesRuntimeDir,t);if(!M(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function Bs(e,t){lf(t);let r=_.join(e.changesDir,t,"runtime");if(!M(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function je(e,t){let r=ve(e,t);if(cf(r))return r;let i=Bs(e,t);return cf(i)?i:r}function $e(e,t){let r=_.resolve(t);if(M(e.runtimeDir,r))return e.runtimeDir;if(M(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function M(e,t){return er(_.resolve(e),_.resolve(t))}async function D(e,t){let r=_.resolve(e),i=_.resolve(t);if(!er(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await Ds(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Zt(r),Zt(i)]);if(!er(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}function yN(e="docs",t="en"){return qn(e,t)}async function de(e){let t=(await Wn(e))?.config??null;return t?.native?t:null}async function ai(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 uf(e){let t=await Gn(e.startPath),r=await de(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${Jn} 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?Un(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??yN(i??"docs"),a=await Ve(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}import{promises as Kb}from"fs";import Yb from"path";import{AsyncLocalStorage as NN}from"async_hooks";import{randomUUID as hf}from"crypto";import{promises as ge}from"fs";import pf from"os";import Q from"path";var df=16*1024,mf=".coordinator",bN=5e3,ff=new NN,Kn=new Map;function kN(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function SN(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 vf(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 Ls(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return _e(r,i)?T(r,i):T(r,i)&&e.size===t.size}function qs(e,t){return Ls(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function We(e){let t,r;try{let i=await Rt(e,df,{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 ${df} 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:SN(JSON.parse(t.toString("utf8")),e),identity:vf(r)}}async function EN(e){return(await We(e))?.owner??null}function gf(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==pf.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 PN(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 Fs(e,t){let r=await We(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!qs(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}.${hf()}.removed`);try{await ge.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await We(i);if(!n||n.owner.id!==e.owner.id||!Ls(n.identity,e.identity))throw await PN(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await ge.rm(i,{force:!0}),"removed"}function wf(e){return{id:hf(),pid:process.pid,hostname:pf.hostname(),createdAt:new Date().toISOString(),operation:e}}async function yf(e,t){let r;try{r=await ge.open(e,"wx")}catch(i){if(i.code==="EEXIST"){let n=await EN(e);throw new Error(`Native lock is already held: ${e}${n?` by pid ${n.pid} for ${n.operation}`:""}`,{cause:i})}throw i}try{return await r.writeFile(JSON.stringify(t,null,2)+`
|
|
146
|
-
`,"utf8"),await r.sync(),
|
|
147
|
-
${
|
|
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=yf(await r.stat({bigint:!0}))}finally{await r.close()}let n=await He(e);if(!i||!n||n.owner.id!==t.id||!ea(n.identity,i))throw new Error(`Native lock changed after write: ${e}`);return n.identity}async function _N(e,t){let r=await D(e.runtimeDir,e.locksDir);await ge.mkdir(r,{recursive:!0});let i=await D(e.runtimeDir,Q.join(r,wf));await ge.mkdir(i,{recursive:!0});let n=bf(t),a=Q.join(i,`.${n.id}.tmp`),o=Q.join(i,`${n.id}.claim`);try{let s=await kf(a,n);await ge.rename(a,o);let c=await He(o);if(!c||!ea(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 ge.rm(a,{force:!0})}}async function IN(e){let t=Q.dirname(e.file),r=!1,i=Q.basename(e.file);for(let n of await ge.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=Q.join(t,n.name);if(Q.resolve(a)!==Q.resolve(e.file))try{let o=await He(a),s=Nf(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Ms(o,t);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function Sf(e){let t=await He(e.file);if(t){if(t.owner.id!==e.owner.id||!Vs(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await Ms(t,Q.dirname(e.file))}}async function TN(e,t){let r=Date.now()+PN;for(;;){let i=await _N(e,t);if(!await IN(i))return i;if(await Sf(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 jN(e){let t=Zn.get(e)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=t.then(()=>i);return Zn.set(e,n),await t,()=>{r(),Zn.get(e)===n&&Zn.delete(e)}}async function Ef(e,t,r){let i=Q.resolve(e.locksDir),n=mf.getStore();if(n?.has(i))return r();let a=await jN(i);try{let o=await TN(e,t),s=new Map(n??[]);return s.set(i,o),await mf.run(s,async()=>{try{return await r()}finally{await Sf(o)}})}finally{a()}}async function ta(e,t,r){return Ef(e,`acquire ${t}`,async()=>{let i=await D(e.runtimeDir,e.locksDir);await ge.mkdir(i,{recursive:!0});let n=await D(e.runtimeDir,Q.join(i,xN(t))),a=bf(r),o=await kf(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:i,owner:a,identity:o}})}async function ra(e){await He(e.file)&&await Ef({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${Q.basename(e.file)}`,async()=>{let t=await He(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Vs(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let r=Q.join(e.locksDir,wf);await Ms(t,r)})}function $N(e){try{return process.kill(e,0),!0}catch(t){let r=t.code;return r==="ESRCH"?!1:r==="EPERM"?!0:null}}async function Pf(e){return Nf(await He(e))}import Zs from"node:path";import fb from"node:path";import If from"node:path";import{createHash as ON}from"crypto";function Ce(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function HN(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=>Ws(i,t)).join(",")}]`}finally{t.delete(e)}}function DN(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)}:${Ws(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function Ws(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)?HN(e,t):DN(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 Ws(e,new Set)}function ae(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 ON("sha256").update(`${e}
|
|
147
|
+
${zs(t)}`).digest("hex")}var BN="comet.native.acceptance.v1";var sR=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),na=Object.freeze({maxCriteria:1024});function Rf(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 xf(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 Cf(e){return e.includes("-->")||e.includes("--!>")}function*ia(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 Qn(e)){let f=l?Pf(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=oi(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(),Cf(n,"Specification",i)}var HN=/^A[1-9]\d*$/u;function Af(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||Rf.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||Rf.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function DN(e,t){return e.localeCompare(t,"en")}function ea(e){let t=Af(e.briefSource??"brief.md","Native brief source"),r=[...e.specs??[]].sort((a,o)=>DN(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=Ws(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of r){let o=Af(a.source,`Native spec source for ${a.capability}`);i.push(...zs(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=oi(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 _f(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(!HN.test(t[r])||t[r]!==`A${r+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function If(e,t){return e.length===t.length&&e.every((r,i)=>r.source===t[i]?.source&&r.text===t[i]?.text)}var ia=yr(Xt(),1);import{promises as BN}from"node:fs";var tr="comet.native.v4",si="comet.native.local-execution.v4";var Tf=["multi-session","single-session"];function Js(){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 LN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,qN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,FN=/^A[1-9][0-9]*$/u,MN=/^[a-f0-9]{64}$/u,VN=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"]),ra=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 V(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 Us(e,t){return e===null?null:V(e,t)}function WN(e,t){let r=V(e,t);if(!MN.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function rr(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 zN(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 Oe(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function na(e,t){return Oe(e,t,(r,i)=>V(r,`${t}[${i}]`))}function _t(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function ir(e,t){let r=V(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function Ks(e,t,r=!1){let i=V(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:V(r.text,`${t}.text`,{empty:!0}),truncated:rr(r.truncated,`${t}.truncated`)}}function JN(e,t){let r=`Native spec_changes[${t}]`,i=Z(e,r);ee(i,new Set(["capability","operation","source"]),r);let n=V(i.capability,`${r}.capability`);if(!qN.test(n))throw new Error(`${r}.capability is invalid`);let a=L(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:Ks(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 GN(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=Us(r.change_branch,`${t}.change_branch`),a=Us(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 UN(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=na(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);_t(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:Us(r.next_action,`${t}.next_action`)}}function KN(e,t){let r=`Native acceptance[${t}]`,i=Z(e,r);ee(i,new Set(["id","source","text","result","reason"]),r);let n=V(i.id,`${r}.id`);if(!FN.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:Ks(i.source,`${r}.source`),text:V(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 YN(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 XN(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=na(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);_t(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:V(r.candidate_id,`${t}.candidate_id`),identity_provider:V(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:V(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:Oe(r.checks,`${t}.checks`,YN),checks_truncated:rr(r.checks_truncated,`${t}.checks_truncated`),known_limits:Oe(r.known_limits,`${t}.known_limits`,(a,o)=>we(a,`${t}.known_limits[${o}]`)),known_limits_truncated:rr(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:V(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:ir(r.submitted_at,`${t}.submitted_at`)}}function QN(e,t){let r=`Native blockers[${t}]`,i=Z(e,r);ee(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=na(i.acceptance_ids,`${r}.acceptance_ids`);return _t(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 ZN(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:V(i.id,`${r}.id`),name:we(i.name,`${r}.name`),argv_display:Oe(i.argv_display,`${r}.argv_display`,(n,a)=>we(n,`${r}.argv_display[${a}]`)),argv_truncated:rr(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:Ks(i.cwd_ref,`${r}.cwd_ref`,!0),status:L(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:zN(i.exit_code,`${r}.exit_code`),duration_ms:j(i.duration_ms,`${r}.duration_ms`)}}function eb(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=Oe(r.checks,`${t}.checks`,ZN);_t(i.map(a=>a.id),`${t}.checks IDs`);let n=V(r.identity_provider,`${t}.identity_provider`);return{candidate_id:V(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:V(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:Oe(r.risks,`${t}.risks`,(a,o)=>we(a,`${t}.risks[${o}]`)),risks_truncated:rr(r.risks_truncated,`${t}.risks_truncated`),completed_at:ir(r.completed_at,`${t}.completed_at`)}}function jf(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=na(i.unresolved_ids,`${r}.unresolved_ids`);return _t(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:ir(i.completed_at,`${r}.completed_at`)}}function tb(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 rb(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:ir(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:ir(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=tb(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 ib(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 nb(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,VN,"Native portable state"),t.schema!==tr)throw new Error(`Native portable state schema must be ${tr}`);let r=V(t.name,"Native state name");if(!LN.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=Oe(t.spec_changes,"Native spec_changes",JN);_t(i.map(s=>s.capability),"Native spec change capabilities");let n=Oe(t.acceptance,"Native acceptance",KN);_t(n.map(s=>s.id),"Native acceptance IDs");let a=Oe(t.history,"Native history",jf);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:tr,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:WN(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:GN(t.workspace),loop:UN(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:XN(t.builder_handoff),blockers:Oe(t.blockers,"Native blockers",QN),verification:t.verification===null?null:eb(t.verification),history:a,history_overflow:rb(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:rr(t.archived,"Native archived"),created_at:ir(t.created_at,"Native created_at")};return ib(o),nb(o),o}function nr(e,t){let r=oe(e),i=jf(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 ab(e,t){let r=(0,ia.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 BN.readFile(e,"utf8");return oe(ab(t,"Native portable state"))}async function aa(e,t,r={}){let i=oe(t);await re(e,(0,ia.stringify)(i),r)}var ta=new Map;async function ob(e,t){let r=ta.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);ta.set(e,a),await r;try{return await t()}finally{i(),ta.get(e)===a&&ta.delete(e)}}async function It(e){return ob(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 ra(t,i.state_version);return await aa(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await X(e.file);if(n.state_version!==t)throw new ra(t,n.state_version)}}),r})}function sb(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function pt(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(sb(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 ze="comet.native.v3",He="comet.native.v2",De="comet.native.v1";var oa="comet.native.portable-migration.v1",lb=new Set(["schema","id","change","fromSchema","status","createdAt"]),ub=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,db=/^[a-z0-9][a-z0-9-]{7,127}$/u,fb=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),hb=new Set([De,He,ze]);function pb(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function mb(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 vb(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 gb(e){return e.schema===De?ci(e):e.schema===He?li(e):ui(e)}function wb(e){return cb.posix.normalize(e.replaceAll("\\","/"))}function yb(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:wb(t.source)})}function Nb(e){return e==="shape"?"shape":"build"}function bb(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function kb(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 $f(e){let t=gb(e.state);_f(e.acceptance);let r=Nb(t.phase),i=r==="shape"?0:1,n=mb(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:tr,name:t.name,language:t.language,phase:r,status:"active",state_version:1,brief:"brief.md",spec_changes:yb(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:bb(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:pt(kb(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:Js(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function Ys(e){let t=pb(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!lb.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==oa)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!db.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!ub.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!hb.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!fb.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:oa,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:vb(t.createdAt,"Native portable migration transaction createdAt")}}function Of(e){switch(Ys(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 sa="comet.native.archive-transaction.v4",Hf="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",Sb=new RegExp(`^portable-archive-(${Hf})\\.json$`,"u"),Eb=new RegExp(`^portable-migration-(${Hf})\\.json$`,"u"),Pb=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,xb=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Cb=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),Rb=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),Ab=new Set(["capability","operation","source","content"]),Df=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Bf(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Lf(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=Bf(e,r);if(Lf(i,Ab,r),typeof i.capability!="string"||!Df.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 Ib(e){let t=Bf(e,"Native portable Archive transaction");if(Lf(t,Rb,"Native portable Archive transaction"),t.schema!==sa)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!Pb.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Df.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"||!xb.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"||!Cb.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:sa,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 ca(e){let t=Sb.exec(e);if(t)return{kind:"archive",change:t[1]};let r=Eb.exec(e);return r?{kind:"migration",change:r[1]}:null}function Tt(e,t){let r=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,i=ca(r);if(!i||i.kind!==t.kind||i.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return Xs.join(e.transactionsDir,r)}async function Qs(e,t){let r=ca(t);if(!r)return null;let i=await H({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=Xs.join(e.transactionsDir,t);if(r.kind==="archive"){let s=Ib(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=Ys(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 ar(e,t){let r=Tt(e,t);try{return await Qs(e,Xs.basename(r))}catch(i){if(i.code==="ENOENT")return null;throw i}}function qf(e){return e.kind==="archive"||e.journal.status!=="committed"}import Je from"path";import{TextDecoder as Lb}from"util";import{createHash as Tb}from"node:crypto";import{constants as la,promises as Re}from"node:fs";import Ae from"node:path";function da(e,t){let r=Ae.relative(e,t);return r===""||!Ae.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ae.sep}`)}function jb(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function $b(e,t){return T({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Ob(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function ua(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 Zs(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 Hb(e,t,r){let i=Ae.resolve(e),n=Ae.resolve(t);if(!da(i,n))throw new Error(`${r} is outside its managed root`);let a=[await Zs(i,r)],o=i;for(let s of Ae.relative(i,n).split(Ae.sep).filter(Boolean)){await jt(a,r),o=Ae.join(o,s);let c=await Zs(o,r);if(!da(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await jt(a,r),a}async function jt(e,t){for(let r of e){let i=await Re.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!$b(r,i)||await Re.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function Db(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function or(e){let t=jb(e.maxBytes),r=Ae.resolve(e.file),i=await Hb(e.root,Ae.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(f=>Zs(Ae.resolve(f),e.label)));await e.hooks?.afterParentChainCaptured?.(),await jt(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=Ob(a),s=await Re.realpath(r);if(!da(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(f=>da(f.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?la.O_RDONLY:la.O_RDONLY|la.O_NOFOLLOW|la.O_NONBLOCK,l=await Re.open(r,c);try{let f=await l.stat();await e.hooks?.afterOpen?.();let[u,d]=await Promise.all([Re.lstat(r),Re.realpath(r)]);if(await jt(i,e.label),await jt(n,e.label),!f.isFile()||!u.isFile()||u.isSymbolicLink()||d!==s||!ua(o,f)||!ua(o,u))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let m=await Db(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 jt(i,e.label),await jt(n,e.label),!h.isFile()||h.isSymbolicLink()||p!==s||!ua(o,v)||!ua(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:m,hash:Tb("sha256").update(m).digest("hex"),size:m.length}}finally{await l.close()}}var qb=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),Fb=new Set(["id","type","source","target","staged","backup"]),Mb=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),Vb=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var Vf=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var Wb=256*1024,LR=1024*1024,qR=16*1024;var FR=64*1024*1024;var zb=new Lb("utf-8",{fatal:!0});function ha(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function pa(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 Wf(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function ec(e,t){if(typeof e!="string"||e.length===0||Je.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function fa(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function Ff(e,t){if(ec(e,t),e.includes("\\")||e!==Je.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 Jb(e,t){let r=ha(e,`transaction operations[${t}]`);if(pa(r,Fb,`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`);ec(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&ec(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 zf(e){let t=ha(e,"Native Archive transaction journal");if(pa(t,Mb,"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"||!Vf.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(!Wf(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(fa(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=ha(s,`Archive transaction operations[${c}]`);if(pa(l,Vb,`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`);Ff(l.target,`Archive transaction operation ${l.id} target`);for(let f of["source","staged","backup"])l[f]!==void 0&&Ff(l[f],`Archive transaction operation ${l.id} ${f}`);if(l.expectedTargetHash!==null&&fa(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(fa(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`);fa(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 Gb(e){let t=ha(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return zf(t);if(pa(t,qb,"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"||!Vf.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!Je.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!Je.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(!Wf(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(Jb),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 Ub(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return Je.join(e.transactionsDir,t)}function Jf(e,t){let r=Ub(e,t);return{directory:r,journal:Je.join(r,"transaction.json"),events:Je.join(r,"events.jsonl"),staged:Je.join(r,"staged"),backups:Je.join(r,"backups")}}async function rc(e,t){let r=Jf(e,t);return await Promise.all(Object.values(r).map(i=>D(e.runtimeDir,i))),r}async function ic(e,t,r={}){let i=await rc(e,t),n=await or({root:e.runtimeDir,file:i.journal,maxBytes:Wb,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(zb.decode(n.bytes)),o=Gb(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function Xb(e,t,r){let i;try{i=await Kb.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 ic(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(ca(n.name))try{let a=await Qs(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(qf(a))return!0}catch{return!0}return!1}async function Qb(e,t){let r=Date.now()+5e3,i=Yb.join(e.locksDir,"root-move.lock");for(;;)try{return await Yn(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await kf(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 G(e,t,r,i){let n=await Qb(e,t);try{if(await ai(e.projectRoot),await Xb(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{await Xn(n)}}import{createHash as Zb}from"crypto";function ye(e){return Zb("sha256").update(e).digest("hex")}var cA={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024};var lA=8*1024*1024;var uA=64*1024,dA=64*1024;var fA={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},hA={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};var pA=(1n<<256n)-1n;var ok=yr(Xt(),1);var _A=4*1024*1024;var sk=null;function ck(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function Gf(e,t){return(...r)=>{let i=sk;if(i===null)return t(...r);let n=ck(`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 OA=Gf("hookWritePolicy",async e=>(await js(e))?.hook??{allow_paths:[]});var __=256*1024;var V_={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 sr from"node:path";var di=/^[a-f0-9]{64}$/u,Kf=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,uk=16*1024,nI=process.platform;function dk(e,t){let r=sr.relative(e,t);return sr.isAbsolute(r)||r===".."||r.startsWith(`..${sr.sep}`)?null:r.replaceAll("\\","/")||"."}function Yf(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function Xf(e,t){if(e.length===0||Yf(e)||e.includes("\\")||sr.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=sr.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function fk(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 nc(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||Yf(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function hk(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(nc(e.changeBranch,"Native workspace change branch"),nc(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 pk(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"||!Kf.test(t.baseCommit)||typeof t.targetCommit!="string"||!Kf.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");nc(t.targetBranch,"Native workspace Git target branch")}function mk(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"||!di.test(String(t.projectRootId))||!di.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");fk(t.capturedAt),Xf(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&&!di.test(String(t.projectRootPathId))||a&&!di.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!di.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&pk(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(hk(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 vk(e,t){return sr.join(je(e,t),"workspace.json")}function gk(e,t){let r=vk(e,t),i=$e(e,r),n=dk(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:Xf(n,"Native workspace file ref")}}async function wk(e,t){try{let r=gk(e,t),i=await H({root:r.root,ref:r.ref,maxBytes:uk});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function fi(e,t){let r=await wk(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(mk(r),r)}var Zf=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],bk=new Set(Zf),eh=new Set([...Zf,"minimum_runtime_version","revision"]),kk=new Set([...eh,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),Sk=new Set(["capability","operation","source","base_hash"]),Ek=new Set(["shape","build","verify","archive"]),Pk=new Set(["implicit","confirmed"]),xk=new Set(["pending","pass","fail"]),$t="comet-state.yaml",oc=/^[a-f0-9]{64}$/u,th=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Ck=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,sc=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"},lr=class extends Error{constructor(r,i){super(r!==ze||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"},ma=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"},hi=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"},va=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"},AI=On("en");function mi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function rh(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 lc(e){if(!th.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Rk(e){if(!th.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function ih(e,t){if(e.length===0||cr.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function Ak(e,t){let r=mi(e,`spec_changes[${t}]`);if(rh(r,Sk,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(Rk(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"&&ih(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"||!oc.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"||!oc.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 uc(e,t){if(rh(e,t,$t),typeof e.name!="string")throw new Error("Native change name is required");if(lc(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"||!Ek.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&&!Pk.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(Ak),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"||!xk.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"&&ih(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 ci(e){let t=mi(e,$t);if(t.schema!==De)throw new Error(`Expected ${De}`);return{schema:De,...uc(t,bk)}}function pi(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function ac(e,t,r){if(e===null)return null;let i=typeof e=="string"?Ck.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 Ik(e){if(e==null)return null;if(typeof e!="string"||!oc.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function Tk(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 li(e){let t=mi(e,$t);if(t.schema!==He)throw new Error(`Expected ${He}`);if(pi(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${He} minimum_runtime_version must be 2`);return{schema:He,minimum_runtime_version:2,revision:pi(t.revision,"Native v2 revision"),...uc(t,eh)}}function ui(e){let t=mi(e,$t);if(t.schema!==ze){if(t.schema===De||t.schema===He){let o=t.schema===De?ci(t):li(t);throw new sc(o.name,o.schema)}throw new lr(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=pi(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new lr(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=pi(t.revision,"Native revision"),n=uc(t,kk),a=Ik(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:ze,minimum_runtime_version:3,revision:i,verification_protocol:Tk(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:ac(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:ac(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:ac(t.partial_allowance,"Native partial_allowance","allowances")}}function jk(e){let t=mi(e,$t);if(t.schema===De){let n=ci(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${ze}`}}if(t.schema===He){let n=li(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${ze}`}}if(t.schema!==ze){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 lr(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=pi(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new lr(t.schema,r).message};let i=ui(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}function fe(e,t){lc(t);let r=cr.join(e.changesDir,t);if(!M(e.changesDir,r))throw new Error("Native change path escaped");return r}async function $k(e,t=cr.dirname(e)){let r=cr.relative(t,e).split(cr.sep).join("/"),i=await H({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,cc.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 ga(e,t){let r=cr.join(fe(e,t),$t);await D(e.nativeRoot,r);let i=jk(await $k(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}import{promises as Ei}from"node:fs";import Ke from"node:path";var yc=yr(Xt(),1);import{promises as wc}from"node:fs";import se from"node:path";import{execFileSync as Ok}from"node:child_process";var Hk=3e4,Dk=8*1024*1024,dc=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 nh(e,t){try{return Ok("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:Hk,maxBuffer:Dk,windowsHide:!0})}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new dc(e,t,i)}}function P(e,t){return nh(e,t).trim()}function vt(e){return P(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function fc(e){let t=nh(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 ah(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 U from"node:path";import{promises as Na}from"node:fs";import wa from"node:path";function oh(...e){if(e.length===0)return wa.resolve();if(wa.win32.isAbsolute(e[0])){let t=wa.win32.resolve(...e);return process.platform==="win32"?t:t.replace(/\\/gu,"/")}return wa.resolve(...e)}var ya=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};var pc="comet.native.supervisor.v2",Bk=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function Lk(e,t){let r=U.relative(U.resolve(e),U.resolve(t));return r===""||!U.isAbsolute(r)&&!r.startsWith(`..${U.sep}`)}function qk(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 Fk(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 oh(e,".worktrees",`${t}-${r}`)}function uh(e,t){return U.join(ve(e,t),"supervisor")}function dh(e,t){return U.join(uh(e,t),"state.json")}function fh(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!==pc)throw new Error(`Native Supervisor state schema must be ${pc}`);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(vi(t.integration.targetCommit,"Native Supervisor target commit"),vi(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&&vi(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(vi(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 dr(e,t){try{let r=await Na.readFile(dh(e,t),"utf8"),i=JSON.parse(r);return fh(i),i}catch(r){if(r.code==="ENOENT")return null;throw r}}async function ur(e,t){fh(t),await Na.mkdir(e.changesRuntimeDir,{recursive:!0}),await z(dh(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function vi(e,t){if(!Bk.test(e))throw new Error(`${t} must be a Git commit`)}function mc(e){return structuredClone(e)}function hh(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function ph(e){vi(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:pc,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 vc(e){let t=qk(e.parent),r=yt(e.paths.projectRoot,t);if(!r)return null;let i=yt(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=le(e.paths.projectRoot).map(o=>U.resolve(o)).find(o=>I(o).currentBranch===t);if(!n)return null;let a=ph({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 hh(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function mh(e){if(!vt(e.integration.worktree))throw new Error("Native Supervisor integration worktree must be clean");let t=P(e.integration.worktree,["rev-parse","--show-toplevel"]);if(U.resolve(t)!==U.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 Mk(e){let t=yt(e.paths.projectRoot,e.state.integration.targetBranch);if(!t||t===e.state.integration.targetCommit)return null;let r=e.state;if(mh(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=mc(r);return a.integration.headCommit=n,a.finalVerification={status:"pending",summary:null},hh(a,{kind:"target-refreshed",child:null,runId:null,summary:`Target ${r.integration.targetBranch} was refreshed before delivery`}),a.stateVersion+=1,await ur(e.paths,a),a}async function gi(e){let r=await dr(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=>U.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(!vt(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 ch({paths:e.paths,state:r,targetCommit:a});if(await lh({paths:e.paths,plan:v}),r.children.every(({status:p})=>p==="archived"))return await hc(e.paths,r.parent),{state:r,targetRoot:n,targetCommit:a};let h=mc(r);for(let p of h.children)p.status="archived";return h.stateVersion+=1,await ur(e.paths,h),await hc(e.paths,r.parent),{state:h,targetRoot:n,targetCommit:a}}let c=mh(r);if(c!==r.integration.headCommit)throw new Error("Native Supervisor integration head changed after final verification");let l=yt(e.paths.projectRoot,r.integration.targetBranch),f=(()=>{if(!l)return!1;try{return P(r.integration.worktree,["merge-base","--is-ancestor",l,c]),!0}catch{return!1}})();if(l!==c&&!f&&l!==r.integration.targetCommit&&await Mk({paths:e.paths,state:r}))throw new Error("Native Supervisor target changed; parent integration checks must be rerun before delivery");let u=await ch({paths:e.paths,state:r,targetCommit:c});l!==c&&P(n,["merge","--ff-only",r.integration.branch]);let d=P(n,["rev-parse","HEAD"]);if(d!==c)throw new Error("Native Supervisor target did not receive the verified integration head");let m=mc(r);for(let v of m.children)v.status="archived";return await lh({paths:e.paths,plan:u}),m.stateVersion+=1,await ur(e.paths,m),await hc(e.paths,r.parent),{state:m,targetRoot:n,targetCommit:d}}function vh(e,t){return U.join(uh(e,t),"cleanup.json")}function sh(e){let t=le(e.paths.projectRoot).map(s=>U.resolve(s)),r=U.resolve(process.cwd()),i=[{root:e.state.integration.worktree,branch:e.state.integration.branch},...e.state.children.map(({name:s})=>({root:Fk(e.paths.projectRoot,e.state.parent,s),branch:`comet/supervisor/${e.state.parent}/${s}`}))].map(s=>({...s,root:U.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(Lk(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=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(br(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 ch(e){let t=vh(e.paths,e.state.parent);try{let i=JSON.parse(await Na.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=sh(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=sh(e);return await z(t,r,{containedRoot:e.paths.changesRuntimeDir}),r}async function lh(e){for(let t of e.plan.worktrees){if(!le(e.paths.projectRoot).map(a=>U.resolve(a)).includes(U.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)br(e.paths.projectRoot,t)&&P(e.paths.projectRoot,["branch","-d",t])}async function hc(e,t){await Na.rm(vh(e,t),{force:!0})}function gh(e){let t=e.children.map(r=>({name:r.name,summary:r.summary,dependsOn:[...r.dependsOn],covers:[],status:r.status,phase:null,projectRoot:r.projectRoot??r.task?.projectRoot??null,message:r.blocker}));return{contractHash:null,confirmed:!0,parentBranch:e.integration.branch,children:t,readyChildren:t.filter(({status:r})=>r==="ready").map(({name:r})=>r),allDone:t.every(({status:r})=>r==="integrated"||r==="archived")}}var wh="children.yaml",fr="comet.native.children.v1",hr="comet.native.children.v2",Ph=hr,Vk=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,yh=new Set(["schema","children"]),Wk=new Set(["schema","acceptance_index","children"]),zk=new Set(["name","depends_on","covers"]),Jk=new Set(["name","summary","depends_on"]),Gk=new Set(["name","depends_on","covers"]);function ka(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function ba(e,t,r){let i=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(i.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...i.length>0?[`unexpected ${i.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${r} fields are invalid: ${a.join("; ")}`)}}function Nh(e,t){if(!Array.isArray(e)||!e.every(r=>typeof r=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((r,i)=>r.localeCompare(i,"en"))}function gc(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 Uk(e){let t=new Map(e.map(a=>[a.name,a])),r=new Set,i=new Set,n=a=>{if(!i.has(a)){if(r.has(a))throw new Error(`Native children dependency cycle includes ${a}`);r.add(a);for(let o of t.get(a).depends_on)n(o);r.delete(a),i.add(a)}};for(let a of e)n(a.name)}function bh(e,t,r=t){let i=new Set(t);for(let o of e){let s=o.covers.filter(c=>!i.has(c));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=r.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function Kk(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===Ph&&e.acceptance_index){let n=r.requiredAcceptanceIds??t??[],a=Object.keys(e.acceptance_index);i.missing=n.filter(c=>!(c in e.acceptance_index)),i.extra=a.filter(c=>!n.includes(c));let o=new Map((r.acceptanceCatalog??[]).map(c=>[c.id,c]));for(let c of n){let l=o.get(c),f=e.acceptance_index[c];l&&f&&(f.source!==l.source||f.text!==l.text)&&i.mismatched.push(c)}let s=new Set(a);for(let c of e.children)i.unknownCovers.push(...c.covers.filter(l=>!s.has(l)));return i.uncovered=a.filter(c=>!kh(e.children,c)),Sh(i)?i:null}if(e.schema===fr&&t){let n=new Set(t);for(let a of e.children)i.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return i.uncovered=t.filter(a=>!kh(e.children,a)),Sh(i)?i:null}return null}function kh(e,t){return e.some(r=>r.covers.includes(t))}function Sh(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function Nc(e){let t=new Set(e.acceptance.filter(({source:r})=>r===e.brief).map(({id:r})=>r));if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let r=[...e.history].reverse().find(({outcome:i})=>i==="fail");for(let i of r?.unresolved_ids??[])t.add(i)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...t]}}function Yk(e){let t=ka(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=ka(n,`Native children acceptance_index.${i}`);if(ba(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 Xk(e,t,r){let i=r.requiredAcceptanceIds??t??[],n=Object.keys(e),a=i.filter(c=>!(c in e)),o=n.filter(c=>!i.includes(c));if(a.length>0||o.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${a.join(", ")||"none"}; extra ${o.join(", ")||"none"}`);let s=new Map((r.acceptanceCatalog??[]).map(c=>[c.id,c]));for(let c of i){let l=s.get(c);if(!l)continue;let f=e[c];if(f.source!==l.source||f.text!==l.text){let u=["source","text"].filter(d=>f[d]!==l[d]);throw new Error(`Native children acceptance_index.${c} does not match the acceptance catalog: copy ${u.join(", ")} exactly from the current acceptance catalog`)}}}function Qk(e,t,r={}){let i=(0,yc.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=ka(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==fr&&a!==hr)throw ba(n,yh,"Native children contract"),new Error(`Native children schema must be ${fr} or ${hr}`);let o=a===fr?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(ba(n,o==="indexed-v2"?Wk:yh,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let c=n.children.map((d,m)=>{let v=ka(d,`Native child ${m}`);if(ba(v,o==="indexed-v2"?Gk:o==="summary-v2"?Jk:zk,`Native ${s} child fields (child ${m})`),typeof v.name!="string"||!Vk.test(v.name))throw new Error(`Native child ${m} name is invalid`);let h=o==="summary-v2";if(h){if(typeof v.summary!="string"||v.summary.trim().length===0)throw new Error(`Native child ${v.name} summary must be a non-empty string`);if(v.summary.length>2e3)throw new Error(`Native child ${v.name} summary exceeds 2000 characters`)}return{name:v.name,summary:h?v.summary:null,depends_on:Nh(v.depends_on,`Native child ${v.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?Nh(v.covers,`Native child ${v.name} covers`):[]}}),l=c.map(({name:d})=>d);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let f=new Set(l);for(let d of c){let m=d.depends_on.filter(v=>!f.has(v));if(m.length>0)throw new Error(`Native child ${d.name} depends on unknown child: ${m.join(", ")}`)}Uk(c);let u=r.policy==="advisory";if(a===Ph){if(o==="indexed-v2"){let d=Yk(n.acceptance_index);u||Xk(d,t,r);let m=Object.keys(d);return u||bh(c,m,m),{schema:hr,acceptance_index:d,children:c}}return{schema:hr,children:c}}return t&&!u&&bh(c,t),{schema:fr,children:c}}async function Sa(e){let t=se.join(e.changeDir,wh);try{await wc.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await H({root:e.changeDir,ref:wh}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=Qk(r.text,e.acceptanceIds,n);return{contract:a,size:r.size,drift:i?Kk(a,e.acceptanceIds,e.validation??{}):null}}function Zk(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 eS(e){let t=Zk(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 xh(e){try{let t=await H({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return eS(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function bc(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 Ch(e){let t=le(e.projectRoot);t.some(i=>gc(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 Ve(i,n.native.artifact_root),parent:gc(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function Rh(e){let t=await Ch(e.paths),r=[],i=[],n=new Map;for(let a of t){let o;try{o=await wc.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 f=await Sa({changeDir:c,...l.acceptance.length>0?{acceptanceIds:l.acceptance.map(({id:u})=>u)}:{}});!f||f.contract.schema!==fr||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})=>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:f}=c,u=l.paths,d=await kc({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 tS(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 rS(e,t){let r;try{r=await wc.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 iS(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,yc.parseDocument)(P(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:oe(a.toJS({mapAsMap:!1}))}catch{return null}}function nS(e,t,r){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==r||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${r??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function Eh(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function kc(e){let t=se.join(e.paths.changesDir,e.state.name),r=await xh(t),i=await Sa({changeDir:t,validation:Nc(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=bc({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===hr){let p=await dr(e.paths,e.state.name);if(!p){let g=e.state.workspace.target_branch??e.state.workspace.change_branch;if(g){let N=await vc({paths:e.paths,parent:e.state.name,targetBranch:g,contract:i.contract});N&&(p=N,await ur(e.paths,N))}}if(p){let g=gh(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 Ch(e.paths),c=new Set(i.contract.children.map(({name:p})=>p)),l=new Map,f=new Map;for(let p of s){let w=p.parent&&a?`refs/heads/${a}`:"HEAD";for(let y of await rS(p,c)){let g={...y,source:p,committedState:iS(p,y.file,w)};l.set(y.state.name,[...l.get(y.state.name)??[],g])}for(let y of c){let g=await tS(p,y);g&&f.set(y,[...f.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&&Eh(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=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,nS(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 w=m.get(p);if(w)return w;let y=d.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:Qe,committedState:O})=>gc(Qe.projectRoot,k.projectRoot)&&O?.name===ce&&Eh(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 aS}from"node:fs";import wi from"node:path";var oS=/[&|<>()^%"!\r\n]/u,pT=["$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 Ah(e,t){let r=t.toLowerCase();return Object.entries(e).find(([i,n])=>i.toLowerCase()===r&&n!==void 0)?.[1]}function sS(e){let t=(Ah(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function cS(e,t,r){let n=wi.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(Ah(t,"PATH")??"").split(wi.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=wi.win32.extname(e)?[e]:sS(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(c=>s?wi.join(s,c):wi.resolve(r,c)))}function _h(e,t,r){return cS(e,t,r).find(i=>aS(i))??e}function Ih(e){if(e.some(t=>oS.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}var Ni="skill-coordinated";function fS(e){return e.state_version+1}function hS(e){return e.map(t=>({...t,result:"pending",reason:null}))}function pS(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:pt(e.summary),completed_at:e.completedAt}}function Sc(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=nr(t,pS({state:t,outcome:"recovery",summary:e.reason,completedAt:r})),n=new Set(t.loop.previous_unresolved_ids),a=n.size===0?hS(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:fS(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 jh}from"node:fs";import bi from"node:path";function Ea(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Pa(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 Be(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 Th(e,t){return e===null?null:Be(e,t)}function Ca(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 mS(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 vS(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function xa(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Ec(e,t){if(e===null)return null;let r=Be(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function Pc(e,t){let r=Be(e,t);if(!bi.isAbsolute(r))throw new Error(`${t} must be absolute`);return bi.resolve(r)}function gS(e,t){let r=`Native local checks[${t}]`,i=Ea(e,r);if(Pa(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)=>Be(l,`${r}.argv[${f}]`,!0)),a=xa(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=Ec(i.startedAt,`${r}.startedAt`),s=Ec(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=Ca(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);return{id:Be(i.id,`${r}.id`),name:Be(i.name,`${r}.name`),operationId:Be(i.operationId,`${r}.operationId`),status:a,repeatable:vS(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:Ca(i.executionCount,`${r}.executionCount`),argv:n,cwd:Pc(i.cwd,`${r}.cwd`),exitCode:mS(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:Be(i.log,`${r}.log`)}}function xc(e){let t="Native local execution state",r=Ea(e,t);if(Pa(r,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),r.schema!==si)throw new Error(`Native local execution schema must be ${si}`);let i=Ea(r.workspace,"Native local workspace");Pa(i,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(r.execution!==null){let o=Ea(r.execution,"Native local execution");Pa(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=Ec(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Be(o.operationId,"Native local execution.operationId"),stage:xa(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:xa(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Th(o.executionId,"Native local execution.executionId"),status:xa(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Ca(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(gS);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:si,change:Be(r.change,"Native local change"),basedOnStateVersion:Ca(r.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:Pc(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Pc(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Th(i.branch,"Native local workspace.branch")},execution:n,checks:a}}function gt(e){return xc({schema:si,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:bi.resolve(e.projectRoot),worktreeRoot:bi.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function Cc(e){let t;try{t=await jh.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 xc(r)}async function Ge(e,t,r={}){let i=xc(t);await jh.mkdir(bi.dirname(e),{recursive:!0}),await z(e,i,r)}import{promises as wS}from"node:fs";function wt(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=xf(l,t);else if(r)Cf(l)&&(r=!1);else if(i!==null)new RegExp(`</${i}\\s*>`,"iu").test(l)&&(i=null);else{let u=xf(l,null);if(u!==null)t=u;else{let f=l.trimStart();if(f.startsWith("<!--")&&!Cf(f))r=!0;else{let m=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(f);m&&n.has(m[1].toLowerCase())&&!f.startsWith("</")&&!f.endsWith("/>")&&!new RegExp(`</${m[1]}\\s*>`,"iu").test(f)&&(i=m[1])}}}if(c===-1)break;o=c+1}}function li(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function Af(e,t,r,i=[],n="content-hash"){let a=li(r),o=t.replaceAll("\\","/").trim(),s=i.map(li);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-${ae(BN,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function _f(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 LN(e){let t=null,r=null,i=0,n=0;for(let{line:a,body:o,index:s}of ia(e)){n=s+1;let c=o?Rf(a):null;c?.level===1&&(Rs(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 Js(e,t="brief.md",r=na.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let n=LN(e);if(n===null)return[];let a=null;for(let{line:l,body:d,index:u}of ia(e)){if(u<n.start||u>=n.end)continue;let f=d?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(f===null)continue;let m=f[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:d,index:u}of ia(e)){if(u<n.start||u>=n.end)continue;let f=d?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;f&&f[1].length===a?(c(),s=[f[2]]):s!==null&&s.push(l)}return c(),_f(o.map(l=>Af("brief-example",t,l.join(`
|
|
150
|
+
`),[],i)),"Brief",i)}function Gs(e,t="spec.md",r=na.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(Af("spec-scenario",t,[o.title,...o.body].join(`
|
|
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 Ye(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function ES(e){return e.archived?Pe(e.language,"Archived","已归档"):e.phase==="verify"&&e.loop.next_action==="confirm-skill-coordinated-pass"?Pe(e.language,"Verification passed; your confirmation is required","验收通过,需要你确认"):e.phase==="archive"&&e.loop.next_action==="archive"?Pe(e.language,"Verification passed; ready to archive","验收通过,可归档"):Pe(e.language,"Verification passed","验收通过")}function PS(e){let t=e.language;return e.verification?.assurance==="semantic-verification-unavailable"?Pe(t,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查"):e.verification_result==="pass"?ES(e):e.verification_result==="blocked"?Pe(t,"Blocked","已阻塞"):e.verification_result==="fail"?Pe(t,"Failed","未通过"):Pe(t,"Pending","待处理")}function xS(e){let t=e.verification?.assurance??(e.builder_handoff?.identity_provider===Si?Si:"host-attested"),r=t===Si&&(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 CS(e,t){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let r=e.language,i=u=>Cs(r,u),n=(u,f)=>Pe(r,u,f),a=e.acceptance.map(u=>`| ${Ye(u.id)} | ${Ye(u.result)} | ${Ye(u.source)} | ${Ye(u.text)} | ${Ye(Nt(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 f=u.argv_display.map(Nt).join(" ");return`| ${Ye(Nt(u.name))} | ${Ye(f||"—")} | ${Ye(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}**: ${Nt(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=>`- ${Nt(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(", ")||"—"} | ${Ye(Nt(u.summary))} | ${u.completed_at} |`)].join(`
|
|
157
|
+
`),d=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","结果")}: **${PS(e)}**
|
|
174
|
+
- ${n("Verification status","验证情况")}: **${xS(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","摘要")}: ${Nt(e.verification.summary)}
|
|
180
180
|
|
|
181
181
|
## ${i("acceptance")}
|
|
182
182
|
|
|
@@ -200,35 +200,35 @@ ${c}
|
|
|
200
200
|
|
|
201
201
|
${l}
|
|
202
202
|
|
|
203
|
-
${
|
|
203
|
+
${d}
|
|
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 SS(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 ki(e){let t;try{t=await wS.readFile(e.file,"utf8")}catch(i){if(i.code==="ENOENT")return"missing";throw i}let r=SS(t);return r===null?"invalid":r===e.stateVersion?"aligned":"stale"}async function Si(e){await re(e.file,kS(e.state,e.supervisor))}var $h=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ES="comet-state.yaml",PS="state.json",Tj=On("en");function Ne(e,t){if(!$h.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=Ke.join(e.changesDir,t);if(!M(e.changesDir,r))throw new Error("Native change path escaped");return r}function he(e,t){return Ke.join(Ne(e,t),ES)}function Ot(e,t){return Ke.join(ve(e,t),PS)}async function Pi(e,t){try{let r=await Ei.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 Oh(e){return I(e).currentBranch}async function Le(e,t){return X(he(e,t))}async function Hh(e){let t=await It({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=Ke.join(Ne(e.paths,t.name),"verification.md");await D(e.paths.nativeRoot,r),await Ei.rm(r,{force:!0})}return t}async function xS(e){let t=Ne(e.paths,e.state.name),r=Ke.join(t,"specs"),i=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await Ei.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(!$h.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=Ke.join(t,...s.split("/")),l=await Ei.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let f=Ke.join(e.paths.specsDir,o.name,"spec.md"),u="create";try{let d=await Ei.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 CS(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 ea({briefMarkdown:r.text,specs:i})}async function Rc(e){let t=await xS(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 f=e.state.spec_changes[l];return f!==void 0&&c.capability===f.capability&&c.source===f.source&&(c.operation===f.operation||r?.has(c.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n=await CS({...e,specChanges:t}),a=e.state.acceptance.map(({source:c,text:l})=>({source:c,text:l}));if(!If(a,n))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let o;try{o=await Sa({changeDir:Ne(e.paths,e.state.name),acceptanceIds:n.map(({id:c})=>c),validation:Nc({...e.state,acceptance:n})})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return(o?bc({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 RS(e){let t=await Le(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 kc({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 Dh(e){let t=await Rh({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 RS({paths:t.candidate.paths,name:t.candidate.state.name,trigger:"v1-archive"});return{parentState:r.state,parentAdvance:r.parentAdvance}}async function Bh(e){return G(e.paths,`set portable workspace finish ${e.name}`,async()=>{let t=await Le(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 Hh({paths:e.paths,previous:t,next:r});return await Ge(Ot(e.paths,t.name),gt({portableState:i,projectRoot:e.paths.projectRoot,branch:Oh(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),i.verification!==null&&await Si({file:Ke.join(Ne(e.paths,t.name),"verification.md"),state:i}),i})}async function Lh(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let i={...nr(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:pt(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 Hh({paths:e.paths,previous:t,next:i});return await Ge(Ot(e.paths,t.name),gt({portableState:n,projectRoot:e.paths.projectRoot,branch:Oh(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function Ra(e){if(e.state.verification===null)return"not-applicable";let t=Ke.join(Ne(e.paths,e.state.name),"verification.md");return await ki({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await Si({file:t,state:e.state}),"rebuilt")}import{promises as AS}from"fs";import _S from"path";var Ac="comet.selection.v2",IS=16*1024;function Aa(e){return _S.join(e,".comet","current-change.json")}function TS(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function qh(e){return e===null||typeof e=="string"}function jS(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(!TS(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&&!qh(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Ac,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Ac)throw new Error(`current change selection schema must be ${Ac}`);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(!qh(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 Fh(e){let t;try{let i=Aa(e),{bytes:n}=await Rt(i,IS,{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",...jS(t)}}async function Mh(e){await AS.rm(Aa(e),{force:!0})}async function Vh(e,t,r){let i=await Fh(e);return i.status!=="selected"||i.selection.workflow!==t||i.selection.change!==r?!1:(await Mh(e),!0)}var Wj=16*1024;function _c(e){return Aa(e.projectRoot)}async function _a(e,t){return await ai(e.projectRoot),Vh(e.projectRoot,"native",t)}var xi=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 Ic(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function Tc(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(!M(e.archiveDir,r))throw new Error("Native Archive path escaped");return r}async function Ia(e){try{return await K.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Wh(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 zh(e,t){let r;try{r=await K.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 jc(e,t){let r=await ar(e,{kind:"archive",change:t});return r?.kind==="archive"?r.journal:null}async function Jh(e,t){return await jc(e,t)!==null||await zh(e,t)!==null}async function Ht(e,t){await K.mkdir(e.transactionsDir,{recursive:!0}),await z(Tt(e,{kind:"archive",change:t.change}),t,{containedRoot:e.runtimeDir})}async function Gh(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=>Wh(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 Ve(a,o.native.artifact_root);i.some(c=>Wh(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 K.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 ga(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 OS(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 HS(e){let t=te.join(e.paths.specsDir,e.change.capability),r=te.join(t,"spec.md");if(!M(e.paths.specsDir,r))throw new Error("Native canonical spec path escaped");if(e.change.operation==="remove"){let n;try{n=await K.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 K.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([K.realpath(e.paths.specsDir),K.realpath(t)]);if(!M(o,s))throw new Error("Native canonical capability path escaped");try{let c=await K.lstat(r);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await K.unlink(r)}catch(c){if(c.code!=="ENOENT")throw c}await K.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 K.mkdir(t,{recursive:!0}),await re(r,e.change.content,{containedRoot:e.paths.nativeRoot})}function $c(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 DS(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 BS(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($c(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function Oc(e){let t=await Le(e.paths,e.name),r=[];try{$c(t)}catch(o){r.push(o.message)}if(await jc(e.paths,e.name)===null)try{let o=await Rc({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 ki({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 Gh({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:Tc(e.paths,Ic(t)),stateVersion:t.state_version}}async function Uh(e){return G(e.paths,`archive portable change ${e.name}`,async()=>{let t=OS(e.serialFirstChange);if(t!==null&&t!==e.name)throw new Error("Native Archive --serial-first must name the change being archived");let r=await jc(e.paths,e.name),i=Ne(e.paths,e.name),n=await Ia(i),a=n?null:await zh(e.paths,e.name),o;if(n)o=await Le(e.paths,e.name);else if(r)o=await X(te.join(Tc(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 dr(e.paths,e.name);if(n&&!o.archived&&r===null){let u=await Rc({paths:e.paths,state:o});if(u.drifted){let d=u.reason??"Native confirmed requirements changed";throw await Lh({paths:e.paths,state:o,reason:d}),new Error(`${d}; Native change returned to Shape and requires confirmation`)}}let c=Tc(e.paths,r?.archive_ref??Ic(o)),l=await Ia(c);if(r&&BS(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 _a(e.paths,o.name),await K.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)$c(o);else if(o.status!=="done"||o.loop.stage!=="done")throw new Error("Native active archived state is inconsistent");let u=await Gh({paths:e.paths,state:o});if(!o.archived&&u.length>0&&t!==o.name)throw new xi(u);r={schema:sa,id:$S(),change:o.name,start_state_version:o.archived?o.state_version-1:o.state_version,archive_ref:Ic(o),status:o.archived?"state-finalized":"prepared",next_spec_index:o.archived?o.spec_changes.length:0,spec_changes:await DS(e.paths,o),created_at:new Date().toISOString()},await Ht(e.paths,r)}if(!n&&l&&r.status==="report-aligned")r={...r,status:"moved"},await Ht(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 gi({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 HS({paths:e.paths,state:o,change:r.spec_changes[u]}),r={...r,next_spec_index:u+1},await Ht(e.paths,r),await e.hooks?.afterSpecApplied?.(u);r={...r,status:"specs-applied"},await Ht(e.paths,r)}if(r.status==="specs-applied"){if(s&&!o.archived&&!f&&(s=(await gi({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 It({file:he(e.paths,o.name),expectedStateVersion:o.state_version,next:u,containedRoot:e.paths.nativeRoot})}r={...r,status:"state-finalized"},await Ht(e.paths,r),await e.hooks?.afterFinalState?.()}if(r.status==="state-finalized"){let u=await Ia(i)?i:c;if(await Si({file:te.join(u,"verification.md"),state:o,...s?{supervisor:s}:{}}),await ki({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 Ht(e.paths,r),s&&!f&&(await gi({paths:e.paths,state:s}),f=!0),await e.hooks?.afterReportAligned?.()}if(r.status==="report-aligned"){if(s&&!f&&await gi({paths:e.paths,state:s}),await K.mkdir(e.paths.archiveDir,{recursive:!0}),await Ia(c))throw new Error(`Native Archive target already exists: ${c}`);await K.rename(i,c),r={...r,status:"moved"},await Ht(e.paths,r),await e.hooks?.afterMove?.()}return r.status==="moved"&&(await _a(e.paths,o.name),await K.rm(ve(e.paths,o.name),{recursive:!0,force:!0}),await e.hooks?.afterRuntimeCleanup?.(),await K.rm(Tt(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 Dt(e,t,r){return e.language==="zh-CN"?r:t}function LS(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:Dt(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:Dt(e,"Reply A or B","回复 A 或 B"),agentInstruction:Dt(e,"Relay the two coordination choices and wait for the user decision. Do not treat a generic confirmation as a mode selection or run --confirmed without --coordination-mode.","转述这两个推进方式并等待用户选择。不要把普通“确认”视为已选择推进方式,也不要在没有 --coordination-mode 时运行 --confirmed。")};if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready")return r(Dt(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(Dt(e,"Wait only while the dispatched Verifier task is still active. If it did not start, ended without a response, or is no longer available, immediately submit the matching verifier-unavailable or verifier-execution-error input. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","仅在已派发的独立验收任务仍在运行时等待。如果任务未启动、结束后没有返回结果或已经丢失,立即提交匹配的 verifier-unavailable 或 verifier-execution-error 输入。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。"));if(e.status==="blocked"&&e.blockers.some(({resolution_action: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:null,agentInstruction:"向用户转述 message,并请用户明确选择是否接受只有自动检查的结果。不要把“继续”当作默认接受。"}:{required:!0,message:"Because independent verification is temporarily unavailable, only the automatic checks could be completed. You can accept the current check results or wait and retry when verification is available.",suggestedReply:null,agentInstruction:"Relay message and ask the user to explicitly choose whether to accept automatic checks only. Do not treat “Continue” as implicit acceptance."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="resolve-verifier-blocker")return e.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="await-user"){let n=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",a=n?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。",o=n?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return e.language==="zh-CN"?{required:!0,message:a,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:o,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}return r(Dt(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 Dc(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Ta(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function Kh(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function qS(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function FS(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function MS(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 Ci(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:Dc({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Ta("summary","--summary"),Kh(e.name,e.flag)]}}function Hc(e){return[Ci({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Ci({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function Ri(e,t){let r=FS(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:LS(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:[Ta("summary","--summary")],commandAlternatives:[Ci({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...Hc({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:Dc({change:e.name,stateVersion:e.state_version,action:"confirm-verifier-unavailable",flag:"--confirmed"}),requiredInputs:["summary","user-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:n("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...i,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Ta("summary","--summary")],commandAlternatives:[Ci({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...Hc({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:[Ta("summary","--summary")],commandAlternatives:Hc({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?Dc({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:MS({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?[qS("coordination-mode","--coordination-mode",Tf)]:[],Kh("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} ${Dt(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:[Ci({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 VS}from"node:crypto";import{promises as Ai}from"node:fs";import WS from"node:path";var Yh=["evidence.md","repair.md","archive.md","checkpoint.md"],zS="verification.md";async function JS(e,t){let r=await ar(e,{kind:"migration",change:t});return r?.kind==="migration"?r.journal:null}async function Xh(e,t){await Ai.mkdir(e.transactionsDir,{recursive:!0}),await z(Tt(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function Qh(e,t,r={}){let i=r.removeVerificationReport===!1?Yh:[...Yh,zS];await Promise.all([Ai.rm(ve(e,t),{recursive:!0,force:!0}),Ai.rm(Bs(e,t),{recursive:!0,force:!0}),...i.map(n=>Ai.rm(WS.join(fe(e,t),n),{force:!0}))])}async function Zh(e,t){await Ge(Ot(e,t.name),gt({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function ep(e,t){try{let r=await fi(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 tp(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 GS(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 ea({briefMarkdown:r.text,specs:i})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function rp(e,t){let r=await ga(e,t);if(!r.state)throw new Error(`Native legacy change ${t} is unreadable`);return r.state}async function ip(e){return G(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await JS(e.paths,e.name),r=await Pi(e.paths,e.name)?await X(he(e.paths,e.name)):null;if(!t&&r)return await Qh(e.paths,e.name,{removeVerificationReport:!1}),await Zh(e.paths,r),r;let i=null,n=null;for(t||(i=await rp(e.paths,e.name),n=await ep(e.paths,e.name),tp(e.paths,n),t={schema:oa,id:VS(),change:i.name,fromSchema:i.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await Xh(e.paths,t));;){let a=Of(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?r||(i??=await rp(e.paths,e.name),n??=await ep(e.paths,e.name),tp(e.paths,n),r=$f({state:i,acceptance:await GS({paths:e.paths,state:i}),workspace:n,migratedAt:e.now}),await aa(he(e.paths,e.name),r,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await Qh(e.paths,e.name):a.action==="commit-transaction"&&(r??=await X(he(e.paths,e.name)),await Zh(e.paths,r)),t={...t,status:a.nextStatus},await Xh(e.paths,t)}return await Ai.rm(Tt(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 np}from"node:fs";import ap from"node:path";function US(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 KS(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function YS(e,t,r){let i=new Date().toISOString(),n=e.verification===null?e:nr(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:pt(t),completed_at:i});return oe({...n,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:r?KS(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 XS(e){try{let t=await Cc(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 op(e){return G(e.paths,`recover portable change ${e.name}`,async()=>{let t=await Le(e.paths,e.name);if(t.status==="done")return await Ra({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=US(e.paths,t);if(r)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:r};let i=Ot(e.paths,e.name),n=await XS(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(d=>d.status==="planned"||d.status==="running"?{...d,status:"interrupted"}:d)},await Ge(i,n.local,{containedRoot:e.paths.runtimeDir}))),a==="available")return await Ra({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(d=>d.status==="interrupted"&&!d.repeatable):void 0;if(s){let d=Sc({state:t,reason:`Check ${s.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await It({file:he(e.paths,t.name),expectedStateVersion:t.state_version,next:d,containedRoot:e.paths.nativeRoot}),await np.rm(ap.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let m=gt({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await Ge(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",f=c||l;if(f){let d=YS(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 It({file:he(e.paths,t.name),expectedStateVersion:t.state_version,next:d,containedRoot:e.paths.nativeRoot})}let u=gt({portableState:t,projectRoot:e.paths.projectRoot,branch:I(e.paths.projectRoot).currentBranch});return await np.mkdir(ap.dirname(Ot(e.paths,t.name)),{recursive:!0}),await Ge(i,u,{containedRoot:e.paths.runtimeDir}),await Ra({paths:e.paths,state:t}),{state:t,local:u,action:f?"reverify":"resume-stable-boundary",reason:a,message:f?"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 uE,constants as dE,promises as fE}from"node:fs";import Ye from"node:path";import{execFileSync as QS}from"node:child_process";import sp from"node:path";var ZS=6e4,eE=8*1024*1024,Bc=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 mr(e,t,r={}){let i=r.timeoutMs??ZS,n=r.maxBufferBytes??eE;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=sp.resolve(r.cwd??process.cwd()),o=r.env??process.env,s=process.platform==="win32"?_h(e,o,a):e,c=sp.win32.extname(s).toLowerCase(),l=c===".bat"||c===".cmd";process.platform==="win32"&&l&&Ih(t);try{return QS(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 Bc(e,t,u,{cause:f})}}import rE from"path";var iE=["outcome","scope","nonGoals","acceptanceExamples"],K$=[...iE,"constraints","decisions","openQuestions","verificationExpectations"];function ja(e,t){return rE.join(e.specsDir,t,"spec.md")}var nE=6e4,W=class extends Error{constructor(r,i,n){super(r,n);this.pullRequest=i;this.name="NativePullRequestFinishError"}pullRequest};function Lc(e,t){try{return mr("gh",t,{cwd:e,timeoutMs:nE}).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 Fc(e,t){try{return JSON.parse(e)}catch(r){throw new Error(`${t} must be valid JSON`,{cause:r})}}function cp(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Bt(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be a non-empty string`);return e}function lp(e,t){let r=Bt(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 Oa(e,t){let r=Bt(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 up(e,t){let r=qc(e,t);if(Bt(r.state,`${t}.state`)!=="OPEN")throw new Error(`${t}.state must be OPEN`);return{number:cp(r.number,`${t}.number`),url:lp(r.url,`${t}.url`),baseBranch:Bt(r.baseRefName,`${t}.baseRefName`),headBranch:Bt(r.headRefName,`${t}.headRefName`),headSha:Oa(r.headRefOid,`${t}.headRefOid`),state:"OPEN"}}function aE(e){let t=qc(e,"pull request finish provider output.pullRequest");return{number:cp(t.number,"pull request finish provider output.pullRequest.number"),url:lp(t.url,"pull request finish provider output.pullRequest.url"),baseBranch:Bt(t.baseBranch,"pull request finish provider output.pullRequest.baseBranch"),headBranch:Bt(t.headBranch,"pull request finish provider output.pullRequest.headBranch"),headSha:Oa(t.headSha,"pull request finish provider output.pullRequest.headSha")}}function oE(e){let t=qc(Fc(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=aE(t.pullRequest);return{schema:"comet.native.pull-request-finish-result.v1",disposition:t.disposition,remoteVerified:!0,pullRequest:r}}function Mc(e){let t=Lc(e.projectRoot,["pr","list","--state","open","--base",e.baseBranch,"--head",e.headBranch,"--limit","2","--json","number,url,baseRefName,headRefName,headRefOid,state"]),r=Fc(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:up(r[0],"gh pr list output[0]")}function dp(e){let t=Lc(e.projectRoot,["pr","view",String(e.pullRequest.number),"--json","number,url,baseRefName,headRefName,headRefOid,state"]),r=up(Fc(t,"gh pr view output"),"gh pr view output"),i=Oa(e.headSha,"Native Archive head SHA");if(r.number!==e.pullRequest.number||r.url!==e.pullRequest.url)throw new W("Pull request provider result does not match the pull request observed from GitHub",r);if(r.baseBranch!==e.baseBranch)throw new W(`Pull request base branch mismatch: expected ${e.baseBranch}, got ${r.baseBranch}`,r);if(r.headBranch!==e.headBranch)throw new W(`Pull request head branch mismatch: expected ${e.headBranch}, got ${r.headBranch}`,r);if(r.headSha!==i)throw new W(`Pull request head SHA mismatch: expected ${i}, got ${r.headSha}`,r);return r}function $a(e){try{return Mc(e)}catch{return null}}function sE(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 cE(e){let t=e.existingPullRequest,r=t?"reused":"created";if(!t)try{let a=Lc(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=Mc(e),!t)throw new Error("GitHub CLI created a pull request that could not be observed uniquely");if(t.url!==a)throw new W("GitHub CLI returned a pull request URL that does not match the remotely observed pull request",t)}catch(n){if(n instanceof W)throw n;let a=$a(e);if(!a)throw new W(n.message,null,{cause:n});t=a,r="reused"}let i;try{i=dp({...e,pullRequest:t})}catch(n){throw n instanceof W?n:new W(`Final GitHub pull request verification failed: ${n.message}`,t,{cause:n})}return{provider:"github-fill",disposition:r,pullRequest:i,remoteVerified:!0}}function lE(e){let[t,...r]=e.config.command,i;try{let o=mr(t,r,{cwd:e.projectRoot,timeoutMs:e.config.timeout_ms,input:`${sE(e)}
|
|
211
|
-
`}).trim();i=
|
|
209
|
+
${Nt(e.verification.summary)}
|
|
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=fE(o)}catch(o){if(o instanceof z)throw o;let s=La(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!==qa(e.headSha,"Native Archive head SHA")){let o=La(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=pp({...e,pullRequest:n})}catch(o){if(o instanceof z)throw o;let s=La(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 mp(e){let t=zc(e);return e.config?mE({...e,existingPullRequest:t,config:e.config}):pE({...e,existingPullRequest:t})}var Ti=class extends Error{constructor(r){super(r.message??"Native workspace finish is blocked");this.result=r;this.name="NativeWorkspaceFinishError"}result};function Jc(e,t){let r=Qe.relative(e,t);return r===""||!Qe.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Qe.sep}`)}function zt(e,t){let r=Qe.relative(e,t).replaceAll("\\","/");if(!r||r===".."||r.startsWith("../")||Qe.isAbsolute(r))throw new Error(`Native workspace finish path escaped the project: ${t}`);return r}function vp(e,t){return t.some(r=>e===r||e.startsWith(`${r}/`))}function gp(e){return e.split("\0").filter(Boolean)}function yE(e,t){return gp(P(e,["ls-files","-z","--",t]))}function NE(e,t){return gp(P(e,["ls-files","--others","--exclude-standard","-z","--",t]))}function bE(e){try{if(P(e,["config","--get","user.name"])&&P(e,["config","--get","user.email"]))return}catch{}throw new Error("Native workspace finish requires configured Git user.name and user.email")}function kE(e,t){for(let r of le(e))if(I(r).currentBranch===t)return r;return null}function SE(e,t){try{yr(e,t,{timeoutMs:1e4})}catch(r){throw new Error(`${e} is required for the selected Native workspace finish`,{cause:r})}}function EE(e,t){if(!t)return;let r=t.command[0];try{if(Qe.posix.isAbsolute(r)||Qe.win32.isAbsolute(r))throw new Error("configured executable must not be an absolute path");if(/[\\/]/u.test(r)){let n=Qe.resolve(e,r);if(!Jc(e,n))throw new Error("configured executable escapes the project root");vE(n,gE.X_OK);return}yr(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 Gc(e){let{paths:t,state:r}=e,i=r.workspace;if(i.isolation==="current")return 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");let n=I(t.projectRoot);if(!n.primaryWorktreeRoot||n.currentBranch!==i.change_branch)throw new Error(`Native workspace finish requires branch ${i.change_branch} in the current registered worktree`);bE(t.projectRoot);let a=[zt(t.projectRoot,$c(t))];e.archiveDir&&a.push(zt(t.projectRoot,fe(t,r.name)),zt(t.projectRoot,e.archiveDir));let o=pc(t.projectRoot).filter(l=>!vp(l,a));if(o.length>0)throw new Error(`Native workspace finish is blocked until change-owned implementation and artifacts are committed; remaining paths: ${o.slice(0,20).join(", ")}${o.length>20?", ...":""}`);let s=i.isolation==="branch"?t.projectRoot:kE(n.primaryWorktreeRoot,i.target_branch);if(i.finish==="merge"&&i.isolation==="worktree"){if(!s)throw new Error(`Native merge finish requires a registered worktree on target branch ${i.target_branch}`);if(!wt(s))throw new Error(`Native merge target worktree is not clean: ${s}`)}let c=i.finish==="push"||i.finish==="pull-request"?ch(t.projectRoot,i.change_branch):null;return i.finish==="pull-request"&&(SE("gh",["--version"]),EE(t.projectRoot,e.pullRequestFinish)),{finish:i.finish,changeRoot:t.projectRoot,primaryRoot:n.primaryWorktreeRoot,changeBranch:i.change_branch,targetBranch:i.target_branch,targetRoot:s,remote:c,isolation:i.isolation,pullRequestFinish:e.pullRequestFinish??null}}async function PE(e){try{return await wE.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function xE(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},message:null,recoveryArgs:null}}function CE(e){if(e.isolation!=="worktree")return{performed:!1,reason:null};if(Jc(e.changeRoot,process.cwd()))return{performed:!1,reason:"invocation-working-directory-is-the-change-worktree"};try{return P(e.primaryRoot,["worktree","remove",e.changeRoot]),{performed:!0,reason:null}}catch(t){return{performed:!1,reason:`worktree-cleanup-failed: ${t.message}`}}}async function wp(e){let t=xE(e.plan),r=null;try{let i=[zt(e.paths.projectRoot,fe(e.paths,e.name)),zt(e.paths.projectRoot,e.archiveDir),...e.state.spec_changes.map(l=>zt(e.paths.projectRoot,Ba(e.paths,l.capability))),zt(e.paths.projectRoot,$c(e.paths))],n=pc(e.plan.changeRoot).filter(l=>!vp(l,i));if(n.length>0)throw new Error(`Native Archive produced or encountered paths outside the authorized finish scope: ${n.slice(0,20).join(", ")}${n.length>20?", ...":""}`);let a=[],o=new Set;for(let l of i){let d=Qe.resolve(e.paths.projectRoot,...l.split("/"));if(yE(e.plan.changeRoot,l).length>0&&a.push(l),await PE(d))for(let f of NE(e.plan.changeRoot,l))o.add(f)}if(a.length>0&&P(e.plan.changeRoot,["add","-u","--",...a]),o.size>0&&P(e.plan.changeRoot,["add","--",...o]),P(e.plan.changeRoot,["diff","--cached","--name-only","-z"])&&P(e.plan.changeRoot,["commit","-m",`chore(native): archive ${e.name}`]),t.commit=P(e.plan.changeRoot,["rev-parse","HEAD"]),!wt(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"){P(e.plan.changeRoot,["push","--set-upstream",e.plan.remote,e.plan.changeBranch]),t.pushed=!0,e.plan.finish==="pull-request"&&(t.pullRequest=mp({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=Jc(e.plan.changeRoot,process.cwd());return e.plan.isolation==="worktree"&&!l?(P(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"&&(P(c,["switch",e.plan.targetBranch]),r=c),P(c,["merge","--no-ff","--no-edit",e.plan.changeBranch]),t.merged=!0,t.targetRoot=c,t.cleanup=CE(e.plan),t}catch(i){if(i instanceof z&&i.pullRequest&&(t.pullRequestUrl=i.pullRequest.url),r!==null){let n;try{P(r,["merge","--abort"])}catch{}try{I(r).currentBranch===e.plan.targetBranch&&P(r,["switch",e.plan.changeBranch]),n=I(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 Ti(t)}}import $i from"path";import{realpathSync as NP}from"fs";var Ze={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function yp(e){return e?e.command?`${Ze.next} ${e.command}`:e.ask_user?`${Ze.next} ${e.ask_user}`:null:null}function Np(e,t){let r=[e.summary],i=yp(e.next);return i&&r.push(i),e.user_message&&r.push("",Ze.relay,e.user_message),t!==void 0&&r.push("",Ze.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> --runner-input <json-file>`,purpose:"Confirm or recover an Agent boundary, advance parent child changes, handle Supervisor task operations, or use one skill-coordinated JSON bridge for Builder handoff, check-plan dispatch, and Verifier response/error.",options:["--summary <text> Required transition or recovery summary.","--confirmed Confirm Shape or an explicitly degraded verifier-unavailable fallback before Archive.","--coordination-mode multi-session|single-session Required when confirming a multi-child Supervisor Shape.","--accept-result Accept the current skill-coordinated Verify result and make it archive-ready.","--revise-implementation Keep confirmed requirements unchanged and return Verify to Build for implementation revision.","--revise-requirements Return Verify or Archive to Shape when user-visible goals or acceptance criteria must change.","--retry-verifier Retry a
|
|
217
|
-
comet native archive <change-name> [--confirmed] [--serial-first <current-change>]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Inspect readiness without rerunning verification.","--finish <action> Persist merge, push, pull-request, or keep for an isolated workspace.","--serial-first <current-change> During execution only, confirm that this change archives before detected capability peers; the value must equal <change-name>.","--confirmed Confirm Archive when project policy requires it."],output:"Readiness plus continuation, or the completed Archive transaction and workspace finish result; Archive does not repeat verification."},doctor:{usage:"comet native doctor [<change-name>] [--repair]",purpose:"Inspect portable state, migrate a legacy active change, or rebuild its local execution overlay.",options:["--repair Apply deterministic migration or rebuild from the portable stable boundary."],output:"Health, migration or recovery details, and the continuation with the next Runner action."}});function
|
|
213
|
+
`}function bp(e,t,r){let i=[e.summary],n=yp(e.next);return n&&i.push(n),e.user_message&&i.push("",Ze.relay,e.user_message),i.push("",`${Ze.detail} ${t}`),r!==void 0&&i.push("",Ze.details,JSON.stringify(r,null,2)),i.join(`
|
|
214
|
+
`)}var RE=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 kp=1024*1024;var Ep="scoped-text-safety",AE=1,_E=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var IE="comet.native.checker-policy.v1";var WO=ae(IE,{policy:Ep,version:AE,limits:_E,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var TE=["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"],zO=new Set(TE);var OE=kp,c0=3*OE;var Pp={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:[]},DE=ye("comet-native-runtime:v3:scope-reopen"),O0=[{skillVersion:"3",skillHash:ye("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:ye("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:ye("comet-native-runtime:v1")}];var Cp=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],mH=new Set(Cp),WE=new Set([...Cp,"minimum_runtime_version","revision"]),vH=new Set([...WE,"operation"]),gH=512*1024,zE=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),wH=new Set([...zE,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);var SH={maxAcceptanceCriteria:na.maxCriteria};var RH={maxSpecs:64,maxFileBytes:Li,maxTotalBytes:4*1024*1024};import{execFile as eP}from"node:child_process";import{promisify as tP}from"node:util";var BH={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};var aD=512*1024;var ji=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};var RD=64*1024;var AD=3600*1e3;var _D=tP(eP);var Fa=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 mB={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var PB=16*1024*1024,xB=256*1024,CB=16*1024;var jB=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var kL=16*1024*1024,Va=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"},Ma=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 x(e,t,r){return e==="zh-CN"?r:t}var Uc={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function _p(e,t){return typeof e=="string"&&Uc[e]?x(t,Uc[e].en,Uc[e].zh):typeof e=="string"?e:""}function Kc(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 oP(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 Ip(e,t){let r=[];e.failed>0&&r.push(x(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(x(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(x(t,`${e.pending} pending`,`${e.pending} 项待验`));let i=x(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function Tp(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.change!="string"||t.disposition!=="continue"&&t.disposition!=="await-user"&&t.disposition!=="blocked"&&t.disposition!=="done"||t.commandArgs!==null&&t.commandArgs!==void 0&&!Array.isArray(t.commandArgs))return!1;let r=t.userCommunication;return!!(r&&typeof r=="object"&&typeof r.required=="boolean"&&(r.message===null||typeof r.message=="string")&&typeof r.agentInstruction=="string")}function Yc(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function sP(e,t,r){return e==="done"?x(r,"complete","已完成"):e==="await-user"?x(r,"waiting for a user decision","等待用户决定"):e==="blocked"?x(r,"paused: needs attention","已暂停,需要处理"):t?x(r,"waiting for a user decision","等待用户决定"):x(r,"ready to continue","可继续推进")}function cP(e,t,r){let i=Yc(e),n=[];r&&n.push(r);let a=x(i,`Change ${e.change}`,`需求 ${e.change}`),o=_p(e.phase,i),s=sP(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(Ip(t,i));let c=e.userCommunication,l=jp(e,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function jp(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:x(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:x(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(e.disposition==="blocked")return{ask_user:x(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function lP(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function uP(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=_p(e.phase,t),n=e.status==="await-user"?x(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?x(t,"paused","已暂停"):e.status==="done"?x(t,"complete","已完成"):x(t,"in progress","进行中"),a=Kc(e.acceptance)?`${x(t,", ",",")}${Ip(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function dP(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 fP(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 hP(e){if(e.healthy){let i=e.repaired?x("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):x("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=pP(e.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:x("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:x("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function pP(e){return Tp(e)?jp(e,Yc(e)):void 0}function $p(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(fP(t))return hP(t);if(lP(t)){let i=dP(t.items);return{summary:[t.total===t.items.length?x(i,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):x(i,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>uP(a,i))].join(`
|
|
215
|
+
`)}}let r=t.continuation;if(Tp(r))return cP(r,mP(t),vP(t,Yc(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:x(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 mP(e){if(Kc(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(Kc(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return oP(r.acceptance)}return null}function vP(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return x(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?x(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function Op(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"conflict":return{summary:x("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:x("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:x("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:x("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:x("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:x("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:x("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:x("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:x("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}var Hp=["--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."],Qc=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:Hp,output:"A human summary plus a NEXT step by default (RELAY TO USER blocks carry user decisions); use --json for the structured envelope, --verbose to append the raw machine projection.",examples:["comet native status --json","comet native status my-change --details --json","comet native next --help"]},init:{usage:"comet native init [--root <artifact-root>] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--root <artifact-root> Project-relative artifact root; defaults to docs.","--language en|zh-CN Language for newly generated Native artifacts."],output:"The resolved project configuration and Native paths.",examples:["comet native init --root docs --language zh-CN"]},root:{usage:"comet native root <show|move> [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move <artifact-root> Move Native artifacts and update project configuration."],output:"The current root projection or the completed move result.",examples:["comet native root show","comet native root move artifacts/native"]},"root show":{usage:"comet native root show",purpose:"Print the configured Native artifact root and resolved paths.",output:"The configured artifact root and resolved Native paths."},"root move":{usage:"comet native root move <artifact-root>",purpose:"Transactionally move Native artifacts and update project configuration.",output:"The source, destination, and committed root-move transaction result.",examples:["comet native root move artifacts/native"]},new:{usage:"comet native new <change-name> [--language en|zh-CN] [--isolation current|branch|worktree] [--change-branch <branch>] [--target-branch <branch>] [--worktree-path <path>]",purpose:"Create a portable Native change and prepare the requested branch or linked worktree.",options:["--language en|zh-CN Artifact language; defaults to project configuration.","--isolation <kind> current, branch, or worktree; defaults to current.","--change-branch <branch> Change branch; defaults to comet/<change-name>.","--target-branch <branch> Local base branch; defaults to the current branch.","--worktree-path <path> Worktree directory; defaults to .worktrees/<change-name>."],output:"The portable state, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN","comet native new session-timeout --isolation branch --target-branch main","comet native new session-timeout --isolation worktree --target-branch main"]},spec:{usage:"comet native spec remove <change-name> <capability>",purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove <change-name> <capability> Record a capability removal."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove <change-name> <capability>",purpose:"Record removal of a capability in the complete target specification.",output:"The updated portable state and continuation with the next Runner action."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"The portable state, brief, complete proposed Specs, and continuation; legacy state is reported as migration-required."},status:{usage:"comet native status [<change-name>] [--cursor <token>] [--details]",purpose:"Discover portable stable boundaries, parent child readiness, or the exact next Runner action.",options:["--cursor <token> Continue a status-list page, or a named details/history page.","--details Include one fixed-size page of acceptance, Spec, handoff, verification, history, workspace, and report details."],output:"A compact v2 status page or one compact Loop projection with local execution availability. Use --details and --cursor to read fixed-size detail pages; parent changes expose childSummary and readyChildren.",examples:["comet native status --json","comet native status session-timeout --details --json"]},select:{usage:"comet native select <change-name>",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next <change-name> --summary <text> [--confirmed] [--coordination-mode multi-session|single-session] [--accept-result|--revise-implementation|--revise-requirements|--retry-verifier|--resolve-verifier-blocker] [--max-parallel <n>] [--expected-state-version <n>] [--expected-action <action>]
|
|
216
|
+
comet native next <change-name> --runner-input <json-file>`,purpose:"Confirm or recover an Agent boundary, advance parent child changes, handle Supervisor task operations, or use one skill-coordinated JSON bridge for Builder handoff, check-plan dispatch, and Verifier response/error.",options:["--summary <text> Required transition or recovery summary.","--confirmed Confirm Shape or an explicitly degraded verifier-unavailable fallback before Archive.","--coordination-mode multi-session|single-session Required when confirming a multi-child Supervisor Shape.","--accept-result Accept the current skill-coordinated Verify result and make it archive-ready.","--revise-implementation Keep confirmed requirements unchanged and return Verify to Build for implementation revision.","--revise-requirements Return Verify or Archive to Shape when user-visible goals or acceptance criteria must change.","--retry-verifier Retry a failed or unavailable Verifier when the continuation allows it.","--resolve-verifier-blocker Resolve a semantic Verifier blocker without changing the candidate, then dispatch a new attempt.","--max-parallel <n> Supervisor task concurrency cap; defaults to 2, use 1 for serial fallback.","--expected-state-version <n> Continuation-issued guard that rejects stale public transition decisions.","--expected-action <action> Continuation-issued guard that binds the public transition decision to its intended action.","--runner-input <file> Skill-coordinated JSON: builder-handoff, dispatch-verifier, verifier-response, verifier-execution-error, or verifier-unavailable. Identity/provider/execution/candidate fields are rejected."," builder-handoff fields: kind, summary, addressed_acceptance_ids, checks, known_limits, review. review fields: status=passed, summary, reviewer_execution_ref from a separate read-only review."," dispatch-verifier fields: kind, checks (an explicitly resolved plan; [] is allowed)."," verifier-response fields: kind, response (request-checks or final-result)."," verifier-execution-error fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch."," verifier-unavailable fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch; accepted only after the explicit Runtime check plan completed and passed."," Supervisor task fields: supervisor-builder-result (child, runId, candidateCommit), supervisor-builder-failure (child, runId, reason), supervisor-verifier-result (child, runId, verdict, verification data), supervisor-reconnect (child, runId), supervisor-cancel (child, runId, reason), or supervisor-integrate (child, checks)."],output:'A compact portable state summary, explicit skill-coordinated label, Runtime-owned check results, scoped verifierDispatch, bounded request-check response, continuation.runnerAction, machine-readable continuation.inputOptions, and continuation.userCommunication with a user-ready message and Agent relay guidance. Read acceptance text and other long fields from paged status --details output. Human-readable verification statuses include "Host independently verified", "Checks completed, but your confirmation is required", "Full verification was unavailable; only automatic checks completed", and "You accepted the incomplete verification result". This generic bridge is not trusted identity attestation: a passing result waits for explicit user confirmation before Archive.',examples:['comet native next session-timeout --summary "Shape confirmed" --confirmed','comet native next session-timeout --summary "Current result accepted" --accept-result','comet native next session-timeout --summary "Implementation needs revision" --revise-implementation','comet native next session-timeout --summary "Acceptance criteria changed" --revise-requirements','comet native next session-timeout --summary "Retry verifier infrastructure" --retry-verifier','comet native next session-timeout --summary "Retry semantic verification" --resolve-verifier-blocker',"comet native next session-timeout --runner-input <temporary-json-file>"]},archive:{usage:`comet native archive <change-name> --dry-run [--finish merge|push|pull-request|keep]
|
|
217
|
+
comet native archive <change-name> [--confirmed] [--serial-first <current-change>]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Inspect readiness without rerunning verification.","--finish <action> Persist merge, push, pull-request, or keep for an isolated workspace.","--serial-first <current-change> During execution only, confirm that this change archives before detected capability peers; the value must equal <change-name>.","--confirmed Confirm Archive when project policy requires it."],output:"Readiness plus continuation, or the completed Archive transaction and workspace finish result; Archive does not repeat verification."},doctor:{usage:"comet native doctor [<change-name>] [--repair]",purpose:"Inspect portable state, migrate a legacy active change, or rebuild its local execution overlay.",options:["--repair Apply deterministic migration or rebuild from the portable stable boundary."],output:"Health, migration or recovery details, and the continuation with the next Runner action."}});function Xc(e,t){return`${e}:
|
|
218
218
|
${t.map(r=>` ${r}`).join(`
|
|
219
|
-
`)}`}function
|
|
220
|
-
${r.output}`),r.examples&&i.push("",
|
|
219
|
+
`)}`}function gP(e){let t=e.filter(i=>i!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return Qc[r]||t.length>1&&Qc[t[0]]?.subcommands?r:t[0]}function wP(e=[]){let t=gP(e),r=Qc[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.subcommands&&i.push("",Xc("Commands",r.subcommands));let n=t===""?r.options:[...r.options??[],...Hp];return n&&n.length>0&&i.push("",Xc("Options",n)),i.push("",`Output:
|
|
220
|
+
${r.output}`),r.examples&&i.push("",Xc("Examples",r.examples)),t===""&&i.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${i.join(`
|
|
221
221
|
`)}
|
|
222
|
-
`}}var
|
|
223
|
-
`}function
|
|
224
|
-
`}:e.error?{exitCode:e.exitCode,stderr:i?
|
|
225
|
-
${
|
|
222
|
+
`}}var yP=wP().usage;var FL=10*1024*1024,q=class extends Error{};function Nr(e,t){let r=e.flatMap((i,n)=>i===t?[n]:[]);if(r.length>1)throw new q(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function br(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new q(`${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 q(`${t} requires a value`);return e.splice(i,2),n}function el(e){if(e.length>0)throw new q(`Unexpected argument: ${e[0]}`)}function Bp(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new q(`${t} is required`);return r}function Zc(e,t){let r=$i.normalize(Dp(e)),i=$i.normalize(Dp(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function Dp(e){let t=$i.resolve(e);try{return NP.native(t)}catch{return t}}function bP(e){let t=$i.resolve(e),r=I(process.cwd());if(!r.isSecondaryWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null)return t;let i=I(t);return!i.isGitWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null||!Zc(r.primaryWorktreeRoot,i.primaryWorktreeRoot)||Zc(r.currentWorktreeRoot,i.currentWorktreeRoot)?t:Zc(process.cwd(),r.currentWorktreeRoot)?$i.resolve(process.cwd()):r.currentWorktreeRoot}async function Lp(e){return e?bP(e):Xn(process.cwd())}async function qp(e){let t=await hf({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function Fp(e){return JSON.stringify(e,null,2)+`
|
|
223
|
+
`}function kr(e,t,r){return{command:e,exitCode:0,data:t,text:r??Fp(t)}}function kP(e,t){if(t instanceof q)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Va)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 Ma)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof Na)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 vi)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 Ea)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof ba)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 Fa)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof ji)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 Vp(e,t){let r=kP(e,t),i=r.error;if(!i)return r;let n=Op({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function Mp(e,t,r=!1){let i=e.envelope??$p(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}})+`
|
|
224
|
+
`}:e.error?{exitCode:e.exitCode,stderr:i?bp(i,e.error.message,r?e.data:void 0):e.error.message}:i?{exitCode:e.exitCode,stdout:Np(i,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==Fp(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
|
|
225
|
+
${Ze.details}
|
|
226
226
|
${JSON.stringify(e.data,null,2)}
|
|
227
|
-
`}:{exitCode:e.exitCode,stdout:e.text}}async function
|
|
228
|
-
`);if(i){if(!h)return
|
|
229
|
-
`);if(c)h=await
|
|
230
|
-
`)}if(l.config.native.archive_confirmation==="required"&&!a)throw new q("archive requires --confirmed when native.archive_confirmation is required");if(h&&h.workspace.isolation!=="current"&&h.workspace.finish===null)throw new q("Native branch and worktree isolation require a persisted --finish preview");let p=h?await
|
|
231
|
-
`)}if(s)throw new q("--serial-first is only valid for portable Native changes");if(!i&&c)throw new q("--finish is only valid with --dry-run");if(
|
|
232
|
-
`)}async function
|
|
227
|
+
`}:{exitCode:e.exitCode,stdout:e.text}}async function Wp(e,t){let r=Bp(e,"change name"),i=Nr(e,"--dry-run"),n=br(e,"--expect-preflight"),a=Nr(e,"--confirmed"),o=br(e,"--finish"),s=br(e,"--serial-first");if(s!==void 0&&!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(s))throw new q("--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 q("--finish must be merge, push, pull-request, or keep");let l=await qp(t),d=await Ci(l.paths,r),u=d?await vt(l.paths,{kind:"archive",change:r}):null,f=d?!1:await Uh(l.paths,r);if(d||f){if(n)throw new q("Portable Native Archive does not use preflight hashes");if(i&&a)throw new q("--confirmed is only valid when executing Archive");if(i&&s)throw new q("--serial-first is only valid when executing Archive");if(!i&&c)throw new q("--finish is only valid with --dry-run");el(e);let v=d&&!i&&u?.kind!=="archive"?await lp({paths:l.paths,name:r}):null,h=v?.state??(d?await _e(l.paths,r):null);if(v?.action==="reverify"||v?.action==="await-user")return kr(i?"archive --dry-run":"archive",{archived:!1,state:v.state,recovery:v,continuation:_i(v.state)},`${v.message}
|
|
228
|
+
`);if(i){if(!h)return kr("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}
|
|
229
|
+
`);if(c)h=await qh({paths:l.paths,name:r,finish:c});else if(h.workspace.isolation!=="current"&&h.workspace.finish===null)throw new q("Native branch and worktree isolation require --finish with --dry-run");let N=await Lc({paths:l.paths,name:r}),k=_i(h),E=N.capabilityPeers.length>0?{...k,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["choose-first-archive"],runnerAction:{...k.runnerAction,kind:"none"}}:k;return kr("archive --dry-run",{...N,workspaceFinish:h.workspace.finish,continuation:E},`Native Archive preview: ${N.ready?"ready":"blocked"}
|
|
230
|
+
`)}if(l.config.native.archive_confirmation==="required"&&!a)throw new q("archive requires --confirmed when native.archive_confirmation is required");if(h&&h.workspace.isolation!=="current"&&h.workspace.finish===null)throw new q("Native branch and worktree isolation require a persisted --finish preview");let p=h?await Gc({paths:l.paths,state:h,pullRequestFinish:l.config.native.finish?.pull_request}):null,w;try{w=await Yh({paths:l.paths,name:r,...s?{serialFirstChange:s}:{}})}catch(N){if(!(N instanceof Ri)||!h)throw N;let k=await Lc({paths:l.paths,name:r}),E=N.peers.length>0?["comet","native","archive",r,"--confirmed","--serial-first",r]:["comet","native","archive",r,"--confirmed"];return{command:"archive",exitCode:73,data:{...k,workspaceFinish:h.workspace.finish,workspaceFinishResult:null,continuation:{disposition:"await-user",reason:N.message,commandArgs:E,inputOptions:N.peers.length>0?["serial-first-change"]:[],runnerAction:null}},error:{code:"conflict",message:N.message}}}h=w.state,!p&&h.workspace.isolation!=="current"&&(p=await Gc({paths:l.paths,state:h,archiveDir:w.archiveDir,pullRequestFinish:l.config.native.finish?.pull_request}));let y=null;if(p)try{y=await wp({paths:l.paths,state:w.state,name:r,archiveDir:w.archiveDir,transactionId:w.transactionId,plan:p})}catch(N){if(!(N instanceof Ti))throw N;return{command:"archive",exitCode:73,data:{...w,workspaceFinish:w.state.workspace.finish,workspaceFinishResult:N.result,continuation:{disposition:"blocked",reason:N.message,commandArgs:N.result.recoveryArgs,inputOptions:[],runnerAction:null}},error:{code:"conflict",message:N.message}}}let g=y?.merged===!0?await Bh({childPaths:l.paths,childState:w.state}):null;return kr("archive",{...w,workspaceFinish:w.state.workspace.finish,workspaceFinishResult:y,...g?{parentAdvance:g.parentAdvance}:{},...g?.parentState?{parentState:g.parentState}:{},continuation:_i(g?.parentState??w.state)},`Archived Native change ${r} to ${w.archiveDir}
|
|
231
|
+
`)}if(s)throw new q("--serial-first is only valid for portable Native changes");if(!i&&c)throw new q("--finish is only valid with --dry-run");if(el(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 op({paths:l.paths,name:r});return kr("archive",{migration:{from:"legacy",to:m.schema,completed:!0},state:m,continuation:_i(m)},`Migrated Native change ${r}; follow the returned portable continuation before Archive
|
|
232
|
+
`)}async function zp(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{Nr(n,"--json"),Nr(n,"--verbose"),c=br(n,"--project-root");let u=[...n,...a],f=await Lp(c);l=await t(u,f)}catch(u){l=Vp(e,u)}let d=Mp(l,o,s);return d.stdout&&process.stdout.write(d.stdout),d.stderr&&process.stderr.write(d.stderr+(d.stderr.endsWith(`
|
|
233
233
|
`)?"":`
|
|
234
|
-
`)),
|
|
234
|
+
`)),d.exitCode}process.exitCode=await zp("archive",Wp);
|